def test_fails_when_previously_registered(self): self.mock_identity.is_valid.return_value = True with self.assertRaisesRegexp(exceptions.ValidationError, r'.*system is already registered.*'): register.RegisterService(self.mock_cp).validate_options( self._build_options())
def test_register_normally(self, mock_persist_consumer): self.mock_identity.is_valid.return_value = False self.mock_installed_products.format_for_server.return_value = [] self.mock_installed_products.tags = [] expected_consumer = json.loads(CONTENT_JSON) self.mock_cp.registerConsumer.return_value = expected_consumer register_service = register.RegisterService(self.mock_cp) register_service.register("org", name="name", environment="environment") self.mock_cp.registerConsumer.assert_called_once_with( name="name", facts={}, owner="org", environment="environment", keys=None, installed_products=[], content_tags=[]) self.mock_installed_products.write_cache.assert_called() mock_persist_consumer.assert_called_once_with(expected_consumer) expected_plugin_calls = [ mock.call('pre_register_consumer', name='name', facts={}), mock.call('post_register_consumer', consumer=expected_consumer, facts={}) ] self.assertEqual(expected_plugin_calls, self.mock_pm.run.call_args_list)
def test_register_with_consumerid(self, mock_persist_consumer, mock_write_cache): self.mock_identity.is_valid.return_value = False self.mock_installed_products.format_for_server.return_value = [] self.mock_installed_products.tags = [] expected_consumer = json.loads(CONSUMER_CONTENT_JSON) self.mock_cp.getConsumer.return_value = json.loads( CONSUMER_CONTENT_JSON) register_service = register.RegisterService(self.mock_cp) register_service.register("org", name="name", consumerid="consumerid") self.mock_cp.getConsumer.assert_called_once_with("consumerid") self.mock_installed_products.write_cache.assert_called() mock_persist_consumer.assert_called_once_with(expected_consumer) mock_write_cache.assert_called_once() expected_plugin_calls = [ mock.call("pre_register_consumer", name="name", facts={}), mock.call("post_register_consumer", consumer=expected_consumer, facts={}), ] self.assertEqual(expected_plugin_calls, self.mock_pm.run.call_args_list)
def test_register_with_activation_keys(self, mock_persist_consumer): self.mock_cp.username = None self.mock_cp.password = None self.mock_identity.is_valid.return_value = False self.mock_installed_products.format_for_server.return_value = [] self.mock_installed_products.tags = [] expected_consumer = json.loads(CONSUMER_CONTENT_JSON) self.mock_cp.registerConsumer.return_value = expected_consumer register_service = register.RegisterService(self.mock_cp) register_service.register("org", name="name", activation_keys=[1]) self.mock_cp.registerConsumer.assert_called_once_with( name="name", facts={}, owner="org", environment=None, keys=[1], installed_products=[], content_tags=[], type="system", role="", addons=[], service_level="", usage="" ) self.mock_installed_products.write_cache.assert_called() mock_persist_consumer.assert_called_once_with(expected_consumer) expected_plugin_calls = [ mock.call('pre_register_consumer', name='name', facts={}), mock.call('post_register_consumer', consumer=expected_consumer, facts={}) ] self.assertEqual(expected_plugin_calls, self.mock_pm.run.call_args_list)
def test_reads_syspurpose(self, mock_persist_consumer): self.mock_installed_products.format_for_server.return_value = [] self.mock_installed_products.tags = [] self.mock_identity.is_valid.return_value = False self.mock_sp_store_contents["role"] = "test_role" self.mock_sp_store_contents["service_level_agreement"] = "test_sla" self.mock_sp_store_contents["addons"] = ["addon1"] self.mock_sp_store_contents["usage"] = "test_usage" expected_consumer = json.loads(CONSUMER_CONTENT_JSON) self.mock_cp.registerConsumer.return_value = expected_consumer register_service = register.RegisterService(self.mock_cp) register_service.register("org", name="name") self.mock_cp.registerConsumer.assert_called_once_with( addons=["addon1"], content_tags=[], environment=None, facts={}, installed_products=[], keys=None, name="name", owner="org", role="test_role", service_level="test_sla", type="system", usage="test_usage")
def test_does_not_require_basic_auth_with_activation_keys(self): self.mock_cp.username = None self.mock_cp.password = None self.mock_identity.is_valid.return_value = False options = self._build_options(activation_keys=[1]) register.RegisterService(self.mock_cp).validate_options(options)
def test_register_with_no_insights_with_systemctl_failure(self, mock_persist_consumer, mock_subprocess_call, mock_write_cache): self.mock_identity.is_valid.return_value = False self.mock_installed_products.format_for_server.return_value = [] self.mock_installed_products.tags = [] expected_consumer = json.loads(CONSUMER_CONTENT_JSON) self.mock_cp.registerConsumer.return_value = expected_consumer mock_subprocess_call.side_effect = Exception register_service = register.RegisterService(self.mock_cp) register_service.register("org", name="name", environment="environment", no_insights=True) self.mock_cp.registerConsumer.assert_called_once_with( name="name", facts={}, owner="org", environment="environment", keys=None, installed_products=[], content_tags=[], type="system", role="", addons=[], service_level="", usage="") self.mock_installed_products.write_cache.assert_called() mock_persist_consumer.assert_called_once_with(expected_consumer) mock_write_cache.assert_called_once() expected_plugin_calls = [ mock.call('pre_register_consumer', name='name', facts={}), mock.call('post_register_consumer', consumer=expected_consumer, facts={}) ] self.assertEqual(expected_plugin_calls, self.mock_pm.run.call_args_list)
def test_does_not_allow_environment_with_consumerid(self): self.mock_cp.username = None self.mock_cp.password = None self.mock_identity.is_valid.return_value = False options = self._build_options(activation_keys=[1], consumerid='consumerid') with self.assertRaisesRegexp(exceptions.ValidationError, r'.*previously registered.*'): register.RegisterService(self.mock_cp).validate_options(options)
def test_does_not_allow_environment_with_activation_keys(self): self.mock_cp.username = None self.mock_cp.password = None self.mock_identity.is_valid.return_value = False options = self._build_options(activation_keys=[1], environment='environment') with self.assertRaisesRegexp(exceptions.ValidationError, r'.*do not allow environments.*'): register.RegisterService(self.mock_cp).validate_options(options)
def test_requires_basic_auth_for_normal_registration(self): self.mock_cp.username = None self.mock_cp.password = None self.mock_identity.is_valid.return_value = False options = self._build_options(consumerid='consumerid') with self.assertRaisesRegexp(exceptions.ValidationError, r'.*Missing username.*'): register.RegisterService(self.mock_cp).validate_options(options)
def test_register_normally_old_candlepin(self, mock_persist_consumer, mock_write_cache): """ Test for the case, when candlepin server returns consumer without information about content access mode. """ self.mock_identity.is_valid.return_value = False self.mock_installed_products.format_for_server.return_value = [] self.mock_installed_products.tags = [] expected_consumer = json.loads(OLD_CONSUMER_CONTENT_JSON) self.mock_cp.registerConsumer.return_value = expected_consumer register_service = register.RegisterService(self.mock_cp) consumer = register_service.register("org", name="name", environments="environment") self.mock_cp.registerConsumer.assert_called_once_with( name="name", facts={}, owner="org", environments="environment", keys=None, installed_products=[], jwt_token=None, content_tags=[], type="system", role="", addons=[], service_level="", usage="", ) self.mock_installed_products.write_cache.assert_called() mock_persist_consumer.assert_called_once_with(expected_consumer) mock_write_cache.assert_called_once() expected_plugin_calls = [ mock.call("pre_register_consumer", name="name", facts={}), mock.call("post_register_consumer", consumer=expected_consumer, facts={}), ] self.assertEqual(expected_plugin_calls, self.mock_pm.run.call_args_list) assert "owner" in consumer assert "contentAccessMode" in consumer["owner"] assert "entitlement" == consumer["owner"]["contentAccessMode"]
def test_register_with_no_insights(self, mock_persist_consumer, mock_subprocess_call, mock_write_cache): self.mock_identity.is_valid.return_value = False self.mock_installed_products.format_for_server.return_value = [] self.mock_installed_products.tags = [] expected_consumer = json.loads(CONSUMER_CONTENT_JSON) self.mock_cp.registerConsumer.return_value = expected_consumer register_service = register.RegisterService(self.mock_cp) mock_open = mock.mock_open() with mock.patch('rhsmlib.services.register.open', mock_open, create=True): register_service.register("org", name="name", environment="environment", no_insights=True) self.mock_cp.registerConsumer.assert_called_once_with( name="name", facts={}, owner="org", environment="environment", keys=None, installed_products=[], content_tags=[], type="system", role="", addons=[], service_level="", usage="") self.mock_installed_products.write_cache.assert_called() mock_persist_consumer.assert_called_once_with(expected_consumer) mock_write_cache.assert_called_once() mock_subprocess_call.assert_called_once_with( ['/usr/bin/systemctl', 'mask', '--now', 'insights-register.path'], stdout=mock_open(), stderr=mock_open()) expected_plugin_calls = [ mock.call('pre_register_consumer', name='name', facts={}), mock.call('post_register_consumer', consumer=expected_consumer, facts={}) ] self.assertEqual(expected_plugin_calls, self.mock_pm.run.call_args_list)
def test_register_normally(self, mock_persist_consumer, mock_write_cache): self.mock_identity.is_valid.return_value = False self.mock_installed_products.format_for_server.return_value = [] self.mock_installed_products.tags = [] expected_consumer = json.loads(CONSUMER_CONTENT_JSON) self.mock_cp.registerConsumer.return_value = expected_consumer register_service = register.RegisterService(self.mock_cp) register_service.register("org", name="name", environments="environment") self.mock_cp.registerConsumer.assert_called_once_with( name="name", facts={}, owner="org", environments="environment", keys=None, installed_products=[], jwt_token=None, content_tags=[], type="system", role="", addons=[], service_level="", usage="", ) self.mock_installed_products.write_cache.assert_called() mock_persist_consumer.assert_called_once_with(expected_consumer) mock_write_cache.assert_called_once() expected_plugin_calls = [ mock.call("pre_register_consumer", name="name", facts={}), mock.call("post_register_consumer", consumer=expected_consumer, facts={}), ] self.assertEqual(expected_plugin_calls, self.mock_pm.run.call_args_list)
def test_does_not_allow_basic_auth_with_activation_keys(self): self.mock_identity.is_valid.return_value = False options = self._build_options(activation_keys=[1]) with self.assertRaisesRegexp(exceptions.ValidationError, r'.*do not require user credentials.*'): register.RegisterService(self.mock_cp).validate_options(options)
def test_allows_force(self): self.mock_identity.is_valid.return_value = True options = self._build_options(force=True) register.RegisterService(self.mock_cp).validate_options(options)
def test_register_normally_with_no_org_specified(self, mock_persist_consumer, mock_write_cache): """ This test is intended for the case, when no organization is specified, but user is member only of one organization and thus it can be automatically selected """ self.mock_cp.getOwnerList = mock.Mock() self.mock_cp.getOwnerList.return_value = [{ "created": "2020-08-18T07:57:47+0000", "updated": "2020-08-18T07:57:47+0000", "id": "ff808081740092cd01740092fe540002", "key": "snowwhite", "displayName": "Snow White", "parentOwner": None, "contentPrefix": None, "defaultServiceLevel": None, "upstreamConsumer": None, "logLevel": None, "autobindDisabled": False, "autobindHypervisorDisabled": False, "contentAccessMode": "entitlement", "contentAccessModeList": "entitlement,org_environment", "lastRefreshed": None, "href": "/owners/snowwhite", }] self.mock_identity.is_valid.return_value = False self.mock_installed_products.format_for_server.return_value = [] self.mock_installed_products.tags = [] expected_consumer = json.loads(CONSUMER_CONTENT_JSON) self.mock_cp.registerConsumer.return_value = expected_consumer register_service = register.RegisterService(self.mock_cp) def _get_owner_cb(orgs): pass def _no_owner_cb(username): pass org = register_service.determine_owner_key( username=self.mock_cp.username, get_owner_cb=_get_owner_cb, no_owner_cb=_no_owner_cb) self.assertIsNotNone(org) register_service.register(org, name="name", environments="environment") self.mock_cp.registerConsumer.assert_called_once_with( name="name", facts={}, owner="snowwhite", environments="environment", keys=None, installed_products=[], jwt_token=None, content_tags=[], type="system", role="", addons=[], service_level="", usage="", ) self.mock_installed_products.write_cache.assert_called() mock_persist_consumer.assert_called_once_with(expected_consumer) mock_write_cache.assert_called_once() expected_plugin_calls = [ mock.call("pre_register_consumer", name="name", facts={}), mock.call("post_register_consumer", consumer=expected_consumer, facts={}), ] self.assertEqual(expected_plugin_calls, self.mock_pm.run.call_args_list)
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