def warnOrGiveUsageMessage(conduit): # XXX: Importing inline as you must be root to read the config file """ either output a warning, or a usage message """ msg = "" # TODO: refactor so there are not two checks for this if os.getuid() != 0: return if ClassicCheck().is_registered_with_classic(): return try: identity = inj.require(inj.IDENTITY) ent_dir = inj.require(inj.ENT_DIR) # Don't warn people to register if we see entitelements, but no identity: if not identity.is_valid() and len(ent_dir.list_valid()) == 0: msg = not_registered_warning elif len(ent_dir.list_valid()) == 0: msg = no_subs_warning if config.in_container() and len(ent_dir.list_valid()) == 0: msg = no_subs_container_warning finally: if msg: conduit.info(2, msg)
def warn_or_usage_message(conduit): """ Display warning message, when the system is not registered (no consumer cert) or then is no entitlement cert """ if os.getuid() != 0: return if ClassicCheck().is_registered_with_classic(): return msg = "" try: identity = inj.require(inj.IDENTITY) ent_dir = inj.require(inj.ENT_DIR) # Don't warn people to register if we see entitlements, but no identity: if not identity.is_valid() and len(ent_dir.list_valid()) == 0: msg = not_registered_warning elif len(ent_dir.list_valid()) == 0 and not is_simple_content_access( identity=identity): msg = no_subs_warning if config.in_container() and len(ent_dir.list_valid()) == 0: msg = no_subs_container_warning finally: if msg: conduit.info(2, msg)
def get_server_versions(cp, exception_on_timeout=False): cp_version = _("Unknown") server_type = _("This system is currently not registered.") rules_version = _("Unknown") identity = inj.require(inj.IDENTITY) # check for Classic before doing anything else if ClassicCheck().is_registered_with_classic(): if identity.is_valid(): server_type = get_branding().REGISTERED_TO_BOTH_SUMMARY else: server_type = get_branding().REGISTERED_TO_OTHER_SUMMARY else: if identity.is_valid(): server_type = get_branding( ).REGISTERED_TO_SUBSCRIPTION_MANAGEMENT_SUMMARY if cp: try: supported_resources = get_supported_resources() if "status" in supported_resources: status = cp.getStatus() cp_version = "-".join([ status.get("version", _("Unknown")), status.get("release", _("Unknown")) ]) rules_version = status.get("rulesVersion", _("Unknown")) except socket.timeout as e: log.error("Timeout error while checking server version") log.exception(e) # for cli, we can assume if we get a timeout here, the rest # of the calls will timeout as well, so raise exception here # instead of waiting for all the calls to timeout if exception_on_timeout: log.error("Timeout error while checking server version") raise # otherwise, ignore the timeout exception except Exception as e: if isinstance(e, GoneException): log.warn( "Server Versions: Error: consumer has been deleted, unable to check server version" ) else: # a more useful error would be handy here log.error("Error while checking server version: %s" % e) log.exception(e) cp_version = _("Unknown") return { "candlepin": cp_version, "server-type": server_type, "rules-version": rules_version }
def _set_validity_status(self): """ Updates the entitlement validity status portion of the UI. """ if ClassicCheck().is_registered_with_classic(): self._set_status_icons(VALID_STATUS) self.subscription_status_label.set_text( get_branding().RHSMD_REGISTERED_TO_OTHER) return is_registered = self.identity.is_valid() self.set_registered(is_registered) warn_count = len(self.backend.cs.unentitled_products) if self.backend.cs.system_status == 'valid': self._set_status_icons(VALID_STATUS) if len(list(self.backend.cs.installed_products.keys())) == 0: # No product certs installed, thus no compliant until date: self.subscription_status_label.set_text( # I18N: Please add newlines if translation is longer: _("No installed products detected.")) elif self.backend.cs.compliant_until: self.subscription_status_label.set_markup( # I18N: Please add newlines if translation is longer: _("System is properly subscribed through %s.") % managerlib.format_date(self.backend.cs.compliant_until)) else: log.warn("Server did not provide a compliant until date.") self.subscription_status_label.set_text( _("System is properly subscribed.")) elif self.backend.cs.system_status == 'partial': self._set_status_icons(PARTIAL_STATUS) self.subscription_status_label.set_markup( # I18N: Please add newlines if translation is longer: _("This system does not match subscription limits.")) elif self.backend.cs.system_status == 'invalid': self._set_status_icons(INVALID_STATUS) if warn_count > 1: self.subscription_status_label.set_markup( # I18N: Please add newlines if translation is longer: _("%s installed products do not have valid subscriptions.") % warn_count) else: self.subscription_status_label.set_markup( # I18N: Please add newlines if translation is longer: _("1 installed product does not have a valid subscription." )) elif self.backend.cs.system_status == 'unknown': self._set_status_icons(UNKNOWN_STATUS) self.subscription_status_label.set_text( # I18N: Please add newlines if translation is longer: _("Keep your system up to date by registering."))
def pre_check_status(force_signal): if force_signal is not None: debug("forcing status signal from cli arg") return force_signal if ClassicCheck().is_registered_with_classic(): debug("System is already registered to another entitlement system") return RHN_CLASSIC identity = require(IDENTITY) sorter = require(CERT_SORTER) if not identity.is_valid() and not sorter.has_entitlements(): debug("The system is not currently registered.") return RHSM_REGISTRATION_REQUIRED return None
def _warnOrGiveUsageMessage(self): """ either output a warning, or a usage message """ msg = "" if ClassicCheck().is_registered_with_classic(): return try: identity = inj.require(inj.IDENTITY) ent_dir = inj.require(inj.ENT_DIR) # Don't warn people to register if we see entitelements, but no identity: if not identity.is_valid() and len(ent_dir.list_valid()) == 0: msg = not_registered_warning elif len(ent_dir.list_valid()) == 0: msg = no_subs_warning finally: if msg: logger.info(msg)
def _warn_or_give_usage_message(): """ Either output a warning, or a usage message """ msg = "" if ClassicCheck().is_registered_with_classic(): return try: identity = inj.require(inj.IDENTITY) ent_dir = inj.require(inj.ENT_DIR) # Don't warn people to register if we see entitlements, but no identity: if not identity.is_valid() and len(ent_dir.list_valid()) == 0: msg = not_registered_warning elif len(ent_dir.list_valid()) == 0 and not is_simple_content_access(identity=identity): msg = no_subs_warning finally: if msg: logger.info(msg)
def warnOrGiveUsageMessage(conduit): # XXX: Importing inline as you must be root to read the config file """ either output a warning, or a usage message """ msg = "" # TODO: refactor so there are not two checks for this if os.getuid() != 0: return if ClassicCheck().is_registered_with_classic(): return try: identity = inj.require(inj.IDENTITY) ent_dir = inj.require(inj.ENT_DIR) # Don't warn people to register if we see entitelements, but no identity: if not identity.is_valid() and len(ent_dir.list_valid()) == 0: msg = not_registered_warning elif len(ent_dir.list_valid()) == 0: # XXX: Importing inline as you must be root to read the config file from subscription_manager.identity import ConsumerIdentity cert_file = ConsumerIdentity.certpath() key_file = ConsumerIdentity.keypath() # In containers we have no identity, but we may have entitlements inherited # from the host, which need to generate a redhat.repo. if identity.is_valid(): try: uep = connection.UEPConnection(cert_file=cert_file, key_file=key_file) # FIXME: catchall exception except Exception: pass else: owner = uep.getOwner(identity.uuid) if owner['contentAccessMode'] != "org_environment": return msg = no_subs_warning if config.in_container() and len(ent_dir.list_valid()) == 0: msg = no_subs_container_warning finally: if msg: conduit.info(2, msg)
def pre_check_status(force_signal): """ Pre check status of the system. Is it registered against classic. Is it registered? :param force_signal: When this is not None, then this value is returned :return: Specified force_signal or RHN_CLASSIC or RHSM_REGISTRATION_REQUIRED or None """ if force_signal is not None: debug("forcing status signal from cli arg") return force_signal if ClassicCheck().is_registered_with_classic(): debug("System is already registered to another entitlement system") return RHN_CLASSIC identity = require(IDENTITY) sorter = require(CERT_SORTER) if not identity.is_valid() and not sorter.has_entitlements(): debug("The system is not currently registered.") return RHSM_REGISTRATION_REQUIRED return None
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)
def _check_rhn_classic(self): if ClassicCheck().is_registered_with_classic(): prompt = messageWindow.ContinueDialog( linkify(get_branding().REGISTERED_TO_OTHER_WARNING), self.main_window, _("System Already Registered")) prompt.connect('response', self._on_rhn_classic_response)
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