def legacy_purge(self, rpc_session, session_key):
        system_id_path = self.rhncfg["systemIdPath"]

        log.info("Deleting system %s from legacy server...", self.system_id)
        try:
            result = rpc_session.system.deleteSystems(session_key, self.system_id)
        except Exception:
            log.exception("Could not delete system %s from legacy server" % self.system_id)
            # If we time out or get a network error, log it and keep going.
            shutil.move(system_id_path, system_id_path + ".save")
            print(_("Did not receive a completed unregistration message from legacy server for system %s.") % self.system_id)

            if self.is_hosted:
                print(_("Please investigate on the Customer Portal at https://access.redhat.com."))
            return

        if result:
            log.info("System %s deleted.  Removing system id file and disabling rhnplugin.conf", self.system_id)
            os.remove(system_id_path)
            try:
                self.disable_yum_rhn_plugin()
            except Exception:
                pass
            print(_("System successfully unregistered from legacy server."))
        else:
            # If the legacy server reports that deletion just failed, then quit.
            system_exit(1, _("Unable to unregister system from legacy server.  ") + SEE_LOG_FILE)
    def select_service_level(self, org, servicelevel):
        not_supported = _("Error: The service-level command is not supported by the server.")
        try:
            levels = self.cp.getServiceLevelList(org)
        except RemoteServerException as e:
            system_exit(-1, not_supported)
        except RestlibException as e:
            if e.code == 404:
                # no need to die, just skip it
                print(not_supported)
                return None
            else:
                # server supports it but something went wrong, die.
                raise e

        # Create the sla tuple before appending the empty string to the list of
        # valid slas.
        slas = [(sla, sla) for sla in levels]
        # Display an actual message for the empty string level.
        slas.append((_("No service level preference"), ""))

        # The empty string is a valid level so append it to the list.
        levels.append("")
        if servicelevel is None or \
            servicelevel.upper() not in (level.upper() for level in levels):
            if servicelevel is not None:
                print(_("\nService level \"%s\" is not available.") % servicelevel)
            menu = Menu(slas, _("Please select a service level agreement for this system."))
            servicelevel = menu.choose()
        return servicelevel
 def load_transition_data(self, rpc_session):
     try:
         transition_data = rpc_session.system.transitionDataForSystem(self.system_id_contents)
         self.consumer_id = transition_data['uuid']
     except Exception as e:
         log.exception(e)
         system_exit(1, _("Could not retrieve system migration data from legacy server.  ") + SEE_LOG_FILE)
    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."))
Beispiel #5
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)
Beispiel #6
0
    def __init__(self, options):
        self.rhncfg = initUp2dateConfig()
        self.rhsmcfg = config.Config(initConfig())

        # Sometimes we need to send up the entire contents of the system id file
        # which is referred to in Satellite 5 nomenclature as a "certificate"
        # although it is not an X509 certificate.
        try:
            self.system_id_contents = open(self.rhncfg["systemIdPath"],
                                           'r').read()
        except IOError:
            system_exit(
                os.EX_IOERR,
                _("Could not read legacy system id at %s") %
                self.rhncfg["systemIdPath"])

        self.system_id = self.get_system_id(self.system_id_contents)

        self.proxy_host = None
        self.proxy_port = None
        self.proxy_user = None
        self.proxy_pass = None

        self.cp = None
        self.db = ProductDatabase()

        self.consumer_id = None

        self.options = options
        self.is_hosted = is_hosted()
Beispiel #7
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 _do_auto_attach(self, consumer):
        """
        Try to do auto-attach, when it was requested using --auto-attach CLI option
        :return: None
        """

        # Do not try to do auto-attach, when simple content access mode is used
        # Only print info message to stdout
        if is_simple_content_access(uep=self.cp, identity=self.identity):
            self._print_ignore_auto_attach_mesage()
            return

        if "serviceLevel" not in consumer and self.options.service_level:
            system_exit(
                os.EX_UNAVAILABLE,
                _(
                    "Error: The --servicelevel option is not supported "
                    "by the server. Did not complete your request."
                ),
            )
        try:
            # We don't call auto_attach with self.option.service_level, because it has been already
            # set during service.register() call
            attach.AttachService(self.cp).attach_auto(service_level=None)
        except connection.RestlibException as rest_lib_err:
            mapped_message: str = ExceptionMapper().get_message(rest_lib_err)
            print_error(mapped_message)
        except Exception:
            log.exception("Auto-attach failed")
            raise
def parse_argv(argv, default_dbus_name):
    parser = argparse.ArgumentParser(
        usage="usage: %(prog)s [options] [class name]")
    parser.add_argument(
        "-b",
        "--bus",
        action="store",
        dest="bus",
        help="Bus to use (defaults to dbus.SystemBus)",
    )
    parser.add_argument("-n", "--bus-name", default=default_dbus_name)
    parser.add_argument("-v", "--verbose", action="store_true")
    (opts, args) = parser.parse_known_args(argv[1:])

    try:
        if hasattr(opts, "bus") and opts.bus:
            opts.bus = rhsmlib.import_class(opts.bus)
        else:
            opts.bus = dbus.SystemBus
    except (AttributeError, ValueError):
        system_exit(
            os.EX_USAGE,
            _("Error: Unable to load bus '{name}'").format(name=opts.bus))

    return opts, args
Beispiel #10
0
def validate_options(options):
    if options.service_level and not options.auto:
        # TODO Need to explain why this restriction exists.
        system_exit(
            1,
            _("The --servicelevel and --no-auto options cannot be used together."
              ))
Beispiel #11
0
 def org(self):
     if not self._org:
         if self.options.org is not None:
             self._org = self.options.org
         else:
             owners = self.cp.getOwnerList(self.options.username)
             if len(owners) == 0:
                 system_exit(
                     os.EX_DATAERR,
                     _("Error: User {username} is not member of any organization."
                       ).format(username=self.options.username),
                 )
             elif len(owners) == 1:
                 self._org = owners[0]["key"]
             else:
                 # Get a list of valid owners. Since no owner was specified,
                 # print a hint message showing available owners, before asking
                 # to enter one.
                 org_keys = [owner["key"] for owner in owners]
                 print(
                     _('Hint: User "{name}" is member of following organizations: {orgs}'
                       ).format(name=self.username,
                                orgs=", ".join(org_keys)))
                 self._org = self._get_org(self.options.org)
     return self._org
Beispiel #12
0
 def select_service_level(self, org, servicelevel):
     not_supported = _(
         "Error: The service-level command is not supported by the server.")
     try:
         levels = self.cp.getServiceLevelList(org)
     except RemoteServerException, e:
         system_exit(-1, not_supported)
Beispiel #13
0
    def connect_to_rhn(self, credentials):
        hostname = self.rhncfg['serverURL'].split('/')[2]
        server_url = 'https://%s/rpc/api' % (hostname)
        try:
            if self.rhncfg['enableProxy']:
                proxy = "%s:%s" % (self.proxy_host, self.proxy_port)
                log.info("Using proxy %s for RHN API methods" % (proxy))
                if self.rhncfg['enableProxyAuth']:
                    proxy = "@".join(
                        ["%s:%s" % (self.proxy_user, self.proxy_pass), proxy])
            else:
                proxy = None

            sc = rpclib.Server(server_url, proxy=proxy)

            ca = self.rhncfg["sslCACert"]
            sc.add_trusted_cert(ca)

            sk = sc.auth.login(credentials.username, credentials.password)
            return (sc, sk)
        except Exception:
            log.error(traceback.format_exc())
            system_exit(
                1,
                _("Unable to authenticate to RHN Classic.  See /var/log/rhsm/rhsm.log for more details."
                  ))
Beispiel #14
0
    def unregister_system_from_rhn_classic(self, sc, sk):
        system_id_path = self.rhncfg["systemIdPath"]
        system_id = self.get_system_id()

        log.info("Deleting system %s from RHN Classic...", system_id)
        try:
            result = sc.system.deleteSystems(sk, system_id)
        except Exception:
            log.error("Could not delete system %s from RHN Classic" %
                      system_id)
            log.error(traceback.format_exc())
            shutil.move(system_id_path, system_id_path + ".save")
            self.disable_yum_rhn_plugin()
            print _(
                "Did not receive a completed unregistration message from RHN Classic for system %s.\n"
                "Please investigate on the Customer Portal at https://access.redhat.com."
            ) % system_id
            return

        if result:
            log.info(
                "System %s deleted.  Removing systemid file and disabling rhnplugin.conf",
                system_id)
            os.remove(system_id_path)
            self.disable_yum_rhn_plugin()
            print _("System successfully unregistered from RHN Classic.")
        else:
            system_exit(
                1,
                _("Unable to unregister system from RHN Classic.  Exiting."))
Beispiel #15
0
    def connect_to_rhn(self, credentials):
        hostname = self.rhncfg['serverURL'].split('/')[2]
        server_url = 'https://%s/rpc/api' % (hostname)

        try:
            if self.rhncfg['enableProxy']:
                proxy = "%s:%s" % (self.proxy_host, self.proxy_port)
                log.info("Using proxy %s for legacy API methods" % (proxy))
                if self.rhncfg['enableProxyAuth']:
                    proxy = "@".join(["%s:%s" % (self.proxy_user, self.proxy_pass), proxy])
            else:
                proxy = None

            rpc_session = rpclib.Server(server_url, proxy=proxy)

            ca = self.rhncfg["sslCACert"]
            rpc_session.add_trusted_cert(ca)

            if credentials.username and credentials.password:
                session_key = rpc_session.auth.login(credentials.username, credentials.password)
            else:
                session_key = None

            return (rpc_session, session_key)
        except Exception as e:
            log.exception(e)
            system_exit(1, _("Unable to authenticate to legacy server.  ") + SEE_LOG_FILE)
Beispiel #16
0
 def get_org(self, username):
     try:
         owner_list = self.cp.getOwnerList(username)
     except Exception, e:
         log.error(e)
         log.error(traceback.format_exc())
         system_exit(1, CONNECTION_FAILURE % e)
 def legacy_unentitle(self, rpc_session):
     system_id = open(self.rhncfg["systemIdPath"], 'r').read()
     try:
         rpc_session.system.unentitle(system_id)
     except Exception, e:
         log.exception("Could not unentitle system on Satellite 5.", e)
         system_exit(1, _("Could not unentitle system on legacy server.  ") + SEE_LOG_FILE)
Beispiel #18
0
    def transfer_http_proxy_settings(self):
        if self.rhncfg['enableProxy']:
            http_proxy = self.rhncfg['httpProxy']
            if http_proxy[:7] == "http://":
                http_proxy = http_proxy[7:]
            try:
                self.proxy_host, self.proxy_port = http_proxy.split(':')
            except ValueError, e:
                log.exception(e)
                system_exit(1, _("Unable to read RHN proxy settings."))

            if self.rhncfg['enableProxyAuth']:
                self.proxy_user = self.rhncfg['proxyUser']
                self.proxy_pass = self.rhncfg['proxyPassword']

            log.info("Using proxy %s:%s" % (self.proxy_host, self.proxy_port))
            if self.options.noproxy:
                # If the user doesn't want to use a proxy to connect to their subscription
                # management server, then remove any proxy information that may have crept in.
                self.rhsmcfg.set('server', 'proxy_hostname', '')
                self.rhsmcfg.set('server', 'proxy_port', '')
                self.rhsmcfg.set('server', 'proxy_user', '')
                self.rhsmcfg.set('server', 'proxy_password', '')
            else:
                self.rhsmcfg.set('server', 'proxy_hostname', self.proxy_host)
                self.rhsmcfg.set('server', 'proxy_port', self.proxy_port)
                self.rhsmcfg.set('server', 'proxy_user', self.proxy_user or '')
                self.rhsmcfg.set('server', 'proxy_password', self.proxy_pass
                                 or '')
            self.rhsmcfg.save()
    def register(self, credentials, org, environment):
        # For registering the machine, use the CLI tool to reuse the username/password (because the GUI will prompt for them again)
        # Prepended a \n so translation can proceed without hitch
        print ("")
        print _("Attempting to register system to destination server...")
        cmd = ['subscription-manager', 'register', '--username='******'--password='******'--serverurl=' + self.options.destination_url)

        if org:
            cmd.append('--org=' + org)
        if environment:
            cmd.append('--environment=' + environment)

        if self.options.five_to_six:
            if self.consumer_exists(self.consumer_id):
                cmd.append('--consumerid=' + self.consumer_id)

        if self.options.auto:
            cmd.append('--auto-attach')

        if self.options.service_level:
            servicelevel = self.select_service_level(org, self.options.service_level)
            cmd.append('--servicelevel=' + servicelevel)

        subprocess.call(cmd)

        identity = inj.require(inj.IDENTITY)
        identity.reload()

        if not identity.is_valid():
            system_exit(2, _("\nUnable to register.\nFor further assistance, please contact Red Hat Global Support Services."))

        print _("System '%s' successfully registered.\n") % identity.name
        return identity
Beispiel #20
0
    def transfer_http_proxy_settings(self):
        if self.rhncfg['enableProxy']:
            http_proxy = self.rhncfg['httpProxy']
            if http_proxy[:7] == "http://":
                http_proxy = http_proxy[7:]
            try:
                self.proxy_host, self.proxy_port = http_proxy.split(':')
            except ValueError as e:
                log.exception(e)
                system_exit(os.EX_CONFIG, _("Could not read legacy proxy settings.  ") + SEE_LOG_FILE)

            if self.rhncfg['enableProxyAuth']:
                self.proxy_user = self.rhncfg['proxyUser']
                self.proxy_pass = self.rhncfg['proxyPassword']

            log.info("Using proxy %s:%s" % (self.proxy_host, self.proxy_port))
            if self.options.noproxy:
                # If the user doesn't want to use a proxy to connect to their subscription
                # management server, then remove any proxy information that may have crept in.
                self.rhsmcfg['server']['proxy_hostname'] = ''
                self.rhsmcfg['server']['proxy_port'] = ''
                self.rhsmcfg['server']['proxy_user'] = ''
                self.rhsmcfg['server']['proxy_password'] = ''
            else:
                self.rhsmcfg['server']['proxy_hostname'] = self.proxy_host
                self.rhsmcfg['server']['proxy_port'] = self.proxy_port
                self.rhsmcfg['server']['proxy_user'] = self.proxy_user or ''
                self.rhsmcfg['server']['proxy_password'] = self.proxy_pass or ''
            self.rhsmcfg.persist()
Beispiel #21
0
    def transfer_http_proxy_settings(self):
        if self.rhncfg['enableProxy']:
            http_proxy = self.rhncfg['httpProxy']
            if http_proxy[:7] == "http://":
                http_proxy = http_proxy[7:]
            try:
                self.proxy_host, self.proxy_port = http_proxy.split(':')
            except ValueError as e:
                log.exception(e)
                system_exit(
                    os.EX_CONFIG,
                    _("Could not read legacy proxy settings.  ") +
                    SEE_LOG_FILE)

            if self.rhncfg['enableProxyAuth']:
                self.proxy_user = self.rhncfg['proxyUser']
                self.proxy_pass = self.rhncfg['proxyPassword']

            log.info("Using proxy %s:%s" % (self.proxy_host, self.proxy_port))
            if self.options.noproxy:
                # If the user doesn't want to use a proxy to connect to their subscription
                # management server, then remove any proxy information that may have crept in.
                self.rhsmcfg['server']['proxy_hostname'] = ''
                self.rhsmcfg['server']['proxy_port'] = ''
                self.rhsmcfg['server']['proxy_user'] = ''
                self.rhsmcfg['server']['proxy_password'] = ''
            else:
                self.rhsmcfg['server']['proxy_hostname'] = self.proxy_host
                self.rhsmcfg['server']['proxy_port'] = self.proxy_port
                self.rhsmcfg['server']['proxy_user'] = self.proxy_user or ''
                self.rhsmcfg['server'][
                    'proxy_password'] = self.proxy_pass or ''
            self.rhsmcfg.persist()
Beispiel #22
0
    def register(self, credentials, org, environment):
        # For registering the machine, use the CLI tool to reuse the username/password (because the GUI will prompt for them again)
        # Prepended a \n so translation can proceed without hitch
        print("")
        print _(
            "Attempting to register system to Red Hat Subscription Management..."
        )
        cmd = [
            'subscription-manager', 'register',
            '--username='******'--password='******'--serverurl=' + self.options.serverurl)

        if org:
            cmd.append('--org=' + org)
        if environment:
            cmd.append('--environment=' + environment)

        result = subprocess.call(cmd)

        identity = inj.require(inj.IDENTITY)
        identity.reload()

        if result != 0:
            system_exit(
                2,
                _("\nUnable to register.\nFor further assistance, please contact Red Hat Global Support Services."
                  ))
        else:
            print _(
                "System '%s' successfully registered to Red Hat Subscription Management.\n"
            ) % identity.name
        return identity
Beispiel #23
0
    def connect_to_rhn(self, credentials):
        hostname = self.rhncfg['serverURL'].split('/')[2]
        server_url = 'https://%s/rpc/api' % (hostname)

        try:
            if self.rhncfg['enableProxy']:
                proxy = "%s:%s" % (self.proxy_host, self.proxy_port)
                log.info("Using proxy %s for legacy API methods" % (proxy))
                if self.rhncfg['enableProxyAuth']:
                    proxy = "@".join(
                        ["%s:%s" % (self.proxy_user, self.proxy_pass), proxy])
            else:
                proxy = None

            rpc_session = rpclib.Server(server_url, proxy=proxy)

            ca = self.rhncfg["sslCACert"]
            rpc_session.add_trusted_cert(ca)

            if credentials.username and credentials.password:
                session_key = rpc_session.auth.login(credentials.username,
                                                     credentials.password)
            else:
                session_key = None

            return (rpc_session, session_key)
        except Exception as e:
            log.exception(e)
            system_exit(
                1,
                _("Unable to authenticate to legacy server.  ") + SEE_LOG_FILE)
Beispiel #24
0
    def _get_connection_info(self):
        url_parse_error = os.EX_USAGE
        try:
            if self.options.destination_url is None:
                url_parse_error = os.EX_CONFIG
                hostname = self.rhsmcfg['server']['hostname']
                port = self.rhsmcfg['server'].get_int('port')
                prefix = self.rhsmcfg['server']['prefix']
            else:
                (_user, _password, hostname, port,
                 prefix) = parse_url(self.options.destination_url,
                                     default_port=443)
        except ServerUrlParseError as e:
            system_exit(url_parse_error,
                        _("Error parsing server URL: %s") % e.msg)

        connection_info = {
            'host': hostname,
            'ssl_port': int(port),
            'handler': prefix
        }

        if not self.options.noproxy:
            connection_info['proxy_hostname_arg'] = self.proxy_host
            connection_info['proxy_port_arg'] = self.proxy_port and int(
                self.proxy_port)
            connection_info['proxy_user_arg'] = self.proxy_user
            connection_info['proxy_password_arg'] = self.proxy_pass

        return connection_info
    def unregister_system_from_rhn_classic(self, sc, sk):
        system_id_path = self.rhncfg["systemIdPath"]
        system_id = self.get_system_id()

        log.info("Deleting system %s from RHN Classic...", system_id)
        try:
            result = sc.system.deleteSystems(sk, system_id)
        except Exception:
            log.error("Could not delete system %s from RHN Classic" % system_id)
            log.error(traceback.format_exc())
            shutil.move(system_id_path, system_id_path + ".save")
            self.disable_yum_rhn_plugin()
            print _(
                "Did not receive a completed unregistration message from RHN Classic for system %s.\n"
                "Please investigate on the Customer Portal at https://access.redhat.com."
            ) % system_id
            return

        if result:
            log.info("System %s deleted.  Removing systemid file and disabling rhnplugin.conf", system_id)
            os.remove(system_id_path)
            self.disable_yum_rhn_plugin()
            print _("System successfully unregistered from RHN Classic.")
        else:
            system_exit(1, _("Unable to unregister system from RHN Classic.  Exiting."))
    def register(self, credentials, org, environment):
        # For registering the machine, use the CLI tool to reuse the username/password (because the GUI will prompt for them again)
        # Prepended a \n so translation can proceed without hitch
        print ("")
        print _("Attempting to register system to Red Hat Subscription Management...")
        cmd = [
            "subscription-manager",
            "register",
            "--username="******"--password="******"--serverurl=" + self.options.serverurl)

        if org:
            cmd.append("--org=" + org)
        if environment:
            cmd.append("--environment=" + environment)

        result = subprocess.call(cmd)

        identity = inj.require(inj.IDENTITY)
        identity.reload()

        if result != 0:
            system_exit(
                2, _("\nUnable to register.\nFor further assistance, please contact Red Hat Global Support Services.")
            )
        else:
            print _("System '%s' successfully registered to Red Hat Subscription Management.\n") % identity.name
        return identity
Beispiel #27
0
    def check_ok_to_proceed(self, username):
        # check if this machine is already registered to Certicate-based RHN
        identity = inj.require(inj.IDENTITY)
        if identity.is_valid():
            if self.options.five_to_six:
                msgs = [
                    _("This system appears to already be registered to Satellite 6."
                      )
                ]
            else:
                msgs = [
                    _("This system appears to already be registered to Red Hat Subscription Management."
                      )
                ]
                msgs.append(
                    _("Please visit https://access.redhat.com/management/consumers/%s to view the profile details."
                      ) % identity.uuid)
            system_exit(1, msgs)

        try:
            self.cp.getOwnerList(username)
        except SSLError, e:
            print _(
                "The CA certificate for the destination server has not been installed."
            )
            system_exit(1, CONNECTION_FAILURE % e)
 def get_subscribed_channels_list(self):
     try:
         subscribed_channels = map(lambda x: x["label"], getChannels().channels())
     except Exception:
         log.error(traceback.format_exc())
         system_exit(1, _("Problem encountered getting the list of subscribed channels.  Exiting."))
     return subscribed_channels
 def get_org(self, username):
     try:
         owner_list = self.cp.getOwnerList(username)
     except Exception, e:
         log.error(e)
         log.error(traceback.format_exc())
         system_exit(1, CONNECTION_FAILURE % e)
Beispiel #30
0
    def select_service_level(self, org, servicelevel):
        not_supported = _(
            "Error: The service-level command is not supported by the server.")
        try:
            levels = self.cp.getServiceLevelList(org)
        except RemoteServerException as e:
            system_exit(-1, not_supported)
        except RestlibException as e:
            if e.code == 404:
                # no need to die, just skip it
                print(not_supported)
                return None
            else:
                # server supports it but something went wrong, die.
                raise e

        # Create the sla tuple before appending the empty string to the list of
        # valid slas.
        slas = [(sla, sla) for sla in levels]
        # Display an actual message for the empty string level.
        slas.append((_("No service level preference"), ""))

        # The empty string is a valid level so append it to the list.
        levels.append("")
        if servicelevel is None or \
            servicelevel.upper() not in (level.upper() for level in levels):
            if servicelevel is not None:
                print(
                    _("\nService level \"%s\" is not available.") %
                    servicelevel)
            menu = Menu(
                slas,
                _("Please select a service level agreement for this system."))
            servicelevel = menu.choose()
        return servicelevel
Beispiel #31
0
    def __init__(self, options):
        self.rhncfg = initUp2dateConfig()
        self.rhsmcfg = config.Config(initConfig())

        # Sometimes we need to send up the entire contents of the system id file
        # which is referred to in Satellite 5 nomenclature as a "certificate"
        # although it is not an X509 certificate.
        try:
            self.system_id_contents = open(self.rhncfg["systemIdPath"], 'r').read()
        except IOError:
            system_exit(os.EX_IOERR, _("Could not read legacy system id at %s") % self.rhncfg["systemIdPath"])

        self.system_id = self.get_system_id(self.system_id_contents)

        self.proxy_host = None
        self.proxy_port = None
        self.proxy_user = None
        self.proxy_pass = None

        self.cp = None
        self.db = ProductDatabase()

        self.consumer_id = None

        self.options = options
        self.is_hosted = is_hosted()
Beispiel #32
0
    def _do_command(self):
        self._validate_options()
        facts = inj.require(inj.FACTS)

        if self.options.list:
            facts_dict = facts.get_facts()
            facts_keys = sorted(facts_dict.keys())

            for key in facts_keys:
                value = facts_dict[key]
                if str(value).strip() == "":
                    value = _("Unknown")
                print("{key}: {value}".format(key=key, value=value))

        if self.options.update:
            identity = inj.require(inj.IDENTITY)
            try:
                facts.update_check(self.cp, identity.uuid, force=True)
            except connection.GoneException as ge:
                raise ge
            except connection.RestlibException as re:
                log.exception(re)
                system_exit(os.EX_SOFTWARE, str(re))
            log.debug("Succesfully updated the system facts.")
            print(_("Successfully updated the system facts."))
    def transfer_http_proxy_settings(self):
        if self.rhncfg["enableProxy"]:
            http_proxy = self.rhncfg["httpProxy"]
            if http_proxy[:7] == "http://":
                http_proxy = http_proxy[7:]
            try:
                self.proxy_host, self.proxy_port = http_proxy.split(":")
            except ValueError, e:
                log.exception(e)
                system_exit(1, _("Unable to read RHN proxy settings."))

            if self.rhncfg["enableProxyAuth"]:
                self.proxy_user = self.rhncfg["proxyUser"]
                self.proxy_pass = self.rhncfg["proxyPassword"]

            log.info("Using proxy %s:%s" % (self.proxy_host, self.proxy_port))
            if self.options.noproxy:
                # If the user doesn't want to use a proxy to connect to their subscription
                # management server, then remove any proxy information that may have crept in.
                self.rhsmcfg.set("server", "proxy_hostname", "")
                self.rhsmcfg.set("server", "proxy_port", "")
                self.rhsmcfg.set("server", "proxy_user", "")
                self.rhsmcfg.set("server", "proxy_password", "")
            else:
                self.rhsmcfg.set("server", "proxy_hostname", self.proxy_host)
                self.rhsmcfg.set("server", "proxy_port", self.proxy_port)
                self.rhsmcfg.set("server", "proxy_user", self.proxy_user or "")
                self.rhsmcfg.set("server", "proxy_password", self.proxy_pass or "")
            self.rhsmcfg.save()
 def load_transition_data(self, rpc_session):
     try:
         transition_data = rpc_session.system.transitionDataForSystem(self.system_id_contents)
         self.consumer_id = transition_data['uuid']
     except Exception, e:
         log.exception(e)
         system_exit(1, _("Could not retrieve system migration data from legacy server.  ") + SEE_LOG_FILE)
    def legacy_purge(self, rpc_session, session_key):
        system_id_path = self.rhncfg["systemIdPath"]

        log.info("Deleting system %s from legacy server...", self.system_id)
        try:
            result = rpc_session.system.deleteSystems(session_key, self.system_id)
        except Exception:
            log.exception("Could not delete system %s from legacy server" % self.system_id)
            # If we time out or get a network error, log it and keep going.
            shutil.move(system_id_path, system_id_path + ".save")
            print _("Did not receive a completed unregistration message from legacy server for system %s.") % self.system_id

            if self.is_hosted:
                print _("Please investigate on the Customer Portal at https://access.redhat.com.")
            return

        if result:
            log.info("System %s deleted.  Removing system id file and disabling rhnplugin.conf", self.system_id)
            os.remove(system_id_path)
            try:
                self.disable_yum_rhn_plugin()
            except Exception:
                pass
            print _("System successfully unregistered from legacy server.")
        else:
            # If the legacy server reports that deletion just failed, then quit.
            system_exit(1, _("Unable to unregister system from legacy server.  ") + SEE_LOG_FILE)
Beispiel #36
0
 def assert_should_be_registered(self):
     if not self.is_consumer_cert_present():
         system_exit(ERR_NOT_REGISTERED_CODE, ERR_NOT_REGISTERED_MSG)
     elif not self.is_registered():
         system_exit(
             os.EX_DATAERR,
             _("Consumer identity either does not exist or is corrupted. Try register --help"
               ))
 def check_for_conflicting_channels(self, subscribed_channels):
     jboss_channel = False
     for channel in subscribed_channels:
         if channel.startswith("jbappplatform"):
             if jboss_channel:
                 system_exit(1, _("You are subscribed to more than one jbappplatform channel."
                                 "  This script does not support that configuration."))
             jboss_channel = True
 def check_is_org_admin(self, sc, sk, username):
     try:
         roles = sc.user.listRoles(sk, username)
     except Exception:
         log.error(traceback.format_exc())
         system_exit(1, _("Problem encountered determining user roles in RHN Classic.  Exiting."))
     if "org_admin" not in roles:
         system_exit(1, _("You must be an org admin to successfully run this script."))
Beispiel #39
0
 def check_for_conflicting_channels(self, subscribed_channels):
     jboss_channel = False
     for channel in subscribed_channels:
         if channel.startswith("jbappplatform"):
             if jboss_channel:
                 system_exit(1, _("You are subscribed to more than one jbappplatform channel."
                                 "  This script does not support that configuration."))
             jboss_channel = True
Beispiel #40
0
 def update_service_level(self, service_level):
     consumer = self.cp.getConsumer(self.identity.uuid)
     if 'serviceLevel' not in consumer:
         system_exit(
             os.EX_UNAVAILABLE,
             _("Error: The service-level command is not supported by the server."
               ))
     self.cp.updateConsumer(self.identity.uuid, service_level=service_level)
Beispiel #41
0
    def _do_command(self):
        self._validate_options()

        self.cp = None
        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:
                try:
                    self.cp = self.cp_provider.get_keycloak_auth_cp(
                        self.options.token)
                except Exception as err:
                    log.error(
                        "unable to connect to candlepin server using token: \"{token}\", err: {err}"
                        .format(token=self.options.token, err=err))
                    print(_("Unable to connect to server using token"))
            elif self.options.username and self.options.password:
                self.cp_provider.set_user_pass(self.options.username,
                                               self.options.password)
                self.cp = self.cp_provider.get_basic_auth_cp()
            else:
                # get an UEP as consumer
                if self.is_registered():
                    self.cp = self.cp_provider.get_consumer_auth_cp()
        except connection.RestlibException as err:
            log.exception(err)
            if getattr(self.options, 'list', None):
                log.error(
                    "Error: Unable to retrieve {attr} from server: {err}".
                    format(attr=self.attr, err=err))
                system_exit(os.EX_SOFTWARE, str(err))
            else:
                log.debug(
                    "Error: Unable to retrieve {attr} from server: {err}".
                    format(attr=self.attr, err=err))
        except Exception as err:
            log.debug(
                "Error: Unable to retrieve {attr} from server: {err}".format(
                    attr=self.attr, err=err))

        self.store = SyncedStore(uep=self.cp, consumer_uuid=self.identity.uuid)

        if getattr(self.options, 'unset', None):
            self.unset()
        elif getattr(self.options, 'set', None):
            self.set()
        elif hasattr(self.options, 'to_add') and len(self.options.to_add) > 0:
            self.add()
        elif hasattr(self.options,
                     'to_remove') and len(self.options.to_remove) > 0:
            self.remove()
        elif getattr(self.options, 'list', None):
            self.list()
        elif getattr(self.options, 'show', None):
            self.show()
        else:
            self.show()
Beispiel #42
0
 def get_subscribed_channels_list(self, rpc_session, session_key):
     try:
         channels = getChannels().channels()
     except Exception as e:
         log.exception(e)
         system_exit(os.EX_SOFTWARE, _("Problem encountered getting the list of subscribed channels.  ") + SEE_LOG_FILE)
     if self.options.five_to_six:
         channels = [self.resolve_base_channel(c['label'], rpc_session, session_key) for c in channels]
     return [x['label'] for x in channels]
Beispiel #43
0
 def resolve_base_channel(self, label, rpc_session, session_key):
     try:
         details = rpc_session.channel.software.getDetails(session_key, label)
     except Exception as e:
         log.exception(e)
         system_exit(os.EX_SOFTWARE, _("Problem encountered getting the list of subscribed channels.  ") + SEE_LOG_FILE)
     if details['clone_original']:
         return self.resolve_base_channel(details['clone_original'], rpc_session, session_key)
     return details
Beispiel #44
0
 def get_subscribed_channels_list(self, rpc_session, session_key):
     try:
         channels = getChannels().channels()
     except Exception, e:
         log.exception(e)
         system_exit(
             1,
             _("Problem encountered getting the list of subscribed channels.  "
               ) + SEE_LOG_FILE)
Beispiel #45
0
 def check_is_org_admin(self, rpc_session, session_key, username):
     try:
         roles = rpc_session.user.listRoles(session_key, username)
     except Exception, e:
         log.exception(e)
         system_exit(
             1,
             _("Problem encountered determining user roles on legacy server.  "
               ) + SEE_LOG_FILE)
Beispiel #46
0
 def resolve_base_channel(self, label, rpc_session, session_key):
     try:
         details = rpc_session.channel.software.getDetails(session_key, label)
     except Exception as e:
         log.exception(e)
         system_exit(os.EX_SOFTWARE, _("Problem encountered getting the list of subscribed channels.  ") + SEE_LOG_FILE)
     if details['clone_original']:
         return self.resolve_base_channel(details['clone_original'], rpc_session, session_key)
     return details
Beispiel #47
0
 def get_subscribed_channels_list(self, rpc_session, session_key):
     try:
         channels = getChannels().channels()
     except Exception as e:
         log.exception(e)
         system_exit(os.EX_SOFTWARE, _("Problem encountered getting the list of subscribed channels.  ") + SEE_LOG_FILE)
     if self.options.five_to_six:
         channels = [self.resolve_base_channel(c['label'], rpc_session, session_key) for c in channels]
     return [x['label'] for x in channels]
 def get_environment(self, owner_key):
     environment_list = []
     try:
         if self.cp.supports_resource('environments'):
             environment_list = self.cp.getEnvironmentList(owner_key)
         elif self.options.environment:
             system_exit(os.EX_UNAVAILABLE, _("Environments are not supported by this server."))
     except Exception, e:
         log.exception(e)
         system_exit(os.EX_SOFTWARE, CONNECTION_FAILURE % e)
 def _get_connection_info(self):
     try:
         if self.options.destination_url is None:
             hostname = self.rhsmcfg.get('server', 'hostname')
             port = self.rhsmcfg.get_int('server', 'port')
             prefix = self.rhsmcfg.get('server', 'prefix')
         else:
             (_user, _password, hostname, port, prefix) = parse_url(self.options.destination_url, default_port=443)
     except ServerUrlParseError, e:
         system_exit(-1, _("Error parsing server URL: %s") % e.msg)
 def load_transition_data(self, rpc_session):
     # We need to send up the entire contents of the systemid file which is referred to in
     # Satellite 5 nomenclature as a "certificate" although it is not an X509 certificate.
     system_id = open(self.rhncfg["systemIdPath"], 'r').read()
     try:
         transition_data = rpc_session.system.transitionDataForSystem(system_id)
         self.consumer_id = transition_data['uuid']
     except Exception, e:
         log.exception(e)
         system_exit(1, _("Could not retrieve system migration data from legacy server.  ") + SEE_LOG_FILE)
 def _get_connection_info(self):
     try:
         if self.options.serverurl is None:
             hostname = self.rhsmcfg.get("server", "hostname")
             port = self.rhsmcfg.get_int("server", "port")
             prefix = self.rhsmcfg.get("server", "prefix")
         else:
             (hostname, port, prefix) = parse_server_info(self.options.serverurl)
     except ServerUrlParseError, e:
         system_exit(-1, _("Error parsing server URL: %s") % e.msg)
Beispiel #52
0
 def legacy_unentitle(self, rpc_session):
     try:
         rpc_session.system.unentitle(self.system_id_contents)
     except Exception as e:
         log.exception("Could not remove system entitlement on Satellite 5.", e)
         system_exit(os.EX_SOFTWARE, _("Could not remove system entitlement on legacy server.  ") + SEE_LOG_FILE)
     try:
         self.disable_yum_rhn_plugin()
     except Exception:
         pass
 def get_environment(self, owner_key):
     environment_list = []
     try:
         if self.cp.supports_resource("environments"):
             environment_list = self.cp.getEnvironmentList(owner_key)
         elif self.options.environment:
             system_exit(1, _("Environments are not supported by this server."))
     except Exception, e:
         log.error(e)
         log.error(traceback.format_exc())
         system_exit(1, CONNECTION_FAILURE % e)
Beispiel #54
0
def check_result(syspurposestore, expectation, success_msg, command, attr):
    if syspurposestore:
        syspurposestore.sync()
        result = syspurposestore.get_cached_contents()
    else:
        result = {}
    if result and not expectation(result):
        advice = SP_ADVICE.format(command=command)
        system_exit(os.EX_SOFTWARE, msgs=_(SP_CONFLICT_MESSAGE.format(attr=attr, advice=advice)))
    else:
        print(_(success_msg))
Beispiel #55
0
    def check_has_access(self, rpc_session, session_key):
        try:
            if session_key is None:
                # We should not ever be here.  This method has a guard that keeps it from being
                # called when not needed.  If we see this error, someone has made a programming
                # mistake.
                raise Exception("No session key available.  Check that XMLRPC connection is being made with credentials.")

            rpc_session.system.getDetails(session_key, self.system_id)
        except Exception as e:
            log.exception(e)
            system_exit(1, _("You do not have access to system %s.  ") % self.system_id + SEE_LOG_FILE)
    def deploy_prod_certificates(self, subscribed_channels):
        release = self.get_release()
        mappingfile = "/usr/share/rhsm/product/" + release + "/channel-cert-mapping.txt"
        log.info("Using mapping file %s", mappingfile)

        try:
            dic_data = self.read_channel_cert_mapping(mappingfile)
        except IOError, e:
            log.exception(e)
            system_exit(os.EX_CONFIG, _("Unable to read mapping file: %(mappingfile)s.\n"
                "Please check that you have the %(package)s package installed.") % {
                    "mappingfile": mappingfile,
                    "package": "subscription-manager-migration-data"})
Beispiel #57
0
 def get_release(self):
     f = open('/etc/redhat-release')
     lines = f.readlines()
     f.close()
     try:
         major_version = re.search("[0-9]+(?=\.[0-9]+)*", str(lines)).group(0)
     except AttributeError:
         log.error("Could not determine RHEL release from /etc/redhat-release")
         # Leaving no message to stdout/stderr as it's past string freeze
         system_exit(1, "")
     else:
         release = "RHEL-" + major_version
     return release
    def check_ok_to_proceed(self):
        # check if this machine is already registered to Certicate-based RHN
        identity = inj.require(inj.IDENTITY)
        if identity.is_valid():
            if self.options.five_to_six:
                msgs = [_("This system appears to already be registered to Satellite 6.")]
            else:
                msgs = [_("This system appears to already be registered to Red Hat Subscription Management.")]
                msgs.append(_("Please visit https://access.redhat.com/management/consumers/%s to view the profile details.") % identity.uuid)
            system_exit(1, msgs)

        try:
            self.cp.getStatus()
        except SSLError, e:
            print _("The CA certificate for the destination server has not been installed.")
            system_exit(os.EX_SOFTWARE, CONNECTION_FAILURE % e)
    def check_ok_to_proceed(self, username):
        # check if this machine is already registered to Certicate-based RHN
        identity = inj.require(inj.IDENTITY)
        if identity.is_valid():
            print _("\nThis system appears to be already registered to Red Hat Subscription Management.  Exiting.")
            system_exit(
                1,
                _("\nPlease visit https://access.redhat.com/management/consumers/%s to view the profile details.")
                % identity.uuid,
            )

        try:
            self.cp.getOwnerList(username)
        except SSLError, e:
            print _("Error: CA certificate for subscription service has not been installed.")
            system_exit(1, CONNECTION_FAILURE % e)
def validate_options(options):
    if options.activation_keys:
        if options.environment:
            system_exit(os.EX_USAGE, _("The --activation-key and --environment options cannot be used together."))
        if options.destination_user or options.destination_password:
            system_exit(os.EX_USAGE, _("The --activation-key option precludes the use of --destination-user and --destination-password"))
        if not options.org:
            system_exit(os.EX_USAGE, _("The --activation-key option requires that a --org be given."))

    if options.service_level and not options.auto:
        # TODO Need to explain why this restriction exists.
        system_exit(os.EX_USAGE, _("The --servicelevel and --no-auto options cannot be used together."))