Esempio n. 1
0
    def _do_command(self):
        """
        Own implementation of all actions
        :return: None
        """
        self._validate_options()

        content = {}
        if self.options.show is True:
            if self.is_registered():
                try:
                    self.cp = self.cp_provider.get_consumer_auth_cp()
                except connection.RestlibException as err:
                    log.exception(err)
                    log.debug(
                        "Error: Unable to retrieve system purpose from server")
                except Exception as err:
                    log.debug(
                        "Error: Unable to retrieve system purpose from server: {err}"
                        .format(err=err))
                else:
                    self.store = SyncedStore(uep=self.cp,
                                             consumer_uuid=self.identity.uuid)
                    sync_result = self.store.sync()
                    content = sync_result.result
            else:
                content = syspurposelib.read_syspurpose()
            print(
                json.dumps(content,
                           indent=2,
                           ensure_ascii=False,
                           sort_keys=True))
Esempio n. 2
0
 def show(self):
     if self.is_registered():
         syspurpose = self.sync().result
     else:
         syspurpose = syspurposelib.read_syspurpose()
     if syspurpose is not None and self.attr in syspurpose and syspurpose[self.attr]:
         val = syspurpose[self.attr]
         values = val if not isinstance(val, list) else ", ".join(val)
         print(_("Current {name}: {val}").format(name=self.name.capitalize(), val=values))
     else:
         print(_("{name} not set.").format(name=self.name.capitalize()))
Esempio n. 3
0
    def _do_command(self):
        """
        Own implementation of all actions
        :return: None
        """
        self._validate_options()

        # a subcommand was actually invoked, so dispatch it
        if self.options.subparser_name is not None:
            subcmd = self.cli_commands[self.options.subparser_name]
            # set a reference to ourselves in the subcommand being executed;
            # this way, everything we collected & created in main() is
            # "forwarded" to the subcommand class (see
            # AbstractSyspurposeCommand.__getattr__())
            subcmd.syspurpose_command = self
            subcmd._do_command()
            return

        content = {}
        if self.options.syspurpose_show is True:
            if self.is_registered():
                try:
                    self.cp = self.cp_provider.get_consumer_auth_cp()
                except connection.RestlibException as err:
                    log.exception(err)
                    log.debug(
                        "Error: Unable to retrieve system purpose from server")
                except Exception as err:
                    log.debug(
                        "Error: Unable to retrieve system purpose from server: {err}"
                        .format(err=err))
                else:
                    self.store = SyncedStore(uep=self.cp,
                                             consumer_uuid=self.identity.uuid)
                    sync_result = self.store.sync()
                    content = sync_result.result
            else:
                content = syspurposelib.read_syspurpose()
            print(
                json.dumps(content,
                           indent=2,
                           ensure_ascii=False,
                           sort_keys=True))
Esempio n. 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())

        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
Esempio n. 5
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
Esempio n. 6
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
Esempio n. 7
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