Example #1
0
    def _do_command(self):
        self._validate_options()
        supported_resources = get_supported_resources()
        if "environments" not in supported_resources:
            system_exit(os.EX_UNAVAILABLE,
                        _("Error: Server does not support environments."))
        try:
            if self.options.token:
                self.cp = self.cp_provider.get_keycloak_auth_cp(
                    self.options.token)
            else:
                if not self.options.enabled:
                    if self.options.username is None or self.options.password is None:
                        print(_("This operation requires user credentials"))
                    self.cp_provider.set_user_pass(self.username,
                                                   self.password)
                    self.cp = self.cp_provider.get_basic_auth_cp()
            self.identity = require(IDENTITY)
            if self.options.set:
                self._set_environments()
            else:
                self._list_environments()
        except connection.RestlibException as re:
            log.exception(re)
            log.error(
                "Error: Unable to retrieve environment list from server: {re}".
                format(re=re))

            mapped_message: str = ExceptionMapper().get_message(re)
            system_exit(os.EX_SOFTWARE, mapped_message)
        except Exception as e:
            handle_exception(
                _("Error: Unable to retrieve environment list from server"), e)
Example #2
0
    def _get_environment_id(self, cp, owner_key, environment_name):
        # If none specified on CLI and the server doesn't support environments,
        # return None, the registration method will skip environment specification.

        # Activation keys may not be used with environment for registration.
        # We use a no-auth cp, so we cannot look up environment ids by name
        if self.options.activation_keys:
            return None

        supported_resources = get_supported_resources()
        supports_environments = 'environments' in supported_resources
        if not environment_name:
            if supports_environments:
                env_list = cp.getEnvironmentList(owner_key)

                # If there aren't any environments, don't prompt for one
                if not env_list:
                    return environment_name

                # If the envronment list is len 1, pick that environment
                if len(env_list) == 1:
                    log.debug(
                        "Using the only available environment: \"{name}\"".
                        format(name=env_list[0]["name"]))
                    return env_list[0]['id']

                env_name_list = [env['name'] for env in env_list]
                print(
                    _('Hint: Organization "{key}" contains following environments: {list}'
                      ).format(key=owner_key, list=", ".join(env_name_list)))

                environment_name = self._prompt_for_environment()

                # Should only ever be len 0 or 1
                env_matches = [
                    env['id'] for env in env_list
                    if env['name'] == environment_name
                ]
                if env_matches:
                    return env_matches[0]
                system_exit(
                    os.EX_DATAERR,
                    _("No such environment: {name}").format(
                        name=environment_name))

            # Server doesn't support environments
            return environment_name

        if not supports_environments:
            system_exit(os.EX_UNAVAILABLE,
                        _("Error: Server does not support environments."))

        env = cp.getEnvironment(owner_key=owner_key, name=environment_name)
        if not env:
            system_exit(
                os.EX_DATAERR,
                _("No such environment: {name}").format(name=environment_name))
        return env['id']
Example #3
0
    def update_check(self, uep, consumer_uuid, force=False):
        """
        Check if packages have changed, and push an update if so.
        """

        # If the server doesn't support packages, don't try to send the profile:
        supported_resources = get_supported_resources()
        if PACKAGES_RESOURCE not in supported_resources:
            log.warning("Server does not support packages, skipping profile upload.")
            return 0

        if force or self.report_package_profile:
            return CacheManager.update_check(self, uep, consumer_uuid, force)
        elif not self.report_package_profile:
            log.warning("Skipping package profile upload due to report_package_profile setting.")
            return 0
        else:
            return 0
Example #4
0
    def _process_environments(self, admin_cp, owner_key):
        """
        Confirms that environment(s) have been chosen if they are supported
        and a choice needs to be made
        """
        supported_resources = get_supported_resources()
        supports_environments = "environments" in supported_resources

        if not supports_environments:
            if self.options.environments is not None:
                system_exit(os.EX_UNAVAILABLE, _("Error: Server does not support environments."))
            return None

        # We have an activation key, so don't need to fill/check the bits
        # related to environments, as they are part of the activation key
        if self.options.activation_keys:
            return None

        all_env_list = admin_cp.getEnvironmentList(owner_key)
        if self.options.environments:
            environments = self.options.environments
        else:
            # If there aren't any environments, don't prompt for one
            if not all_env_list:
                return None

            # If the envronment list is len 1, pick that environment
            if len(all_env_list) == 1:
                log.debug(
                    'Using the only available environment: "{name}"'.format(name=all_env_list[0]["name"])
                )
                return all_env_list[0]["id"]

            env_name_list = [env["name"] for env in all_env_list]
            print(
                _('Hint: Organization "{key}" contains following environments: {list}').format(
                    key=owner_key, list=", ".join(env_name_list)
                )
            )
            environments = self._prompt_for_environment()
            if not self.cp.has_capability(MULTI_ENV) and "," in environments:
                system_exit(os.EX_USAGE, _("The entitlement server does not allow multiple environments"))

        return check_set_environment_names(all_env_list, environments)
    def _do_command(self):
        self._validate_options()
        try:
            if self.options.token:
                self.cp = self.cp_provider.get_keycloak_auth_cp(
                    self.options.token)
            else:
                self.cp_provider.set_user_pass(self.username, self.password)
                self.cp = self.cp_provider.get_basic_auth_cp()
            supported_resources = get_supported_resources()
            if 'environments' in supported_resources:
                environments = self._get_environments(self.org)

                if len(environments):
                    print("+-------------------------------------------+")
                    print("          {env}".format(env=_('Environments')))
                    print("+-------------------------------------------+")
                    for env in environments:
                        print(
                            columnize(ENVIRONMENT_LIST,
                                      echo_columnize_callback, env['name'],
                                      env['description'] or "") + "\n")
                else:
                    print(_("This org does not have any environments."))
            else:
                system_exit(os.EX_UNAVAILABLE,
                            _("Error: Server does not support environments."))

            log.debug("Successfully retrieved environment list from server.")
        except connection.RestlibException as re:
            log.exception(re)
            log.error(
                "Error: Unable to retrieve environment list from server: {re}".
                format(re=re))
            system_exit(os.EX_SOFTWARE, str(re))
        except Exception as e:
            handle_exception(
                _("Error: Unable to retrieve environment list from server"), e)
Example #6
0
    def _do_command(self):
        # get current consumer identity
        identity = inj.require(inj.IDENTITY)

        # check for Classic before doing anything else
        if ClassicCheck().is_registered_with_classic():
            if identity.is_valid():
                print(
                    _("server type: {type}").format(
                        type=get_branding().REGISTERED_TO_BOTH_SUMMARY))
            else:
                # no need to continue if user is only registered to Classic
                print(
                    _("server type: {type}").format(
                        type=get_branding().REGISTERED_TO_OTHER_SUMMARY))
                return

        try:
            self._validate_options()
            consumerid = self.identity.uuid
            consumer_name = self.identity.name
            if not self.options.regenerate:
                owner = get_current_owner(self.cp, self.identity)
                ownername = owner['displayName']
                ownerid = owner['key']

                print(
                    _('system identity: {consumerid}').format(
                        consumerid=consumerid))
                print(
                    _('name: {consumer_name}').format(
                        consumer_name=consumer_name))
                print(_('org name: {ownername}').format(ownername=ownername))
                print(_('org ID: {ownerid}').format(ownerid=ownerid))

                supported_resources = get_supported_resources(
                    self.cp, self.identity)
                if 'environments' in supported_resources:
                    consumer = self.cp.getConsumer(consumerid)
                    environment = consumer['environment']
                    if environment:
                        environment_name = environment['name']
                    else:
                        environment_name = _("None")
                    print(
                        _('environment name: {environment_name}').format(
                            environment_name=environment_name))
            else:
                if self.options.force:
                    # get an UEP with basic auth or keycloak auth
                    if self.options.token:
                        self.cp = self.cp_provider.get_keycloak_auth_cp(
                            self.options.token)
                    else:
                        self.cp_provider.set_user_pass(self.username,
                                                       self.password)
                        self.cp = self.cp_provider.get_basic_auth_cp()
                consumer = self.cp.regenIdCertificate(consumerid)
                managerlib.persist_consumer_cert(consumer)

                # do this in persist_consumer_cert? or some other
                # high level, "I just registered" thing
                self.identity.reload()

                print(_("Identity certificate has been regenerated."))

                log.debug("Successfully generated a new identity from server.")
        except connection.GoneException as ge:
            # Gone exception is caught in CliCommand and a consistent message
            # is printed there for all commands
            raise ge
        except connection.RestlibException as re:
            log.exception(re)
            log.error(
                u"Error: Unable to generate a new identity for the system: {re}"
            ).format(re=re)
            system_exit(os.EX_SOFTWARE, str(re))
        except Exception as e:
            handle_exception(
                _("Error: Unable to generate a new identity for the system"),
                e)
Example #7
0
    def __init__(self, cache_only=False, apply_overrides=True):
        self.identity = inj.require(inj.IDENTITY)

        # These should probably move closer their use
        self.ent_dir = inj.require(inj.ENT_DIR)
        self.prod_dir = inj.require(inj.PROD_DIR)

        self.ent_source = ent_cert.EntitlementDirEntitlementSource()

        self.cp_provider = inj.require(inj.CP_PROVIDER)

        self.manage_repos = 1
        self.apply_overrides = apply_overrides
        self.manage_repos = manage_repos_enabled()

        self.release = None
        self.overrides = {}
        self.override_supported = False

        try:
            self.override_supported = 'content_overrides' in get_supported_resources(
                uep=None, identity=self.identity)
        except (socket.error, connection.ConnectionException) as e:
            # swallow the error to fix bz 1298327
            log.exception(e)
            pass

        self.written_overrides = WrittenOverrideCache()

        # FIXME: empty report at the moment, should be changed to include
        # info about updated repos
        self.report = RepoActionReport()
        self.report.name = "Repo updates"
        # If we are not registered, skip trying to refresh the
        # data from the server
        if not self.identity.is_valid():
            return

        # NOTE: if anything in the RepoActionInvoker init blocks, and it
        #       could, yum could still block. The closest thing to an
        #       event loop we have is the while True: sleep() in lock.py:Lock.acquire()

        # Only attempt to update the overrides if they are supported
        # by the server.
        if self.override_supported:
            try:
                override_cache = inj.require(inj.OVERRIDE_STATUS_CACHE)
            except KeyError:
                override_cache = OverrideStatusCache()

            if cache_only:
                status = override_cache.read_cache_only()
            else:
                self.uep = self.cp_provider.get_consumer_auth_cp()
                status = override_cache.load_status(self.uep,
                                                    self.identity.uuid)

            for item in status or []:
                # Don't iterate through the list
                if item['contentLabel'] not in self.overrides:
                    self.overrides[item['contentLabel']] = {}
                self.overrides[item['contentLabel']][
                    item['name']] = item['value']
Example #8
0
    def _do_command(self):
        self._validate_options()
        # Abort if not registered
        self.assert_should_be_registered()

        supported_resources = get_supported_resources()
        if "content_overrides" not in supported_resources:
            system_exit(
                os.EX_UNAVAILABLE,
                _("Error: The 'repo-override' command is not supported by the server."
                  ))

        # update entitlement certificates if necessary. If we do have new entitlements
        # CertLib.update() will call RepoActionInvoker.update().
        self.entcertlib.update()
        # make sure the EntitlementDirectory singleton is refreshed
        self._request_validity_check()

        overrides = Overrides()

        if not manage_repos_enabled():
            print(_("Repositories disabled by configuration."))

        if self.options.list:
            results = overrides.get_overrides(self.identity.uuid)
            if results:
                self._list(results, self.options.repos)
            else:
                print(
                    _("This system does not have any content overrides applied to it."
                      ))
            return

        if self.options.additions:
            repo_ids = [
                repo.id
                for repo in overrides.repo_lib.get_repos(apply_overrides=False)
            ]
            to_add = [
                Override(repo, name, value) for repo in self.options.repos
                for name, value in list(self.options.additions.items())
            ]
            try:
                results = overrides.add_overrides(self.identity.uuid, to_add)
            except connection.RestlibException as ex:
                if ex.code == 400:
                    # blocklisted overrides specified.
                    # Print message and return a less severe code.
                    mapped_message: str = ExceptionMapper().get_message(ex)
                    system_exit(1, mapped_message)
                else:
                    raise ex

            # Print out warning messages if the specified repo does not exist in the repo file.
            for repo in self.options.repos:
                if repo not in repo_ids:
                    print(
                        _("Repository '{repo}' does not currently exist, but the override has been added."
                          ).format(repo=repo))

        if self.options.removals:
            to_remove = [
                Override(repo, item) for repo in self.options.repos
                for item in self.options.removals
            ]
            results = overrides.remove_overrides(self.identity.uuid, to_remove)
        if self.options.remove_all:
            results = overrides.remove_all_overrides(self.identity.uuid,
                                                     self.options.repos)

        # Update the cache and refresh the repo file.
        overrides.update(results)
Example #9
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