예제 #1
0
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()
예제 #2
0
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()
예제 #3
0
    def _get_libset(self):

        self.entcertlib = EntCertActionInvoker()
        self.repolib = RepoActionInvoker()

        lib_set = [self.entcertlib, self.repolib]
        return lib_set
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()
예제 #5
0
    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()
예제 #6
0
    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()
예제 #7
0
    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)
예제 #8
0
 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."
         )
예제 #9
0
    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()
예제 #10
0
 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")
예제 #11
0
 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)
예제 #12
0
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)
예제 #13
0
    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
예제 #14
0
    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)
예제 #15
0
    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
예제 #16
0
    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
예제 #17
0
    def test_get_repo_file(self):
        repo_action_invoker = RepoActionInvoker()

        repo_file = repo_action_invoker.get_repo_file()
        self.assertFalse(repo_file is None)
예제 #18
0
 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.")