def _on_registration_finished_cb(self, new_account, error=None):
        if error is not None:
            handle_gui_exception(error, registergui.REGISTER_ERROR,
                    self._parent.window)
            self._parent.finish_registration(failed=True)
            return

        try:
            managerlib.persist_consumer_cert(new_account)
            self._parent.backend.cs.force_cert_check()  # Ensure there isn't much wait time

            if self._parent.activation_keys:
                self._parent.pre_done(registergui.REFRESH_SUBSCRIPTIONS_PAGE)
            elif self._parent.skip_auto_bind:
                message = _("You have opted to skip auto-attach.")
                self._parent.manual_message = message
                self._parent.pre_done(MANUALLY_SUBSCRIBE_PAGE)
            else:
                self._parent.pre_done(registergui.SELECT_SLA_PAGE)

        # If we get errors related to consumer name on register,
        # go back to the credentials screen where we set the
        # consumer name. See bz#865954
        except RestlibException, e:
            handle_gui_exception(e, registergui.REGISTER_ERROR,
                self._parent.window)
            if e.code == 404 and self._parent.activation_keys:
                self._parent.pre_done(registergui.ACTIVATION_KEY_PAGE)
            if e.code == 400:
                self._parent.pre_done(registergui.CREDENTIALS_PAGE)
示例#2
0
    def _register(self, org, options):
        options = dbus_utils.dbus_to_python(options)
        options = self.validate_options(options)

        environment = options.get('environment')
        facts_dict = self.facts.get_facts()
        consumer_name = options['name']

        self.plugin_manager.run("pre_register_consumer",
                                name=consumer_name,
                                facts=facts_dict)

        cp = self.build_uep(options)
        registration_output = cp.registerConsumer(
            name=consumer_name,
            facts=facts_dict,
            owner=org,
            environment=environment,
            keys=options.get('activation_keys', None),
            installed_products=self.installed_mgr.format_for_server(),
            content_tags=self.installed_mgr.tags)
        self.installed_mgr.write_cache()
        self.plugin_manager.run("post_register_consumer",
                                consumer=registration_output['content'],
                                facts=facts_dict)

        consumer = json.loads(registration_output['content'],
                              object_hook=dbus_utils._decode_dict)
        managerlib.persist_consumer_cert(consumer)

        if 'idCert' in consumer:
            del consumer['idCert']

        registration_output['content'] = json.dumps(consumer)
        return registration_output
示例#3
0
    def _on_registration_finished_cb(self, new_account, error=None):
        if error is not None:
            handle_gui_exception(error, registergui.REGISTER_ERROR,
                    self._parent.window)
            self._parent.finish_registration(failed=True)
            return

        try:
            managerlib.persist_consumer_cert(new_account)
            self._parent.backend.cs.force_cert_check()  # Ensure there isn't much wait time

            if self._parent.activation_keys:
                self._parent.pre_done(registergui.REFRESH_SUBSCRIPTIONS_PAGE)
            elif self._parent.skip_auto_bind:
                message = _("You have opted to skip auto-attach.")
                self._parent.manual_message = message
                self._parent.pre_done(MANUALLY_SUBSCRIBE_PAGE)
            else:
                self._parent.pre_done(registergui.SELECT_SLA_PAGE)

        # If we get errors related to consumer name on register,
        # go back to the credentials screen where we set the
        # consumer name. See bz#865954
        except RestlibException, e:
            handle_gui_exception(e, registergui.REGISTER_ERROR,
                self._parent.window)
            if e.code == 404 and self._parent.activation_keys:
                self._parent.pre_done(registergui.ACTIVATION_KEY_PAGE)
            if e.code == 400:
                self._parent.pre_done(registergui.CREDENTIALS_PAGE)
示例#4
0
    def register(self, org, activation_keys=None, environment=None, force=None, name=None, consumerid=None,
            type=None, role=None, addons=None, service_level=None, usage=None, **kwargs):
        # We accept a kwargs argument so that the DBus object can pass the options dictionary it
        # receives transparently to the service via dictionary unpacking.  This strategy allows the
        # DBus object to be more independent of the service implementation.

        # If there are any values in kwargs that don't map to keyword arguments defined in the message
        # signature we want to consider that an error.
        if kwargs:
            raise exceptions.ValidationError(_("Unknown arguments: %s") % kwargs.keys())

        type = type or "system"

        options = {
            'activation_keys': activation_keys,
            'environment': environment,
            'force': force,
            'name': name,
            'consumerid': consumerid,
            'type': type
        }
        self.validate_options(options)

        environment = options['environment']
        facts_dict = self.facts.get_facts()

        # Default to the hostname if no name is given
        consumer_name = options['name'] or socket.gethostname()

        self.plugin_manager.run("pre_register_consumer", name=consumer_name, facts=facts_dict)

        if consumerid:
            consumer = self.cp.getConsumer(consumerid)
            if consumer.get('type', {}).get('manifest', {}):
                raise exceptions.ServiceError(
                    "Registration attempted with a consumer ID that is not of type 'system'")
        else:
            consumer = self.cp.registerConsumer(
                name=consumer_name,
                facts=facts_dict,
                owner=org,
                environment=environment,
                keys=options.get('activation_keys'),
                installed_products=self.installed_mgr.format_for_server(),
                content_tags=self.installed_mgr.tags,
                type=type,
                role=role,
                addons=addons,
                service_level=service_level,
                usage=usage
            )
        self.installed_mgr.write_cache()
        self.plugin_manager.run("post_register_consumer", consumer=consumer, facts=facts_dict)
        managerlib.persist_consumer_cert(consumer)

        # Now that we are registered, load the new identity
        self.identity.reload()
        return consumer
    def _on_registration_finished_cb(self, new_account, error=None):
        try:
            if error != None:
                raise error

            managerlib.persist_consumer_cert(new_account)
            self.consumer.reload()
            self._finish_registration()

        except Exception, e:
            handle_gui_exception(e, REGISTER_ERROR, self.registerWin)
            self._finish_registration(failed=True)
    def _on_registration_finished_cb(self, new_account, error=None):
        try:
            if error != None:
                raise error

            managerlib.persist_consumer_cert(new_account)
            self.consumer.reload()
            self._finish_registration()

        except Exception, e:
            handle_gui_exception(e, REGISTER_ERROR, self.registerWin)
            self._finish_registration(failed=True)
示例#7
0
    def _register_consumer(self, name, facts, owner, env, activation_keys,
                           callback):
        """
        method run in the worker thread.
        """
        try:
            installed_mgr = require(INSTALLED_PRODUCTS_MANAGER)

            self.plugin_manager.run("pre_register_consumer",
                                    name=name,
                                    facts=facts.get_facts())
            retval = self.backend.cp_provider.get_basic_auth_cp(
            ).registerConsumer(
                name=name,
                facts=facts.get_facts(),
                owner=owner,
                environment=env,
                keys=activation_keys,
                installed_products=installed_mgr.format_for_server())
            self.plugin_manager.run("post_register_consumer",
                                    consumer=retval,
                                    facts=facts.get_facts())

            # Facts and installed products went out with the registration
            # request, manually write caches to disk:
            facts.write_cache()
            installed_mgr.write_cache()

            cp = self.backend.cp_provider.get_basic_auth_cp()

            # In practice, the only time this condition should be true is
            # when we are working with activation keys.  See BZ #888790.
            if not self.backend.cp_provider.get_basic_auth_cp().username and \
                not self.backend.cp_provider.get_basic_auth_cp().password:
                # Write the identity cert to disk
                managerlib.persist_consumer_cert(retval)
                self.backend.update()
                cp = self.backend.cp_provider.get_consumer_auth_cp()

            # FIXME: this looks like we are updating package profile as
            #        basic auth
            profile_mgr = require(PROFILE_MANAGER)
            profile_mgr.update_check(cp, retval['uuid'])

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

            self.queue.put((callback, retval, None))
        except Exception:
            self.queue.put((callback, None, sys.exc_info()))
示例#8
0
    def _on_registration_finished_cb(self, new_account, error=None):
        try:
            if error != None:
                raise error

            managerlib.persist_consumer_cert(new_account)
            self._parent.consumer.reload()
            if self._parent.skip_auto_bind:
                self._parent.pre_done(FINISH)
            else:
                self._parent.pre_done(SELECT_SLA_PAGE)

        except Exception, e:
            handle_gui_exception(e, REGISTER_ERROR, self._parent.window)
            self._parent.finish_registration(failed=True)
示例#9
0
    def _on_registration_finished_cb(self, new_account, error=None):
        try:
            if error != None:
                raise error

            managerlib.persist_consumer_cert(new_account)
            self._parent.consumer.reload()
            if self._parent.skip_auto_bind:
                self._parent.pre_done(FINISH)
            else:
                self._parent.pre_done(SELECT_SLA_PAGE)

        except Exception, e:
            handle_gui_exception(e, REGISTER_ERROR, self._parent.window)
            self._parent.finish_registration(failed=True)
    def _register_consumer(self, name, facts, owner, env, activation_keys, callback):
        """
        method run in the worker thread.
        """
        try:
            installed_mgr = require(INSTALLED_PRODUCTS_MANAGER)

            self.plugin_manager.run("pre_register_consumer", name=name, facts=facts.get_facts())
            retval = self.backend.cp_provider.get_basic_auth_cp().registerConsumer(
                name=name,
                facts=facts.get_facts(),
                owner=owner,
                environment=env,
                keys=activation_keys,
                installed_products=installed_mgr.format_for_server(),
            )
            self.plugin_manager.run("post_register_consumer", consumer=retval, facts=facts.get_facts())

            # Facts and installed products went out with the registration
            # request, manually write caches to disk:
            facts.write_cache()
            installed_mgr.write_cache()

            cp = self.backend.cp_provider.get_basic_auth_cp()

            # In practice, the only time this condition should be true is
            # when we are working with activation keys.  See BZ #888790.
            if (
                not self.backend.cp_provider.get_basic_auth_cp().username
                and not self.backend.cp_provider.get_basic_auth_cp().password
            ):
                # Write the identity cert to disk
                managerlib.persist_consumer_cert(retval)
                self.backend.update()
                cp = self.backend.cp_provider.get_consumer_auth_cp()

            # FIXME: this looks like we are updating package profile as
            #        basic auth
            profile_mgr = require(PROFILE_MANAGER)
            profile_mgr.update_check(cp, retval["uuid"])

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

            self.queue.put((callback, retval, None))
        except Exception:
            self.queue.put((callback, None, sys.exc_info()))
示例#11
0
    def _do_update(self):
        if not ConsumerIdentity.existsAndValid():
            # we could in theory try to update the id in the
            # case of it being bogus/corrupted, ala #844069,
            # but that seems unneeded
            return 0

        from subscription_manager import managerlib

        idcert = ConsumerIdentity.read()
        uuid = idcert.getConsumerId()
        consumer = self.uep.getConsumer(uuid)
        # only write the cert if the serial has changed
        if idcert.getSerialNumber() != consumer['idCert']['serial']['serial']:
            log.debug('identity certificate changed, writing new one')
            managerlib.persist_consumer_cert(consumer)
        return 1
示例#12
0
    def _do_update(self):
        if not ConsumerIdentity.existsAndValid():
            # we could in theory try to update the id in the
            # case of it being bogus/corrupted, ala #844069,
            # but that seems unneeded
            return 0

        from subscription_manager import managerlib

        idcert = ConsumerIdentity.read()
        uuid = idcert.getConsumerId()
        consumer = self.uep.getConsumer(uuid)
        # only write the cert if the serial has changed
        if idcert.getSerialNumber() != consumer['idCert']['serial']['serial']:
            log.debug('identity certificate changed, writing new one')
            managerlib.persist_consumer_cert(consumer)
        return 1
示例#13
0
    def _on_registration_finished_cb(self, new_account, error=None):
        try:
            if error != None:
                raise error

            managerlib.persist_consumer_cert(new_account)
            self._parent.consumer.reload()
            if self._parent.skip_auto_bind:
                message = _("You have opted to skip auto-subscribe.")
                self._parent.manual_message = message
                self._parent.pre_done(MANUALLY_SUBSCRIBE_PAGE)
            else:
                self._parent.pre_done(registergui.SELECT_SLA_PAGE)

        except Exception, e:
            handle_gui_exception(e, registergui.REGISTER_ERROR,
                    self._parent.window)
            self._parent.finish_registration(failed=True)
示例#14
0
    def _on_registration_finished_cb(self, new_account, error=None):
        try:
            if error != None:
                raise error

            managerlib.persist_consumer_cert(new_account)
            self._parent.consumer.reload()
            if self._parent.skip_auto_bind:
                message = _("You have opted to skip auto-subscribe.")
                self._parent.manual_message = message
                self._parent.pre_done(MANUALLY_SUBSCRIBE_PAGE)
            else:
                self._parent.pre_done(registergui.SELECT_SLA_PAGE)

        except Exception, e:
            handle_gui_exception(e, registergui.REGISTER_ERROR,
                                 self._parent.window)
            self._parent.finish_registration(failed=True)
示例#15
0
    def _on_registration_finished_cb(self, new_account, error=None):
        if error is not None:
            handle_gui_exception(error, REGISTER_ERROR, self._parent.parent)
            self._parent.finish_registration(failed=True)
            return

        try:
            managerlib.persist_consumer_cert(new_account)
            self._parent.backend.cs.force_cert_check()  # Ensure there isn't much wait time

            if self._parent.activation_keys:
                self._parent.pre_done(REFRESH_SUBSCRIPTIONS_PAGE)
            elif self._parent.skip_auto_bind:
                self._parent.pre_done(FINISH)
            else:
                self._parent.pre_done(SELECT_SLA_PAGE)
        except Exception, e:
            handle_gui_exception(e, REGISTER_ERROR, self._parent.parent)
            self._parent.finish_registration(failed=True)
    def _on_registration_finished_cb(self, new_account, error=None):
        if error is not None:
            handle_gui_exception(error, REGISTER_ERROR, self._parent.parent)
            self._parent.finish_registration(failed=True)
            return

        try:
            managerlib.persist_consumer_cert(new_account)
            self._parent.backend.cs.force_cert_check()  # Ensure there isn't much wait time

            if self._parent.activation_keys:
                self._parent.pre_done(REFRESH_SUBSCRIPTIONS_PAGE)
            elif self._parent.skip_auto_bind:
                self._parent.pre_done(FINISH)
            else:
                self._parent.pre_done(SELECT_SLA_PAGE)
        except Exception, e:
            handle_gui_exception(e, REGISTER_ERROR, self._parent.parent)
            self._parent.finish_registration(failed=True)
示例#17
0
    def _update_cert(self, identity):

        # to avoid circular imports
        # FIXME: move persist stuff here
        from subscription_manager import managerlib

        idcert = identity.consumer

        consumer = self._get_consumer(identity)

        # only write the cert if the serial has changed
        # FIXME: this would be a good place to have a Consumer/ConsumerCert
        # model.
        # FIXME: and this would be a ConsumerCert model '!='
        if idcert.getSerialNumber() != consumer['idCert']['serial']['serial']:
            log.debug('identity certificate changed, writing new one')

            # FIXME: should be in this module? managerlib is an odd place
            managerlib.persist_consumer_cert(consumer)

        # updated the cert, or at least checked
        self.report._status = 1
        return self.report
    def _update_cert(self, identity):

        # to avoid circular imports
        # FIXME: move persist stuff here
        from subscription_manager import managerlib

        idcert = identity.getConsumerCert()

        consumer = self._get_consumer(identity)

        # only write the cert if the serial has changed
        # FIXME: this would be a good place to have a Consumer/ConsumerCert
        # model.
        # FIXME: and this would be a ConsumerCert model '!='
        if idcert.getSerialNumber() != consumer['idCert']['serial']['serial']:
            log.debug('identity certificate changed, writing new one')

            # FIXME: should be in this module? managerlib is an odd place
            managerlib.persist_consumer_cert(consumer)

        # updated the cert, or at least checked
        self.report._status = 1
        return self.report
示例#19
0
    def register(self, org, activation_keys=None, environment=None, force=None, name=None, consumerid=None,
            type=None, role=None, addons=None, service_level=None, usage=None, no_insights=None, **kwargs):
        # We accept a kwargs argument so that the DBus object can pass the options dictionary it
        # receives transparently to the service via dictionary unpacking.  This strategy allows the
        # DBus object to be more independent of the service implementation.

        # If there are any values in kwargs that don't map to keyword arguments defined in the message
        # signature we want to consider that an error.
        if kwargs:
            raise exceptions.ValidationError(_("Unknown arguments: %s") % kwargs.keys())

        if no_insights is True:
            try:
                # insights-client implements a systemd path unit to trigger insights registration whenever the consumer
                # certificate changes. By masking this unit, we disable this automatic insights registration mechanism.
                # See: https://www.freedesktop.org/software/systemd/man/systemd.path.html
                log.debug("Disabling automatic insights registration by masking insights-register.path")
                with open('/dev/null', 'w') as devnull:
                    subprocess.call(['/usr/bin/systemctl', 'mask', '--now', 'insights-register.path'], stdout=devnull,
                                    stderr=devnull)
            except Exception as e:
                # ignore failures here in case we're running in a container, or some other issue prevents disabling
                # insights auto-register
                log.warning("Failed to disable automatic insights registration: %s", e, exc_info=True)

        syspurpose = syspurposelib.read_syspurpose()

        save_syspurpose = False

        # First set new syspurpose values, if there is any
        if role is not None:
            syspurpose['role'] = role
            save_syspurpose = True
        if addons is not None:
            syspurpose['addons'] = addons
            save_syspurpose = True
        if service_level is not None:
            syspurpose['service_level_agreement'] = service_level
            save_syspurpose = True
        if usage is not None:
            syspurpose['usage'] = usage
            save_syspurpose = True

        # Then try to get all syspurpose values
        role = syspurpose.get('role', '')
        addons = syspurpose.get('addons', [])
        usage = syspurpose.get('usage', '')
        service_level = syspurpose.get('service_level_agreement', '')

        type = type or "system"

        options = {
            'activation_keys': activation_keys,
            'environment': environment,
            'force': force,
            'name': name,
            'consumerid': consumerid,
            'type': type
        }
        self.validate_options(options)

        environment = options['environment']
        facts_dict = self.facts.get_facts()

        # Default to the hostname if no name is given
        consumer_name = options['name'] or socket.gethostname()

        self.plugin_manager.run("pre_register_consumer", name=consumer_name, facts=facts_dict)

        if consumerid:
            consumer = self.cp.getConsumer(consumerid)
            if consumer.get('type', {}).get('manifest', {}):
                raise exceptions.ServiceError(
                    "Registration attempted with a consumer ID that is not of type 'system'")
        else:
            consumer = self.cp.registerConsumer(
                name=consumer_name,
                facts=facts_dict,
                owner=org,
                environment=environment,
                keys=options.get('activation_keys'),
                installed_products=self.installed_mgr.format_for_server(),
                content_tags=self.installed_mgr.tags,
                type=type,
                role=role,
                addons=addons,
                service_level=service_level,
                usage=usage
            )
        self.installed_mgr.write_cache()
        self.plugin_manager.run("post_register_consumer", consumer=consumer, facts=facts_dict)
        managerlib.persist_consumer_cert(consumer)

        # Now that we are registered, load the new identity
        self.identity.reload()

        # If new syspurpose values were given as arguments, then save these values to syspurpose.json now
        if save_syspurpose is True:
            syspurposelib.write_syspurpose(syspurpose)

        return consumer
示例#20
0
    def register(self,
                 org,
                 activation_keys=None,
                 environment=None,
                 force=None,
                 name=None,
                 consumerid=None,
                 **kwargs):
        # We accept a kwargs argument so that the DBus object can pass the options dictionary it
        # receives transparently to the service via dictionary unpacking.  This strategy allows the
        # DBus object to be more independent of the service implementation.

        # If there are any values in kwargs that don't map to keyword arguments defined in the message
        # signature we want to consider that an error.
        if kwargs:
            raise exceptions.ValidationError(
                _("Unknown arguments: %s") % kwargs.keys())

        options = {
            'activation_keys': activation_keys,
            'environment': environment,
            'force': force,
            'name': name,
            'consumerid': consumerid
        }
        self.validate_options(options)

        environment = options['environment']
        facts_dict = self.facts.get_facts()

        # Default to the hostname if no name is given
        consumer_name = options['name'] or socket.gethostname()

        self.plugin_manager.run("pre_register_consumer",
                                name=consumer_name,
                                facts=facts_dict)

        if consumerid:
            consumer = self.cp.getConsumer(consumerid)
            if consumer.get('type', {}).get('manifest', {}):
                raise exceptions.ServiceError(
                    "Registration attempted with a consumer ID that is not of type 'system'"
                )
        else:
            consumer = self.cp.registerConsumer(
                name=consumer_name,
                facts=facts_dict,
                owner=org,
                environment=environment,
                keys=options.get('activation_keys'),
                installed_products=self.installed_mgr.format_for_server(),
                content_tags=self.installed_mgr.tags)
        self.installed_mgr.write_cache()
        self.plugin_manager.run("post_register_consumer",
                                consumer=consumer,
                                facts=facts_dict)
        managerlib.persist_consumer_cert(consumer)

        # Now that we are registered, load the new identity
        self.identity.reload()
        return consumer
示例#21
0
    def register(self, org, activation_keys=None, environment=None, force=None, name=None, consumerid=None,
            type=None, role=None, addons=None, service_level=None, usage=None, **kwargs):
        # We accept a kwargs argument so that the DBus object can pass the options dictionary it
        # receives transparently to the service via dictionary unpacking.  This strategy allows the
        # DBus object to be more independent of the service implementation.

        # If there are any values in kwargs that don't map to keyword arguments defined in the message
        # signature we want to consider that an error.
        if kwargs:
            raise exceptions.ValidationError(_("Unknown arguments: %s") % kwargs.keys())

        syspurpose = syspurposelib.read_syspurpose()
        role = role or syspurpose.get('role', '')
        addons = addons or syspurpose.get('addons', [])
        usage = usage or syspurpose.get('usage', '')
        service_level = service_level or syspurpose.get('service_level_agreement', '')

        type = type or "system"

        options = {
            'activation_keys': activation_keys,
            'environment': environment,
            'force': force,
            'name': name,
            'consumerid': consumerid,
            'type': type
        }
        self.validate_options(options)

        environment = options['environment']
        facts_dict = self.facts.get_facts()

        # Default to the hostname if no name is given
        consumer_name = options['name'] or socket.gethostname()

        self.plugin_manager.run("pre_register_consumer", name=consumer_name, facts=facts_dict)

        if consumerid:
            consumer = self.cp.getConsumer(consumerid)
            if consumer.get('type', {}).get('manifest', {}):
                raise exceptions.ServiceError(
                    "Registration attempted with a consumer ID that is not of type 'system'")
        else:
            consumer = self.cp.registerConsumer(
                name=consumer_name,
                facts=facts_dict,
                owner=org,
                environment=environment,
                keys=options.get('activation_keys'),
                installed_products=self.installed_mgr.format_for_server(),
                content_tags=self.installed_mgr.tags,
                type=type,
                role=role,
                addons=addons,
                service_level=service_level,
                usage=usage
            )
        self.installed_mgr.write_cache()
        self.plugin_manager.run("post_register_consumer", consumer=consumer, facts=facts_dict)
        managerlib.persist_consumer_cert(consumer)

        # Now that we are registered, load the new identity
        self.identity.reload()
        # We want a new SyncedStore every time as we otherwise can hold onto bad state in
        # long-lived services in dbus
        uep = inj.require(inj.CP_PROVIDER).get_consumer_auth_cp()
        store = syspurposelib.SyncedStore(uep, consumer_uuid=self.identity.uuid)
        if store:
            store.sync()
        return consumer
示例#22
0
    def register(self,
                 org,
                 activation_keys=None,
                 environments=None,
                 force=None,
                 name=None,
                 consumerid=None,
                 type=None,
                 role=None,
                 addons=None,
                 service_level=None,
                 usage=None,
                 jwt_token=None,
                 **kwargs):
        # We accept a kwargs argument so that the DBus object can pass the options dictionary it
        # receives transparently to the service via dictionary unpacking.  This strategy allows the
        # DBus object to be more independent of the service implementation.

        # If there are any values in kwargs that don't map to keyword arguments defined in the message
        # signature we want to consider that an error.
        if kwargs:
            raise exceptions.ValidationError(
                _("Unknown arguments: %s") % kwargs.keys())

        syspurpose = syspurposelib.read_syspurpose()

        save_syspurpose = False

        # First set new syspurpose values, if there is any
        if role is not None:
            syspurpose["role"] = role
            save_syspurpose = True
        if addons is not None:
            syspurpose["addons"] = addons
            save_syspurpose = True
        if service_level is not None:
            syspurpose["service_level_agreement"] = service_level
            save_syspurpose = True
        if usage is not None:
            syspurpose["usage"] = usage
            save_syspurpose = True

        # Then try to get all syspurpose values
        role = syspurpose.get("role", "")
        addons = syspurpose.get("addons", [])
        usage = syspurpose.get("usage", "")
        service_level = syspurpose.get("service_level_agreement", "")

        type = type or "system"

        options = {
            "activation_keys": activation_keys,
            "environments": environments,
            "force": force,
            "name": name,
            "consumerid": consumerid,
            "type": type,
            "jwt_token": jwt_token,
        }
        self.validate_options(options)

        environments = options["environments"]
        facts_dict = self.facts.get_facts()

        # Default to the hostname if no name is given
        consumer_name = options["name"] or socket.gethostname()

        self.plugin_manager.run("pre_register_consumer",
                                name=consumer_name,
                                facts=facts_dict)

        if consumerid:
            consumer = self.cp.getConsumer(consumerid)
            if consumer.get("type", {}).get("manifest", {}):
                raise exceptions.ServiceError(
                    "Registration attempted with a consumer ID that is not of type 'system'"
                )
        else:
            consumer = self.cp.registerConsumer(
                name=consumer_name,
                facts=facts_dict,
                owner=org,
                environments=environments,
                keys=options.get("activation_keys"),
                installed_products=self.installed_mgr.format_for_server(),
                content_tags=self.installed_mgr.tags,
                type=type,
                role=role,
                addons=addons,
                service_level=service_level,
                usage=usage,
                jwt_token=jwt_token,
            )
        self.installed_mgr.write_cache()
        self.plugin_manager.run("post_register_consumer",
                                consumer=consumer,
                                facts=facts_dict)
        managerlib.persist_consumer_cert(consumer)

        # Now that we are registered, load the new identity
        self.identity.reload()

        # If new syspurpose values were given as arguments, then save these values to syspurpose.json now
        if save_syspurpose is True:
            syspurposelib.write_syspurpose(syspurpose)

        syspurpose_dict = {
            "service_level_agreement":
            consumer["serviceLevel"]
            if "serviceLevel" in list(consumer.keys()) else "",
            "role":
            consumer["role"] if "role" in list(consumer.keys()) else "",
            "usage":
            consumer["usage"] if "usage" in list(consumer.keys()) else "",
            "addons":
            consumer["addOns"] if "addOns" in list(consumer.keys()) else [],
        }

        # Try to do three-way merge and then save result to syspurpose.json file
        local_result = syspurposelib.merge_syspurpose_values(
            remote=syspurpose_dict, base={})
        syspurposelib.write_syspurpose(local_result)

        # Save syspurpose attributes from consumer to cache file
        syspurposelib.write_syspurpose_cache(syspurpose_dict)

        content_access_mode_cache = inj.require(inj.CONTENT_ACCESS_MODE_CACHE)

        # Is information about content access mode included in consumer
        if "owner" not in consumer:
            log.warning(
                "Consumer does not contain any information about owner.")
        elif "contentAccessMode" in consumer["owner"]:
            log.debug(
                "Saving content access mode from consumer object to cache file."
            )
            # When we know content access mode from consumer, then write it to cache file
            content_access_mode = consumer["owner"]["contentAccessMode"]
            content_access_mode_cache.set_data(content_access_mode,
                                               self.identity)
            content_access_mode_cache.write_cache()
        else:
            # If not, then we have to do another REST API call to get this information
            # It will not be included in cache file. When cache file is empty, then
            # it will trigger accessing REST API and saving result in cache file.
            log.debug(
                "Information about content access mode is not included in consumer"
            )
            content_access_mode = content_access_mode_cache.read_data()
            # Add information about content access mode to consumer
            consumer["owner"]["contentAccessMode"] = content_access_mode

        return consumer
示例#23
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)
示例#24
0
    def register(self,
                 org,
                 activation_keys=None,
                 environment=None,
                 force=None,
                 name=None,
                 consumerid=None,
                 type=None,
                 role=None,
                 addons=None,
                 service_level=None,
                 usage=None,
                 autoheal=None,
                 **kwargs):
        # We accept a kwargs argument so that the DBus object can pass the options dictionary it
        # receives transparently to the service via dictionary unpacking.  This strategy allows the
        # DBus object to be more independent of the service implementation.

        # If there are any values in kwargs that don't map to keyword arguments defined in the message
        # signature we want to consider that an error.
        if kwargs:
            raise exceptions.ValidationError(
                _("Unknown arguments: %s") % kwargs.keys())

        syspurpose = syspurposelib.read_syspurpose()

        save_syspurpose = False

        # First set new syspurpose values, if there is any
        if role is not None:
            syspurpose['role'] = role
            save_syspurpose = True
        if addons is not None:
            syspurpose['addons'] = addons
            save_syspurpose = True
        if service_level is not None:
            syspurpose['service_level_agreement'] = service_level
            save_syspurpose = True
        if usage is not None:
            syspurpose['usage'] = usage
            save_syspurpose = True

        # Then try to get all syspurpose values
        role = syspurpose.get('role', '')
        addons = syspurpose.get('addons', [])
        usage = syspurpose.get('usage', '')
        service_level = syspurpose.get('service_level_agreement', '')

        type = type or "system"

        options = {
            'activation_keys': activation_keys,
            'environment': environment,
            'force': force,
            'name': name,
            'consumerid': consumerid,
            'type': type
        }
        self.validate_options(options)

        environment = options['environment']
        facts_dict = self.facts.get_facts()

        # Default to the hostname if no name is given
        consumer_name = options['name'] or socket.gethostname()

        self.plugin_manager.run("pre_register_consumer",
                                name=consumer_name,
                                facts=facts_dict)

        if consumerid:
            consumer = self.cp.getConsumer(consumerid)
            if consumer.get('type', {}).get('manifest', {}):
                raise exceptions.ServiceError(
                    "Registration attempted with a consumer ID that is not of type 'system'"
                )
        else:
            consumer = self.cp.registerConsumer(
                name=consumer_name,
                facts=facts_dict,
                owner=org,
                environment=environment,
                keys=options.get('activation_keys'),
                installed_products=self.installed_mgr.format_for_server(),
                content_tags=self.installed_mgr.tags,
                type=type,
                role=role,
                addons=addons,
                service_level=service_level,
                usage=usage,
                autoheal=autoheal)
        self.installed_mgr.write_cache()
        self.plugin_manager.run("post_register_consumer",
                                consumer=consumer,
                                facts=facts_dict)
        managerlib.persist_consumer_cert(consumer)

        # Now that we are registered, load the new identity
        self.identity.reload()

        # If new syspurpose values were given as arguments, then save these values to syspurpose.json now
        if save_syspurpose is True:
            syspurposelib.write_syspurpose(syspurpose)

        return consumer