def test_he_unicode(self):
     e = Exception("Ошибка при обновлении системных данных (см. /var/log/rhsm/rhsm.log")
     #    e = FakeException(msg="Ошибка при обновлении системных данных (см. /var/log/rhsm/rhsm.log")
     try:
         handle_exception("a: %s" % e, e)
     except SystemExit as e:
         self.assertEqual(e.code, os.EX_SOFTWARE)
Example #2
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)
    def _do_command(self):
        if not self.is_registered():
            # TODO: Should this use the standard NOT_REGISTERED message?
            system_exit(ERR_NOT_REGISTERED_CODE, _("This system is currently not registered."))

        print(_("Unregistering from: {hostname}:{port}{prefix}").format(
              hostname=conf["server"]["hostname"], port=conf["server"]["port"], prefix=conf["server"]["prefix"]))
        try:
            unregister.UnregisterService(self.cp).unregister()
        except Exception as e:
            handle_exception("Unregister failed", e)

        # managerlib.unregister reloads the now None provided identity
        # so cp_provider provided auth_cp's should fail, like the below

        # This block is simply to ensure that the yum repos got updated. If it fails,
        # there is no issue since it will most likely be cleaned up elsewhere (most
        # likely by the yum plugin)
        try:
            # there is no consumer cert at this point, a uep object
            # is not useful
            cleanup_certmgr = UnregisterActionClient()
            cleanup_certmgr.update()
        except Exception as e:
            pass

        self._request_validity_check()

        # We have new credentials, restart virt-who
        restart_virt_who()

        print(_("System has been unregistered."))
Example #4
0
    def _do_command(self):
        self.assert_should_be_registered()
        try:
            # Also remove the content access mode cache to be sure we display
            # SCA or regular mode correctly
            content_access_mode = inj.require(inj.CONTENT_ACCESS_MODE_CACHE)
            if content_access_mode.exists():
                content_access_mode.delete_cache()

            if self.options.force is True:
                # get current consumer identity
                consumer_identity = inj.require(inj.IDENTITY)
                # Force a regen of the entitlement certs for this consumer
                if not self.cp.regenEntitlementCertificates(consumer_identity.uuid, True):
                    log.debug(
                        "Warning: Unable to refresh entitlement certificates; service likely unavailable"
                    )

            self.entcertlib.update()

            log.debug("Refreshed local data")
            print(_("All local data refreshed"))
        except connection.RestlibException as re:
            log.error(re)

            mapped_message: str = ExceptionMapper().get_message(re)
            system_exit(os.EX_SOFTWARE, mapped_message)
        except Exception as e:
            handle_exception(
                _("Unable to perform refresh due to the following exception: {e}").format(e=e), e
            )

        self._request_validity_check()
 def test_he_restlib_exception_unicode(self):
     e = connection.RestlibException(
         404, "Ошибка при обновлении системных данных (см. /var/log/rhsm/rhsm.log"
     )
     try:
         handle_exception("обновлении", e)
     except SystemExit as e:
         self.assertEqual(e.code, os.EX_SOFTWARE)
Example #6
0
 def test_he_ssl_wrong_host(self):
     if not six.PY2:
         raise SkipTest(
             "M2Crypto-specific interface. Not used with Python 3.")
     e = SSL.Checker.WrongHost("expectedHost.example.com",
                               "actualHost.example.com", "subjectAltName")
     try:
         handle_exception("huh", e)
     except SystemExit as e:
         self.assertEqual(e.code, os.EX_SOFTWARE)
Example #7
0
 def test_he_socket_error(self):
     # these error messages are bare strings, so we need to update the tests
     # if those messages change
     expected_msg = 'Network error, unable to connect to server. Please see /var/log/rhsm/rhsm.log for more information.'
     managercli.log.set_expected_msg(expected_msg)
     try:
         handle_exception(self.msg, socket.error())
     except SystemExit as e:
         self.assertEqual(e.code, os.EX_SOFTWARE)
     self.assertEqual(managercli.log.expected_msg, expected_msg)
    def _do_command(self):
        self._validate_options()
        try:
            # If we have a username/password, we're going to use that, otherwise
            # we'll use the identity certificate. We already know one or the other
            # exists:
            if self.options.token:
                self.cp = self.cp_provider.get_keycloak_auth_cp(
                    self.options.token)
            elif self.options.username and self.options.password:
                self.cp_provider.set_user_pass(self.username, self.password)
                self.cp = self.cp_provider.get_basic_auth_cp()
            elif not self.is_registered() and self.options.show:
                pass
            else:
                # get an UEP as consumer
                self.cp = self.cp_provider.get_consumer_auth_cp()
        except connection.RestlibException as re:
            log.exception(re)
            log.error(
                "Error: Unable to retrieve service levels: {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 service levels."), e)
        else:
            try:
                if self.options.unset:
                    self.unset()
                elif self.options.set is not None:
                    self.set()
                elif self.options.list:
                    self.list_service_levels()
                elif self.options.show:
                    self.show()
                else:
                    self.show()
            except UnauthorizedException as uex:
                handle_exception(_(str(uex)), uex)
            except connection.GoneException as ge:
                raise ge
            except connection.RestlibException as re_err:
                log.exception(re_err)
                log.error(
                    "Error: Unable to retrieve service levels: {err}".format(
                        err=re_err))

                mapped_message: str = ExceptionMapper().get_message(re_err)
                system_exit(os.EX_SOFTWARE, mapped_message)
            except ProxyException:
                system_exit(
                    os.EX_UNAVAILABLE,
                    _("Proxy connection failed, please check your settings."),
                )
Example #9
0
    def _do_command(self):

        try:
            # get a UEP
            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()
            owners = self.cp.getOwnerList(self.username)
            log.debug("Successfully retrieved org list from server.")
            if len(owners):
                print("+-------------------------------------------+")
                print("          {name} {label}".format(
                    name=self.username, label=_("Organizations")))
                print("+-------------------------------------------+")
                print("")
                for owner in owners:
                    print(
                        columnize(ORG_LIST, echo_columnize_callback,
                                  owner["displayName"], owner["key"]) + "\n")
            else:
                print(
                    _("{username} cannot register with any organizations.").
                    format(username=self.username))

        except connection.RestlibException as re:
            log.exception(re)
            log.error(
                "Error: Unable to retrieve org 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 org list from server"), e)
    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 #11
0
    def _do_command(self):
        """
        Executes the command.
        """
        self.assert_should_be_registered()
        self._validate_options()

        try:
            # FIXME: why just facts and package profile update here?
            # update facts first, if we need to
            facts = inj.require(inj.FACTS)
            facts.update_check(self.cp, self.identity.uuid)

            profile_mgr = inj.require(inj.PROFILE_MANAGER)
            profile_mgr.update_check(self.cp, self.identity.uuid)

            # BZ 1248833 Ensure we print out the display message if we get any back
            response = self.cp.activateMachine(self.identity.uuid,
                                               self.options.email,
                                               self.options.locale)
            if response and response.get('displayMessage'):
                system_exit(0, response.get('displayMessage'))
        except connection.GoneException as ge:
            raise ge
        except connection.RestlibException as e:
            # candlepin throws an exception during activateMachine, even for
            # 200's. We need to look at the code in the RestlibException and proceed
            # accordingly
            if 200 <= e.code <= 210:
                system_exit(0, e)
            else:
                handle_exception(u"Unable to redeem: {e}".format(e=e), e)
        except Exception as e:
            handle_exception(u"Unable to redeem: {e}".format(e=e), e)

        self._request_validity_check()
Example #12
0
 def test_he_ssl_error(self):
     e = ssl.SSLError()
     try:
         handle_exception("huh", e)
     except SystemExit as e:
         self.assertEqual(e.code, os.EX_SOFTWARE)
Example #13
0
 def test_he_network_exception(self):
     e = connection.NetworkException(1337)
     try:
         handle_exception("huh", e)
     except SystemExit as e:
         self.assertEqual(e.code, os.EX_SOFTWARE)
Example #14
0
 def test_he_remote_server_exception(self):
     e = connection.RemoteServerException(1984)
     try:
         handle_exception("huh", e)
     except SystemExit as e:
         self.assertEqual(e.code, os.EX_SOFTWARE)
Example #15
0
 def test_he_bad_certificate(self):
     e = connection.BadCertificateException("/road/to/nowhwere")
     try:
         handle_exception("huh", e)
     except SystemExit as e:
         self.assertEqual(e.code, os.EX_SOFTWARE)
Example #16
0
 def test_he_restlib_exception(self):
     e = connection.RestlibException(404, "this is a msg")
     try:
         handle_exception("huh", e)
     except SystemExit as e:
         self.assertEqual(e.code, os.EX_SOFTWARE)
except KeyboardInterrupt:
    system_exit(0, "\nUser interrupted process.")
except ImportError as err:
    system_exit(
        2, "Unable to find Subscription Manager module.\n"
        "Error: %s" % err)


def main():
    # execute
    try:
        return migrate.main()
    except KeyboardInterrupt:
        system_exit(0, "\nUser interrupted process.")

    return 0


if __name__ == '__main__':
    try:
        sys.exit(abs(main() or 0))
    except SystemExit as sys_err:
        # this is a non-exceptional exception thrown by Python 2.4, just
        # re-raise, bypassing handle_exception
        raise sys_err
    except KeyboardInterrupt:
        system_exit(0, "\nUser interrupted process.")
    except Exception as err:
        handle_exception("Exception caught in rhm-migrate-classic-to-rhsm",
                         err)
Example #18
0
 def test_he(self):
     e = FakeException()
     try:
         handle_exception(self.msg, e)
     except SystemExit as e:
         self.assertEqual(e.code, os.EX_SOFTWARE)
Example #19
0
    from subscription_manager.cli_command.cli import handle_exception
except KeyboardInterrupt:
    system_exit(0, "\nUser interrupted process.")
except ImportError as err:
    system_exit(2, "Unable to find Subscription Manager module.\nError:",
                str(err))


def main():
    # execute
    try:
        return migrate.main(five_to_six_script=True)
    except KeyboardInterrupt:
        system_exit(0, "\nUser interrupted process.")

    return 0


if __name__ == '__main__':
    try:
        sys.exit(abs(main() or 0))
    except SystemExit as e:
        # this is a non-exceptional exception thrown by Python 2.4, just
        # re-raise, bypassing handle_exception
        raise e
    except KeyboardInterrupt:
        system_exit(0, "\nUser interrupted process.")
    except Exception as e:
        handle_exception("Exception caught in sat5to6", e)
Example #20
0
    def _do_command(self):
        """
        Executes the command.
        """
        self.assert_should_be_registered()
        self._validate_options()

        # --pool or --file turns off default auto attach
        if self.options.pool or self.options.file:
            self.auto_attach = False

        # Do not try to do auto-attach, when simple content access mode is used
        # BZ: https://bugzilla.redhat.com/show_bug.cgi?id=1826300
        #
        if is_simple_content_access(uep=self.cp, identity=self.identity):
            if self.auto_attach is True:
                self._print_ignore_auto_attach_mesage()
            else:
                self._print_ignore_attach_message()
            return 0

        installed_products_num = 0
        return_code = 0
        report = None

        # TODO: change to if self.auto_attach: else: pool/file stuff
        try:
            cert_action_client = ActionClient(skips=[PackageProfileActionInvoker])
            cert_action_client.update()
            cert_update = True

            attach_service = attach.AttachService(self.cp)
            if self.options.pool:
                subscribed = False

                for pool in self.options.pool:
                    # odd html strings will cause issues, reject them here.
                    if pool.find("#") >= 0:
                        system_exit(os.EX_USAGE, _("Please enter a valid numeric pool ID."))

                    try:
                        ents = attach_service.attach_pool(pool, self.options.quantity)
                        # Usually just one, but may as well be safe:
                        for ent in ents:
                            pool_json = ent["pool"]
                            print(
                                _("Successfully attached a subscription for: {name}").format(
                                    name=pool_json["productName"]
                                )
                            )
                            log.debug(
                                "Attached a subscription for {name}".format(name=pool_json["productName"])
                            )
                            subscribed = True
                    except connection.RestlibException as re:
                        log.exception(re)

                        exception_mapper = ExceptionMapper()
                        mapped_message = exception_mapper.get_message(re)

                        if re.code == 403:
                            print(mapped_message)  # already subscribed.
                        elif re.code == 400 or re.code == 404:
                            print(mapped_message)  # no such pool.
                        else:
                            system_exit(os.EX_SOFTWARE, mapped_message)  # some other error.. don't try again
                if not subscribed:
                    return_code = 1
            # must be auto
            else:
                installed_products_num = len(products.InstalledProducts(self.cp).list())
                # if we are green, we don't need to go to the server
                self.sorter = inj.require(inj.CERT_SORTER)

                if self.sorter.is_valid():
                    if not installed_products_num:
                        print(_("No Installed products on system. " "No need to attach subscriptions."))
                    else:
                        print(
                            _(
                                "All installed products are covered by valid entitlements. "
                                "No need to update subscriptions at this time."
                            )
                        )
                    cert_update = False
                else:
                    # If service level specified, make an additional request to
                    # verify service levels are supported on the server:
                    if self.options.service_level:
                        consumer = self.cp.getConsumer(self.identity.uuid)
                        if "serviceLevel" not in consumer:
                            system_exit(
                                os.EX_UNAVAILABLE,
                                _(
                                    "Error: The --servicelevel option is not "
                                    "supported by the server. Did not "
                                    "complete your request."
                                ),
                            )

                    attach_service.attach_auto(self.options.service_level)
                    if self.options.service_level is not None:
                        #  RHBZ 1632797 we should only save the sla if the sla was actually
                        #  specified. The uep and consumer_uuid are None, because service_level was sent
                        # to candlepin server using attach_service.attach_auto()
                        save_sla_to_syspurpose_metadata(
                            uep=None, consumer_uuid=None, service_level=self.options.service_level
                        )
                        print(_("Service level set to: {}").format(self.options.service_level))

            if cert_update:
                report = self.entcertlib.update()

            profile_action_client = ProfileActionClient()
            profile_action_client.update()

            if report and report.exceptions():
                print(_("Entitlement Certificate(s) update failed due to the following reasons:"))
                for e in report.exceptions():
                    print("\t-", str(e))
            elif self.auto_attach:
                if not installed_products_num:
                    return_code = 1
                else:
                    self.sorter.force_cert_check()
                    # Make sure that we get fresh status of installed products
                    status_cache = inj.require(inj.ENTITLEMENT_STATUS_CACHE)
                    status_cache.load_status(
                        self.sorter.cp_provider.get_consumer_auth_cp(),
                        self.sorter.identity.uuid,
                        self.sorter.on_date,
                    )
                    self.sorter.load()
                    # run this after entcertlib update, so we have the new entitlements
                    return_code = show_autosubscribe_output(self.cp, self.identity)

        except Exception as e:
            handle_exception("Unable to attach: {e}".format(e=e), e)

        # it is okay to call this no matter what happens above,
        # it's just a notification to perform a check
        self._request_validity_check()

        return return_code
Example #21
0
    ga_loader.init_ga()

except KeyboardInterrupt:
    system_exit(0, "\nUser interrupted process.")
except ImportError as err:
    system_exit(2, "Unable to find Subscription Manager module.\n"
                   "Error: %s" % err)


def main():
    # execute
    try:
        return managercli.ManagerCLI().main()
    except KeyboardInterrupt:
        system_exit(0, "\nUser interrupted process.")

    return 0


if __name__ == '__main__':
    try:
        sys.exit(abs(main() or 0))
    except SystemExit as err:
        # This is a non-exceptional exception thrown by Python 2.4, just
        # re-raise, bypassing handle_exception
        raise err
    except KeyboardInterrupt:
        system_exit(0, "\nUser interrupted process.")
    except Exception as e:
        handle_exception("exception caught in subscription-manager", e)
    def _do_command(self):
        self.options.destination = os.path.expanduser(self.options.destination)
        self._validate_options()
        consumer = inj.require(inj.IDENTITY)
        if not consumer.is_valid():
            system_exit(ERR_NOT_REGISTERED_CODE, ERR_NOT_REGISTERED_MSG)

        code = self._make_code()
        archive_name = "rhsm-debug-system-%s" % code
        tar_file_name = "%s.tar.gz" % archive_name
        # /var/spool/rhsm/debug/rhsm-debug-system-20131212-121234/
        content_path = os.path.join(self.assemble_path, archive_name)
        # /var/spool/rhsm/debug/rhsm-debug-system-20131212-123413.tar.gz
        tar_file_path = os.path.join(self.assemble_path, tar_file_name)

        try:
            # assemble path is in the package, so should always exist
            self._makedir(content_path)

            owner = self.cp.getOwner(consumer.uuid)

            self._write_flat_file(content_path, "consumer.json",
                                  self.cp.getConsumer(consumer.uuid))
            self._write_flat_file(content_path, "compliance.json",
                                  self.cp.getCompliance(consumer.uuid))
            self._write_flat_file(content_path, "entitlements.json",
                                  self.cp.getEntitlementList(consumer.uuid))
            self._write_flat_file(
                content_path, "pools.json",
                self.cp.getPoolsList(consumer.uuid, True, None, owner["key"]))
            self._write_flat_file(content_path, "version.json",
                                  self._get_version_info())

            # FIXME: we need to anon proxy passwords?
            sos = self.options.sos
            defaults = conf.defaults()
            # sosreport collects /etc/rhsm/* and /var/*/rhsm/*, so these would
            # be redundant for sos
            if not sos:
                # copy rhsm.conf specifically
                self._copy_cert_directory("/etc/rhsm", content_path)
                self._copy_directory("/var/log/rhsm", content_path)
                self._copy_directory("/var/lib/rhsm", content_path)

            if not sos:
                self._copy_cert_directory(DEFAULT_PRODUCT_CERT_DIR,
                                          content_path)

            if defaults["productcertdir"] != conf["rhsm"][
                    "productCertDir"] or not sos:
                self._copy_cert_directory(conf["rhsm"]["productCertDir"],
                                          content_path)

            if defaults["entitlementcertdir"] != conf["rhsm"][
                    "entitlementCertDir"] or not sos:
                self._copy_cert_directory(conf["rhsm"]["entitlementCertDir"],
                                          content_path)

            if defaults["consumercertdir"] != conf["rhsm"][
                    "consumerCertDir"] or not sos:
                self._copy_cert_directory(conf["rhsm"]["consumerCertDir"],
                                          content_path)

            # If ca_cert_dir and pluginconfdif are configured as subdirs of /etc/rhsm
            # (as is the default) we will have already copied there contents,
            # so ignore directory exists errors
            try:
                if defaults["ca_cert_dir"] != conf["rhsm"][
                        "ca_cert_dir"] or not sos:
                    self._copy_cert_directory(conf["rhsm"]["ca_cert_dir"],
                                              content_path)
            except EnvironmentError as e:
                if e.errno != errno.EEXIST:
                    raise

            try:
                if defaults["pluginconfdir"] != conf["rhsm"][
                        "pluginconfdir"] or not sos:
                    self._copy_directory(conf["rhsm"]["pluginconfdir"],
                                         content_path)
            except EnvironmentError as e:
                if e.errno != errno.EEXIST:
                    raise

            # build an archive by default
            if self.options.archive:
                try:
                    tf = tarfile.open(tar_file_path, "w:gz")
                    tf.add(content_path, archive_name)
                finally:
                    tf.close()

                final_path = os.path.join(self.options.destination,
                                          "rhsm-debug-system-%s.tar.gz" % code)

                self.final_destination_path = final_path

                sfm = SaferFileMove()
                sfm.move(tar_file_path, final_path)
                print(_("Wrote: {final_path}").format(final_path=final_path))
            else:
                # NOTE: this will fail across filesystems. We could add a force
                # flag to for creation of a specific name with approriate
                # warnings.
                dest_dir_name = os.path.join(self.options.destination,
                                             archive_name)

                # create the dest dir, and set it's perms, this is atomic ish
                self._makedir(dest_dir_name)

                # try to rename the dir atomically
                # rename only works on the same filesystem, but it is atomic.
                os.rename(content_path, dest_dir_name)

                print(
                    _("Wrote: {destination_dir_name}").format(
                        destination_dir_name=dest_dir_name))

        except Exception as e:
            handle_exception(
                _("Unable to create zip file of system information: {error}").
                format(error=e), e)
            sys.exit(os.EX_SOFTWARE)
        finally:
            if content_path and os.path.isdir(content_path):
                shutil.rmtree(content_path, True)
Example #23
0
    def _do_command(self):
        """
        Executes the command.
        """

        self.log_client_version()

        # Always warn the user if registered to old RHN/Spacewalk
        if ClassicCheck().is_registered_with_classic():
            print(get_branding().REGISTERED_TO_OTHER_WARNING)

        self._validate_options()

        # gather installed products info
        self.installed_mgr = inj.require(inj.INSTALLED_PRODUCTS_MANAGER)

        previously_registered = False
        if self.is_registered() and self.options.force:
            previously_registered = True
            # First let's try to un-register previous consumer; if this fails
            # we'll let the error bubble up, so that we don't blindly re-register.
            # managerlib.unregister handles the special case that the consumer has already been removed.
            old_uuid = self.identity.uuid

            print(
                _("Unregistering from: {hostname}:{port}{prefix}").format(
                    hostname=conf["server"]["hostname"],
                    port=conf["server"]["port"],
                    prefix=conf["server"]["prefix"],
                )
            )
            try:
                unregister.UnregisterService(self.cp).unregister()
                self.entitlement_dir.__init__()
                self.product_dir.__init__()
                log.info("--force specified, unregistered old consumer: {old_uuid}".format(old_uuid=old_uuid))
                print(_("The system with UUID {old_uuid} has been unregistered").format(old_uuid=old_uuid))
            except ssl.SSLError as e:
                # since the user can override serverurl for register, a common use case is to try to switch servers
                # using register --force... However, this normally cannot successfully unregister since the servers
                # are different.
                handle_exception("Unregister failed: {e}".format(e=e), e)
            except Exception as e:
                handle_exception("Unregister failed", e)

        self.cp_provider.clean()
        if previously_registered:
            print(_("All local data removed"))

        # Proceed with new registration:
        try:
            if self.options.token:
                admin_cp = self.cp_provider.get_keycloak_auth_cp(self.options.token)
            elif not self.options.activation_keys:
                hostname = conf["server"]["hostname"]
                if ":" in hostname:
                    normalized_hostname = "[{hostname}]".format(hostname=hostname)
                else:
                    normalized_hostname = hostname
                print(
                    _("Registering to: {hostname}:{port}{prefix}").format(
                        hostname=normalized_hostname,
                        port=conf["server"]["port"],
                        prefix=conf["server"]["prefix"],
                    )
                )
                self.cp_provider.set_user_pass(self.username, self.password)
                admin_cp = self.cp_provider.get_basic_auth_cp()
            else:
                admin_cp = self.cp_provider.get_no_auth_cp()

            # This is blocking and not async, which aside from blocking here, also
            # means things like following name owner changes gets weird.
            service = register.RegisterService(admin_cp)

            if self.options.consumerid:
                log.debug("Registering as existing consumer: {id}".format(id=self.options.consumerid))
                consumer = service.register(None, consumerid=self.options.consumerid)
            else:
                if self.options.org:
                    owner_key = self.options.org
                else:
                    owner_key = service.determine_owner_key(
                        username=self.username, get_owner_cb=self._get_owner_cb, no_owner_cb=self._no_owner_cb
                    )
                environment_ids = self._process_environments(admin_cp, owner_key)
                consumer = service.register(
                    owner_key,
                    activation_keys=self.options.activation_keys,
                    environments=environment_ids,
                    force=self.options.force,
                    name=self.options.consumername,
                    type=self.options.consumertype,
                    service_level=self.options.service_level,
                )
        except (connection.RestlibException, exceptions.ServiceError) as re:
            log.exception(re)

            mapped_message: str = ExceptionMapper().get_message(re)
            system_exit(os.EX_SOFTWARE, mapped_message)
        except Exception as e:
            handle_exception(_("Error during registration: {e}").format(e=e), e)
        else:
            consumer_info = identity.ConsumerIdentity(consumer["idCert"]["key"], consumer["idCert"]["cert"])
            print(_("The system has been registered with ID: {id}").format(id=consumer_info.getConsumerId()))
            print(_("The registered system name is: {name}").format(name=consumer_info.getConsumerName()))
            if self.options.service_level:
                print(_("Service level set to: {level}").format(level=self.options.service_level))

        # We have new credentials, restart virt-who
        restart_virt_who()

        # get a new UEP as the consumer
        self.cp = self.cp_provider.get_consumer_auth_cp()

        # log the version of the server we registered to
        self.log_server_version()

        facts = inj.require(inj.FACTS)

        # FIXME: can these cases be replaced with invoking
        # FactsLib (or a FactsManager?)
        # Must update facts to clear out the old ones:
        if self.options.consumerid:
            log.debug("Updating facts")
            #
            # FIXME: Need a ConsumerFacts.sync or update or something
            # TODO: We register, with facts, then update facts again...?
            #       Are we trying to sync potential new or dynamic facts?
            facts.update_check(self.cp, consumer["uuid"], force=True)

        # Facts and installed products went out with the registration request,
        # manually write caches to disk:
        # facts service job now(soon)
        facts.write_cache()
        self.installed_mgr.update_check(self.cp, consumer["uuid"])

        if self.options.release:
            # TODO: grab the list of valid options, and check
            self.cp.updateConsumer(consumer["uuid"], release=self.options.release)

        if self.autoattach:
            self._do_auto_attach(consumer)

        if (
            self.options.consumerid
            or self.options.activation_keys
            or self.autoattach
            or self.cp.has_capability(CONTENT_ACCESS_CERT_CAPABILITY)
        ):
            log.debug("System registered, updating entitlements if needed")
            # update certs, repos, and caches.
            # FIXME: aside from the overhead, should this be cert_action_client.update?
            self.entcertlib.update()

        try:
            profile_mgr = inj.require(inj.PROFILE_MANAGER)
            # 767265: always force an upload of the packages when registering
            profile_mgr.update_check(self.cp, consumer["uuid"], True)
        except RemoteServerException as err:
            # When it is not possible to upload profile ATM, then print only error about this
            # to rhsm.log. The rhsmcertd will try to upload it next time.
            log.error("Unable to upload profile: {err}".format(err=str(err)))

        subscribed = 0
        if self.options.activation_keys or self.autoattach:
            # update with latest cert info
            self.sorter = inj.require(inj.CERT_SORTER)
            self.sorter.force_cert_check()
            subscribed = show_autosubscribe_output(self.cp, self.identity)

        self._request_validity_check()
        return subscribed
Example #24
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 #25
0
    def _do_command(self):
        """
        Executes the command.
        """
        self._validate_options()
        return_code = 0
        if self.is_registered():
            ent_service = entitlement.EntitlementService(self.cp)
            try:
                if self.options.all:
                    total = ent_service.remove_all_entitlements()
                    # total will be None on older Candlepins that don't
                    # support returning the number of subscriptions unsubscribed from
                    if total is None:
                        print(_("All subscriptions have been removed at the server."))
                    else:
                        count = total["deletedRecords"]
                        print(
                            ungettext(
                                "%s subscription removed at the server.",
                                "%s subscriptions removed at the server.",
                                count,
                            )
                            % count
                        )
                else:
                    # Try to remove subscriptions defined by pool IDs first (remove --pool=...)
                    if self.options.pool_ids:
                        (
                            removed_pools,
                            unremoved_pools,
                            removed_serials,
                        ) = ent_service.remove_entilements_by_pool_ids(self.options.pool_ids)
                        if not removed_pools:
                            return_code = 1
                        self._print_unbind_ids_result(removed_pools, unremoved_pools, "pools")
                    else:
                        removed_serials = []
                    # Then try to remove subscriptions defined by serials (remove --serial=...)
                    unremoved_serials = []
                    if self.options.serials:
                        serials = unique_list_items(self.options.serials)
                        # Don't remove serials already removed by a pool
                        serials_to_remove = [serial for serial in serials if serial not in removed_serials]
                        _removed_serials, unremoved_serials = ent_service.remove_entitlements_by_serials(
                            serials_to_remove
                        )
                        removed_serials.extend(_removed_serials)
                        if not _removed_serials:
                            return_code = 1
                    # Print final result of removing pools
                    self._print_unbind_ids_result(removed_serials, unremoved_serials, "serial numbers")
            except connection.GoneException as ge:
                raise ge
            except connection.RestlibException as err:
                log.error(err)

                mapped_message: str = ExceptionMapper().get_message(err)
                system_exit(os.EX_SOFTWARE, mapped_message)
            except Exception as e:
                handle_exception(
                    _("Unable to perform remove due to the following exception: {e}").format(e=e), e
                )
        else:
            # We never got registered, just remove the cert
            try:
                if self.options.all:
                    total = 0
                    for ent in self.entitlement_dir.list():
                        ent.delete()
                        total = total + 1
                    print(_("{total} subscriptions removed from this system.").format(total=total))
                else:
                    if self.options.serials or self.options.pool_ids:
                        serials = self.options.serials or []
                        pool_ids = self.options.pool_ids or []
                        count = 0
                        for ent in self.entitlement_dir.list():
                            ent_pool_id = str(getattr(ent.pool, "id", None) or "")
                            if str(ent.serial) in serials or ent_pool_id in pool_ids:
                                ent.delete()
                                print(
                                    _(
                                        "Subscription with serial number {serial} removed from this system"
                                    ).format(serial=str(ent.serial))
                                )
                                count = count + 1
                        if count == 0:
                            return_code = 1
            except Exception as e:
                handle_exception(
                    _("Unable to perform remove due to the following exception: {e}").format(e=e), e
                )

        # it is okay to call this no matter what happens above,
        # it's just a notification to perform a check
        self._request_validity_check()
        return return_code