def _update(self, cache_only): """ update entitlement certificates """ logger.info(_('Updating Subscription Management repositories.')) # XXX: Importing inline as you must be root to read the config file from subscription_manager.identity import ConsumerIdentity cert_file = str(ConsumerIdentity.certpath()) key_file = str(ConsumerIdentity.keypath()) identity = inj.require(inj.IDENTITY) # In containers we have no identity, but we may have entitlements inherited # from the host, which need to generate a redhat.repo. if identity.is_valid(): try: connection.UEPConnection(cert_file=cert_file, key_file=key_file) # FIXME: catchall exception except Exception: # log logger.info(_("Unable to connect to Subscription Management Service")) return else: logger.info(_("Unable to read consumer identity")) if config.in_container(): logger.info(_("Subscription Manager is operating in container mode.")) if not cache_only: cert_action_invoker = EntCertActionInvoker() cert_action_invoker.update() repo_action_invoker = RepoActionInvoker(cache_only=cache_only) repo_action_invoker.update()
def clean_all_data(backup=True): consumer_dir = cfg.get('rhsm', 'consumerCertDir') if backup: if consumer_dir[-1] == "/": consumer_dir_backup = consumer_dir[0:-1] + ".old" else: consumer_dir_backup = consumer_dir + ".old" # Delete backup dir if it exists: shutil.rmtree(consumer_dir_backup, ignore_errors=True) # Copy current consumer dir: log.debug("Backing up %s to %s.", consumer_dir, consumer_dir_backup) shutil.copytree(consumer_dir, consumer_dir_backup) # FIXME FIXME # Delete current consumer certs: for path in [ConsumerIdentity.keypath(), ConsumerIdentity.certpath()]: if (os.path.exists(path)): log.debug("Removing identity cert: %s" % path) os.remove(path) require(IDENTITY).reload() # Delete all entitlement certs rather than the directory itself: ent_cert_dir = cfg.get('rhsm', 'entitlementCertDir') if os.path.exists(ent_cert_dir): for f in glob.glob("%s/*.pem" % ent_cert_dir): certpath = os.path.join(ent_cert_dir, f) log.debug("Removing entitlement cert: %s" % f) os.remove(certpath) else: log.warn("Entitlement cert directory does not exist: %s" % ent_cert_dir) # Subclasses of cache.CacheManager have a @classmethod delete_cache # for deleting persistent caches cache.ProfileManager.delete_cache() cache.InstalledProductsManager.delete_cache() cache.SyspurposeCache.delete_cache() # FIXME: implement as dbus client to facts service DeleteCache() once implemented #Facts.delete_cache() # WrittenOverridesCache is also a subclass of cache.CacheManager, but # it is deleted in RepoActionInvoker.delete_repo_file() below. # StatusCache subclasses have a a per instance cache varable # and delete_cache is an instance method, so we need to call # the delete_cache on the instances created in injectioninit. require(ENTITLEMENT_STATUS_CACHE).delete_cache() require(PROD_STATUS_CACHE).delete_cache() require(POOL_STATUS_CACHE).delete_cache() require(OVERRIDE_STATUS_CACHE).delete_cache() require(RELEASE_STATUS_CACHE).delete_cache() RepoActionInvoker.delete_repo_file() log.info("Cleaned local data")
def update(conduit, cache_only): """ Update entitlement certificates """ if os.getuid() != 0: conduit.info( 3, 'Not root, Subscription Management repositories not updated') return conduit.info(3, 'Updating Subscription Management repositories.') identity = inj.require(inj.IDENTITY) if not identity.is_valid(): conduit.info(3, "Unable to read consumer identity") # In containers we have no identity, but we may have entitlements inherited # from the host, which need to generate a redhat.repo. if config.in_container(): conduit.info(3, "Subscription Manager is operating in container mode.") if not cache_only and not config.in_container(): cert_action_invoker = EntCertActionInvoker(locker=YumRepoLocker( conduit=conduit)) cert_action_invoker.update() if cache_only or config.in_container(): repo_action_invoker = RepoActionInvoker( cache_only=cache_only, locker=YumRepoLocker(conduit=conduit)) repo_action_invoker.update()
def update(conduit, cache_only): """ update entitlement certificates """ if os.getuid() != 0: conduit.info(3, 'Not root, Subscription Management repositories not updated') return conduit.info(3, 'Updating Subscription Management repositories.') # XXX: Importing inline as you must be root to read the config file from subscription_manager.identity import ConsumerIdentity cert_file = ConsumerIdentity.certpath() key_file = ConsumerIdentity.keypath() identity = inj.require(inj.IDENTITY) # In containers we have no identity, but we may have entitlements inherited # from the host, which need to generate a redhat.repo. if identity.is_valid(): try: connection.UEPConnection(cert_file=cert_file, key_file=key_file) #FIXME: catchall exception except Exception: # log conduit.info(2, "Unable to connect to Subscription Management Service") return else: conduit.info(3, "Unable to read consumer identity") if config.in_container(): conduit.info(3, "Subscription Manager is operating in container mode.") rl = RepoActionInvoker(cache_only=cache_only, locker=YumRepoLocker(conduit=conduit)) rl.update()
def update(conduit, cache_only): """ update entitlement certificates """ if os.getuid() != 0: conduit.info( 3, 'Not root, Subscription Management repositories not updated') return conduit.info(3, 'Updating Subscription Management repositories.') # XXX: Importing inline as you must be root to read the config file from subscription_manager.identity import ConsumerIdentity cert_file = ConsumerIdentity.certpath() key_file = ConsumerIdentity.keypath() identity = inj.require(inj.IDENTITY) if not identity.is_valid(): conduit.info(3, "Unable to read consumer identity") return try: connection.UEPConnection(cert_file=cert_file, key_file=key_file) #FIXME: catchall exception except Exception: # log conduit.info(2, "Unable to connect to Subscription Management Service") return rl = RepoActionInvoker(cache_only=cache_only) rl.update()
def _update(self, cache_only): """ update entitlement certificates """ logger.info(_('Updating Subscription Management repositories.')) # XXX: Importing inline as you must be root to read the config file from subscription_manager.identity import ConsumerIdentity cert_file = str(ConsumerIdentity.certpath()) key_file = str(ConsumerIdentity.keypath()) identity = inj.require(inj.IDENTITY) # In containers we have no identity, but we may have entitlements inherited # from the host, which need to generate a redhat.repo. if identity.is_valid(): try: connection.UEPConnection(cert_file=cert_file, key_file=key_file) # FIXME: catchall exception except Exception: # log logger.info( _("Unable to connect to Subscription Management Service")) return else: logger.info(_("Unable to read consumer identity")) if config.in_container(): logger.info( _("Subscription Manager is operating in container mode.")) rl = RepoActionInvoker(cache_only=cache_only) rl.update()
def _update(cache_only): """ Update entitlement certificates and redhat.repo :param cache_only: is True, when rhsm.full_refresh_on_yum is set to 0 in rhsm.conf """ logger.info(_('Updating Subscription Management repositories.')) identity = inj.require(inj.IDENTITY) if not identity.is_valid(): logger.info(_("Unable to read consumer identity")) if config.in_container(): logger.info( _("Subscription Manager is operating in container mode.")) if cache_only is True: log.debug('DNF subscription-manager operates in cache-only mode') if not cache_only and not config.in_container(): log.debug( 'Trying to update entitlement certificates and redhat.repo') cert_action_invoker = EntCertActionInvoker() cert_action_invoker.update() else: log.debug('Skipping updating of entitlement certificates') log.debug('Generating redhat.repo') repo_action_invoker = RepoActionInvoker(cache_only=cache_only) repo_action_invoker.update()
def update(conduit, cache_only): """ update entitlement certificates """ if os.getuid() != 0: conduit.info(3, 'Not root, Subscription Management repositories not updated') return conduit.info(3, 'Updating Subscription Management repositories.') # XXX: Importing inline as you must be root to read the config file from subscription_manager.identity import ConsumerIdentity cert_file = ConsumerIdentity.certpath() key_file = ConsumerIdentity.keypath() identity = inj.require(inj.IDENTITY) if not identity.is_valid(): conduit.info(3, "Unable to read consumer identity") return try: uep = connection.UEPConnection(cert_file=cert_file, key_file=key_file) #FIXME: catchall exception except Exception: # log conduit.info(2, "Unable to connect to Subscription Management Service") return rl = RepoActionInvoker(uep=uep, cache_only=cache_only) rl.update()
def test_get_repos(self): self._stub_content() repo_action_invoker = RepoActionInvoker() repos = repo_action_invoker.get_repos() if len(repos) == 0: self.fail( "get_repos() should have a set of Repo's, but the set is empty." )
def test_is_managed(self): self._stub_content() repo_action_invoker = RepoActionInvoker() repo_label = 'a_test_repo' im_result = repo_action_invoker.is_managed(repo_label) self.assertTrue(im_result)
def clean_all_data(backup=True): consumer_dir = cfg.get('rhsm', 'consumerCertDir') if backup: if consumer_dir[-1] == "/": consumer_dir_backup = consumer_dir[0:-1] + ".old" else: consumer_dir_backup = consumer_dir + ".old" # Delete backup dir if it exists: shutil.rmtree(consumer_dir_backup, ignore_errors=True) # Copy current consumer dir: log.debug("Backing up %s to %s.", consumer_dir, consumer_dir_backup) shutil.copytree(consumer_dir, consumer_dir_backup) # FIXME FIXME # Delete current consumer certs: for path in [ConsumerIdentity.keypath(), ConsumerIdentity.certpath()]: if (os.path.exists(path)): log.debug("Removing identity cert: %s" % path) os.remove(path) require(IDENTITY).reload() # Delete all entitlement certs rather than the directory itself: ent_cert_dir = cfg.get('rhsm', 'entitlementCertDir') if os.path.exists(ent_cert_dir): for f in glob.glob("%s/*.pem" % ent_cert_dir): certpath = os.path.join(ent_cert_dir, f) log.debug("Removing entitlement cert: %s" % f) os.remove(certpath) else: log.warn("Entitlement cert directory does not exist: %s" % ent_cert_dir) # Subclasses of cache.CacheManager have a @classmethod delete_cache # for deleting persistent caches cache.ProfileManager.delete_cache() cache.InstalledProductsManager.delete_cache() if SyncedStore is not None: SyncedStore(None).update_cache({}) # FIXME: implement as dbus client to facts service DeleteCache() once implemented # Facts.delete_cache() # WrittenOverridesCache is also a subclass of cache.CacheManager, but # it is deleted in RepoActionInvoker.delete_repo_file() below. # StatusCache subclasses have a a per instance cache varable # and delete_cache is an instance method, so we need to call # the delete_cache on the instances created in injectioninit. require(ENTITLEMENT_STATUS_CACHE).delete_cache() require(SYSTEMPURPOSE_COMPLIANCE_STATUS_CACHE).delete_cache() require(PROD_STATUS_CACHE).delete_cache() require(POOL_STATUS_CACHE).delete_cache() require(OVERRIDE_STATUS_CACHE).delete_cache() require(RELEASE_STATUS_CACHE).delete_cache() RepoActionInvoker.delete_repo_file() log.debug("Cleaned local data")
def repo_hook(self): """Update yum repos.""" try: # NOTE: this may need a lock rl = RepoActionInvoker() rl.update() except Exception, e: log.debug(e) log.debug("Failed to update repos")
def test_get_repos(self): self._stub_content(include_content_access=True) repo_action_invoker = RepoActionInvoker() repos = repo_action_invoker.get_repos() self.assertEqual(2, len(repos), 'Should produce two repos') matching_repos = [repo for repo in repos if repo.id == 'a_test_repo'] self.assertEqual(1, len(matching_repos), 'Should only produce one repo for "a_test_repo"') repo = matching_repos[0] certpath = repo.get('sslclientcert') self.assertNotEqual(certpath, self.stub_content_access_cert.path)
class Overrides(object): def __init__(self): self.cp_provider = inj.require(inj.CP_PROVIDER) self.cache = inj.require(inj.OVERRIDE_STATUS_CACHE) self.repo_lib = RepoActionInvoker(cache_only=True) def get_overrides(self, consumer_uuid): return self._build_from_json( self.cache.load_status(self._getuep(), consumer_uuid)) def add_overrides(self, consumer_uuid, overrides): return self._build_from_json(self._getuep().setContentOverrides( consumer_uuid, self._add(overrides))) def remove_overrides(self, consumer_uuid, overrides): return self._delete_overrides(consumer_uuid, self._remove(overrides)) def remove_all_overrides(self, consumer_uuid, repos): return self._delete_overrides(consumer_uuid, self._remove_all(repos)) def update(self, overrides): self.cache.server_status = [ override.to_json() for override in overrides ] self.cache.write_cache() self.repo_lib.update() def _delete_overrides(self, consumer_uuid, override_data): return self._build_from_json(self._getuep().deleteContentOverrides( consumer_uuid, override_data)) def _add(self, overrides): return [override.to_json() for override in overrides] def _remove(self, overrides): return [{ 'contentLabel': override.repo_id, 'name': override.name } for override in overrides] def _remove_all(self, repos): if repos: return [{'contentLabel': repo} for repo in repos] else: return None def _build_from_json(self, override_json): return [ Override.from_json(override_dict) for override_dict in override_json ] def _getuep(self): return self.cp_provider.get_consumer_auth_cp()
def _get_libset(self): self.entcertlib = EntCertActionInvoker() self.repolib = RepoActionInvoker() lib_set = [self.entcertlib, self.repolib] return lib_set
def clean_all_data(backup=True): consumer_dir = cfg.get('rhsm', 'consumerCertDir') if backup: if consumer_dir[-1] == "/": consumer_dir_backup = consumer_dir[0:-1] + ".old" else: consumer_dir_backup = consumer_dir + ".old" # Delete backup dir if it exists: shutil.rmtree(consumer_dir_backup, ignore_errors=True) # Copy current consumer dir: log.debug("Backing up %s to %s.", consumer_dir, consumer_dir_backup) shutil.copytree(consumer_dir, consumer_dir_backup) # FIXME FIXME # Delete current consumer certs: for path in [ConsumerIdentity.keypath(), ConsumerIdentity.certpath()]: if (os.path.exists(path)): log.debug("Removing identity cert: %s" % path) os.remove(path) require(IDENTITY).reload() # Delete all entitlement certs rather than the directory itself: ent_cert_dir = cfg.get('rhsm', 'entitlementCertDir') if os.path.exists(ent_cert_dir): for f in glob.glob("%s/*.pem" % ent_cert_dir): certpath = os.path.join(ent_cert_dir, f) log.debug("Removing entitlement cert: %s" % f) os.remove(certpath) else: log.warn("Entitlement cert directory does not exist: %s" % ent_cert_dir) cache.ProfileManager.delete_cache() cache.InstalledProductsManager.delete_cache() Facts.delete_cache() # Must also delete in-memory cache require(ENTITLEMENT_STATUS_CACHE).delete_cache() require(PROD_STATUS_CACHE).delete_cache() require(OVERRIDE_STATUS_CACHE).delete_cache() RepoActionInvoker.delete_repo_file() log.info("Cleaned local data")
class Overrides(object): def __init__(self): self.cp_provider = inj.require(inj.CP_PROVIDER) self.cache = inj.require(inj.OVERRIDE_STATUS_CACHE) self.repo_lib = RepoActionInvoker(cache_only=True) def get_overrides(self, consumer_uuid): return self._build_from_json(self.cache.load_status(self._getuep(), consumer_uuid)) def add_overrides(self, consumer_uuid, overrides): return self._build_from_json(self._getuep().setContentOverrides(consumer_uuid, self._add(overrides))) def remove_overrides(self, consumer_uuid, overrides): return self._delete_overrides(consumer_uuid, self._remove(overrides)) def remove_all_overrides(self, consumer_uuid, repos): return self._delete_overrides(consumer_uuid, self._remove_all(repos)) def update(self, overrides): self.cache.server_status = [override.to_json() for override in overrides] self.cache.write_cache() self.repo_lib.update() def _delete_overrides(self, consumer_uuid, override_data): return self._build_from_json(self._getuep().deleteContentOverrides(consumer_uuid, override_data)) def _add(self, overrides): return [override.to_json() for override in overrides] def _remove(self, overrides): return [{'contentLabel': override.repo_id, 'name': override.name} for override in overrides] def _remove_all(self, repos): if repos: return [{'contentLabel': repo} for repo in repos] else: return None def _build_from_json(self, override_json): return [Override.from_json(override_dict) for override_dict in override_json] def _getuep(self): return self.cp_provider.get_consumer_auth_cp()
def clean_all_data(backup=True): consumer_dir = cfg.get('rhsm', 'consumerCertDir') if backup: if consumer_dir[-1] == "/": consumer_dir_backup = consumer_dir[0:-1] + ".old" else: consumer_dir_backup = consumer_dir + ".old" # Delete backup dir if it exists: shutil.rmtree(consumer_dir_backup, ignore_errors=True) # Copy current consumer dir: log.info("Backing up %s to %s." % (consumer_dir, consumer_dir_backup)) shutil.copytree(consumer_dir, consumer_dir_backup) # FIXME FIXME # Delete current consumer certs: for path in [ConsumerIdentity.keypath(), ConsumerIdentity.certpath()]: if (os.path.exists(path)): log.debug("Removing identity cert: %s" % path) os.remove(path) require(IDENTITY).reload() # Delete all entitlement certs rather than the directory itself: ent_cert_dir = cfg.get('rhsm', 'entitlementCertDir') if os.path.exists(ent_cert_dir): for f in glob.glob("%s/*.pem" % ent_cert_dir): certpath = os.path.join(ent_cert_dir, f) log.debug("Removing entitlement cert: %s" % f) os.remove(certpath) else: log.warn("Entitlement cert directory does not exist: %s" % ent_cert_dir) cache.ProfileManager.delete_cache() cache.InstalledProductsManager.delete_cache() Facts.delete_cache() # Must also delete in-memory cache require(ENTITLEMENT_STATUS_CACHE).delete_cache() require(PROD_STATUS_CACHE).delete_cache() require(OVERRIDE_STATUS_CACHE).delete_cache() RepoActionInvoker.delete_repo_file() log.info("Cleaned local data")
def _set_enable_for_yum_repositories(setting, *repo_ids): invoker = RepoActionInvoker() repos = invoker.get_repos() repos_to_change = [] for r in repo_ids: matches = set([repo for repo in repos if fnmatch.fnmatch(repo.id, r)]) repos_to_change.extend(matches) if len(repos_to_change) == 0: return 0 # The cache should be primed at this point by the invoker.get_repos() cache = inj.require(inj.OVERRIDE_STATUS_CACHE) identity = inj.require(inj.IDENTITY) cp_provider = inj.require(inj.CP_PROVIDER) if identity.is_valid() and cp_provider.get_consumer_auth_cp( ).supports_resource('content_overrides'): overrides = [{ 'contentLabel': repo.id, 'name': 'enabled', 'value': setting } for repo in repos_to_change] cp = cp_provider.get_consumer_auth_cp() results = cp.setContentOverrides(identity.uuid, overrides) cache = inj.require(inj.OVERRIDE_STATUS_CACHE) # Update the cache with the returned JSON cache.server_status = results cache.write_cache() invoker.update() else: for repo in repos_to_change: repo['enabled'] = setting repo_file = RepoFile() repo_file.read() for repo in repos_to_change: repo_file.update(repo) repo_file.write() return len(repos_to_change)
def _set_enable_for_yum_repositories(setting, *repo_ids): invoker = RepoActionInvoker() repos = invoker.get_repos() repos_to_change = [] for r in repo_ids: matches = set([repo for repo in repos if fnmatch.fnmatch(repo.id, r)]) repos_to_change.extend(matches) if len(repos_to_change) == 0: return 0 # The cache should be primed at this point by the invoker.get_repos() cache = inj.require(inj.OVERRIDE_STATUS_CACHE) identity = inj.require(inj.IDENTITY) cp_provider = inj.require(inj.CP_PROVIDER) if identity.is_valid() and cp_provider.get_consumer_auth_cp().supports_resource('content_overrides'): overrides = [{'contentLabel': repo.id, 'name': 'enabled', 'value': setting} for repo in repos_to_change] cp = cp_provider.get_consumer_auth_cp() results = cp.setContentOverrides(identity.uuid, overrides) cache = inj.require(inj.OVERRIDE_STATUS_CACHE) # Update the cache with the returned JSON cache.server_status = results cache.write_cache() invoker.update() else: for repo in repos_to_change: repo['enabled'] = setting repo_file = YumRepoFile() repo_file.read() for repo in repos_to_change: repo_file.update(repo) repo_file.write() return len(repos_to_change)
def _do_command(self): cdn_url = conf['rhsm']['baseurl'] # note: parse_baseurl_info will populate with defaults if not found (cdn_hostname, cdn_port, _cdn_prefix) = parse_baseurl_info(cdn_url) # Base CliCommand has already setup proxy info etc self.cp_provider.set_content_connection_info(cdn_hostname=cdn_hostname, cdn_port=cdn_port) self.release_backend = ReleaseBackend() self.assert_should_be_registered() repo_action_invoker = RepoActionInvoker() if self.options.unset: self.cp.updateConsumer(self.identity.uuid, release="") repo_action_invoker.update() print(_("Release preference has been unset")) elif self.options.release is not None: # get first list of available releases from the server try: releases = self.release_backend.get_releases() except MultipleReleaseProductsError as err: log.error("Getting releases failed: {err}".format(err=err)) system_exit(os.EX_CONFIG, err.translated_message()) if self.options.release in releases: self.cp.updateConsumer( self.identity.uuid, release=self.options.release ) else: system_exit(os.EX_DATAERR, _( "No releases match '{release}'. " "Consult 'release --list' for a full listing.").format( release=self.options.release)) repo_action_invoker.update() print(_("Release set to: {release}").format(release=self.options.release)) elif self.options.list: try: releases = self.release_backend.get_releases() except MultipleReleaseProductsError as err: log.error("Getting releases failed: {err}".format(err=err)) system_exit(os.EX_CONFIG, err.translated_message()) if len(releases) == 0: system_exit(os.EX_CONFIG, _( "No release versions available, please check subscriptions.")) print("+-------------------------------------------+") print(" {label} ".format(label=_('Available Releases'))) print("+-------------------------------------------+") for release in releases: print(release) else: self.show_current_release()
def _get_libset(self): self.entcertlib = EntCertActionInvoker() self.repolib = RepoActionInvoker() self.factlib = FactsActionInvoker() self.profilelib = PackageProfileActionInvoker() self.installedprodlib = InstalledProductsActionInvoker() self.idcertlib = IdentityCertActionInvoker() # WARNING: order is important here, we need to update a number # of things before attempting to autoheal, and we need to autoheal # before attempting to fetch our certificates: lib_set = [ self.entcertlib, self.idcertlib, self.repolib, self.factlib, self.profilelib, self.installedprodlib ] return lib_set
def test_get_repos(self): self._stub_content() repo_action_invoker = RepoActionInvoker() repos = repo_action_invoker.get_repos() if len(repos) == 0: self.fail("get_repos() should have a set of Repo's, but the set is empty.")
def __init__(self): self.cp_provider = inj.require(inj.CP_PROVIDER) self.cache = inj.require(inj.OVERRIDE_STATUS_CACHE) self.repo_lib = RepoActionInvoker(cache_only=True)
def _do_command(self): self._reconcile_list_options() rc = 0 if not manage_repos_enabled(): print(_("Repositories disabled by configuration.")) return rc # Pull down any new entitlements and refresh the entitlements directory if self.identity.is_valid(): cert_action_client = ActionClient(skips=[PackageProfileActionInvoker]) cert_action_client.update() self._request_validity_check() if self.is_registered(): supported_resources = get_supported_resources() self.use_overrides = "content_overrides" in supported_resources else: self.use_overrides = False # specifically, yum repos, for now. rl = RepoActionInvoker() repos = rl.get_repos() if self.options.repo_actions is not None: rc = self._set_repo_status(repos, rl, self.options.repo_actions) if self.identity.is_valid(): profile_action_client = ProfileActionClient() profile_action_client.update() if self.list: if len(repos): # TODO: Perhaps this should be abstracted out as well...? def filter_repos(repo): disabled_values = ["false", "0"] repo_enabled = repo["enabled"].lower() show_enabled = self.list_enabled and repo_enabled not in disabled_values show_disabled = self.list_disabled and repo_enabled in disabled_values return show_enabled or show_disabled repos = list(filter(filter_repos, repos)) if len(repos): print("+----------------------------------------------------------+") print(_(" Available Repositories in {file}").format(file=rl.get_repo_file())) print("+----------------------------------------------------------+") for repo in repos: print( columnize( REPOS_LIST, echo_columnize_callback, repo.id, repo["name"], repo["baseurl"], repo["enabled"], ) + "\n" ) else: print(_("There were no available repositories matching the specified criteria.")) else: print(_("This system has no repositories available through subscriptions.")) return rc
def _set_repo_status(self, repos, repo_action_invoker, repo_actions): """ Given a list of repo actions (tuple of enable/disable and repo ID), build a list without duplicates to send to the server. """ rc = 0 # Maintain a dict of repo to enabled/disabled status. This allows us # to remove dupes and send only the last action specified by the user # on the command line. Items will be overwritten as we process the CLI # arguments in order. repos_to_modify = {} if not len(repos): print(_("This system has no repositories available through subscriptions.")) return 1 for (status, repoid) in repo_actions: matches = set([repo for repo in repos if fnmatch.fnmatch(repo.id, repoid)]) if not matches: rc = 1 print( _( "Error: '{repoid}' does not match a valid repository ID. " 'Use "subscription-manager repos --list" to see valid repositories.' ).format(repoid=repoid) ) log.warning("'{repoid}' does not match a valid repository ID.".format(repoid=repoid)) # Overwrite repo if it's already in the dict, we want the last # match to be the one sent to server. for repo in matches: repos_to_modify[repo] = status if repos_to_modify: # The cache should be primed at this point by the # repo_action_invoker.get_repos() cache = inj.require(inj.OVERRIDE_STATUS_CACHE) if self.is_registered() and self.use_overrides: overrides = [ {"contentLabel": repo.id, "name": "enabled", "value": repos_to_modify[repo]} for repo in repos_to_modify ] metadata_overrides = [ {"contentLabel": repo.id, "name": "enabled_metadata", "value": repos_to_modify[repo]} for repo in repos_to_modify ] overrides.extend(metadata_overrides) results = self.cp.setContentOverrides(self.identity.uuid, overrides) cache = inj.require(inj.OVERRIDE_STATUS_CACHE) # Update the cache with the returned JSON cache.server_status = results cache.write_cache() repo_action_invoker.update() else: # When subscription-manager is in offline mode, then we have to generate redhat.repo from # entitlement certificates rl = RepoActionInvoker() rl.update() # In the disconnected case we must modify the repo file directly. changed_repos = [repo for repo in matches if repo["enabled"] != status] for repo in changed_repos: repo["enabled"] = status repo["enabled_metadata"] = status if changed_repos: repo_file = YumRepoFile() repo_file.read() for repo in changed_repos: repo_file.update(repo) repo_file.write() for repo in repos_to_modify: # Watchout for string comparison here: if repos_to_modify[repo] == "1": print(_("Repository '{repoid}' is enabled for this system.").format(repoid=repo.id)) else: print(_("Repository '{repoid}' is disabled for this system.").format(repoid=repo.id)) return rc
def test_get_repo_file(self): repo_action_invoker = RepoActionInvoker() repo_file = repo_action_invoker.get_repo_file() self.assertFalse(repo_file is None)
def test_get_repos_empty_dirs(self): repo_action_invoker = RepoActionInvoker() repos = repo_action_invoker.get_repos() if repos: self.fail("get_repos() should have returned an empty set but did not.")
#!/usr/bin/python # # This script was downloaded from https://bugzilla.redhat.com/attachment.cgi?id=1027300 and slightly modified # This purpose of this script is to verify bugzilla https://bugzilla.redhat.com/show_bug.cgi?id=1223038 # Bug 1223038 - RepoActionInvoker.is_managed() broken in subscription-manager-1.14.5-1.el6.x86_64 /usr/share/rhsm/subscription_manager/repolib.py # import sys import logging LOG_FILENAME = 'ismanagedtest.log' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) # read argument to this script some_repo = str(sys.argv[1]) _LIBPATH = "/usr/share/rhsm" # add to the path if need be if _LIBPATH not in sys.path: sys.path.append(_LIBPATH) from subscription_manager.injectioninit import init_dep_injection init_dep_injection() from subscription_manager.repolib import RepoActionInvoker rai = RepoActionInvoker() # Should print "False" if is_managed is working print rai.is_managed(some_repo)