Ejemplo n.º 1
0
    def print_consumed(self,
                       service_level=None,
                       filter_string=None,
                       pid_only=False):
        # list all certificates that have not yet expired, even those
        # that are not yet active.
        service = entitlement.EntitlementService()
        certs = service.get_consumed_product_pools(service_level=service_level,
                                                   matches=filter_string)

        # Process and display our (filtered) certs:
        if len(certs):
            if pid_only:
                for cert in certs:
                    print(cert.pool_id)
            else:
                print("+-------------------------------------------+")
                print("   " + _("Consumed Subscriptions"))
                print("+-------------------------------------------+")

                for cert in certs:
                    kwargs = {
                        "filter_string": filter_string,
                        "match_columns": AVAILABLE_SUBS_MATCH_COLUMNS,
                        "is_atty": sys.stdout.isatty(),
                    }
                    if hasattr(cert, "roles") and hasattr(
                            cert, "usage") and hasattr(cert, "addons"):
                        print(
                            columnize(CONSUMED_LIST,
                                      highlight_by_filter_string_columnize_cb,
                                      *cert, **kwargs) + "\n")
                    else:
                        print(
                            columnize(OLD_CONSUMED_LIST,
                                      highlight_by_filter_string_columnize_cb,
                                      *cert, **kwargs) + "\n")
        elif not pid_only:
            if filter_string and service_level:
                print(
                    _('No consumed subscription pools were found matching the expression "{filter}" and the service level "{level}".'
                      ).format(filter=filter_string, level=service_level))
            elif filter_string:
                print(
                    _('No consumed subscription pools were found matching the expression "{filter}".'
                      ).format(filter=filter_string))
            elif service_level:
                print(
                    _('No consumed subscription pools were found matching the service level "{level}".'
                      ).format(level=service_level))
            else:
                print(_("No consumed subscription pools were found."))
Ejemplo n.º 2
0
    def _run_unbind(self, serial, selection, callback, except_callback):
        """
        Selection is only passed to maintain the gui error message.  This
        can be removed, because it doesn't really give us any more information
        """
        try:
            ent_service = entitlement.EntitlementService(self.cp_provider.get_consumer_auth_cp())
            ent_service.remove_entitlements_by_serials([serial])
            try:
                self.certlib.update()
            except Disconnected:
                pass

            if callback:
                ga_GObject.idle_add(callback)
        except Exception:
            ga_GObject.idle_add(except_callback, sys.exc_info(), selection)
Ejemplo n.º 3
0
    def _do_command(self):
        """
        Executes the command.
        """
        self._validate_options()

        if self.options.installed and not self.options.pid_only:
            installed_products = products.InstalledProducts(self.cp).list(
                self.options.filter_string)

            if len(installed_products):
                print("+-------------------------------------------+")
                print(_("    Installed Product Status"))
                print("+-------------------------------------------+")

                for product in installed_products:
                    if is_simple_content_access(self.cp, self.identity):
                        print(
                            columnize(
                                INSTALLED_PRODUCT_STATUS_SCA,
                                none_wrap_columnize_callback,
                                product[0],  # Name
                                product[1],  # ID
                                product[2],  # Version
                                product[3],  # Arch
                            ) + "\n")
                    else:
                        status = STATUS_MAP[product[4]]
                        print(
                            columnize(
                                INSTALLED_PRODUCT_STATUS,
                                none_wrap_columnize_callback,
                                product[0],  # Name
                                product[1],  # ID
                                product[2],  # Version
                                product[3],  # Arch
                                status,  # Status
                                product[5],  # Status details
                                product[6],  # Start
                                product[7],  # End
                            ) + "\n")
            else:
                if self.options.filter_string:
                    print(
                        _('No installed products were found matching the expression "{filter}".'
                          ).format(filter=self.options.filter_string))
                else:
                    print(_("No installed products to list"))

        if self.options.available:
            self.assert_should_be_registered()
            on_date = None
            after_date = None
            if self.options.on_date:
                on_date = self._parse_date(self.options.on_date)
            elif self.options.after_date:
                after_date = self._parse_date(self.options.after_date)

            epools = entitlement.EntitlementService().get_available_pools(
                show_all=self.options.all,
                on_date=on_date,
                no_overlap=self.options.no_overlap,
                match_installed=self.options.match_installed,
                matches=self.options.filter_string,
                service_level=self.options.service_level,
                after_date=after_date,
            )

            if len(epools):
                if self.options.pid_only:
                    for data in epools:
                        print(data["id"])
                else:
                    print("+-------------------------------------------+")
                    print("    " + _("Available Subscriptions"))
                    print("+-------------------------------------------+")

                    for data in epools:
                        if PoolWrapper(data).is_virt_only():
                            entitlement_type = _("Virtual")
                        else:
                            entitlement_type = _("Physical")

                        if "management_enabled" in data and data[
                                "management_enabled"]:
                            data["management_enabled"] = _("Yes")
                        else:
                            data["management_enabled"] = _("No")

                        kwargs = {
                            "filter_string": self.options.filter_string,
                            "match_columns": AVAILABLE_SUBS_MATCH_COLUMNS,
                            "is_atty": sys.stdout.isatty(),
                        }
                        print(
                            columnize(
                                AVAILABLE_SUBS_LIST,
                                highlight_by_filter_string_columnize_cb,
                                data["productName"], data["providedProducts"],
                                data["productId"], data["contractNumber"]
                                or "", data["id"], data["management_enabled"],
                                data["quantity"], data["suggested"],
                                data["service_type"] or "",
                                self._split_mulit_value_field(
                                    data["roles"]), data["service_level"]
                                or "", data["usage"] or "",
                                self._split_mulit_value_field(data["addons"]),
                                data["pool_type"], data["startDate"],
                                data["endDate"], entitlement_type, **kwargs) +
                            "\n")
            elif not self.options.pid_only:
                if self.options.filter_string and self.options.service_level:
                    print(
                        _('No available subscription pools were found matching the expression "{filter}" and the service level "{level}".'
                          ).format(filter=self.options.filter_string,
                                   level=self.options.service_level))
                elif self.options.filter_string:
                    print(
                        _('No available subscription pools were found matching the expression "{filter}".'
                          ).format(filter=self.options.filter_string))
                elif self.options.service_level:
                    print(
                        _('No available subscription pools were found matching the service level "{level}".'
                          ).format(level=self.options.service_level))
                else:
                    print(_("No available subscription pools to list"))

        if self.options.consumed:
            self.print_consumed(
                service_level=self.options.service_level,
                filter_string=self.options.filter_string,
                pid_only=self.options.pid_only,
            )
Ejemplo n.º 4
0
    def _do_command(self):
        """
        Executes the command.
        """
        self._validate_options()
        return_code = 0
        if self.is_registered():
            ent_service = entitlement.EntitlementService(self.cp)
            try:
                if self.options.all:
                    total = ent_service.remove_all_entitlements()
                    # total will be None on older Candlepins that don't
                    # support returning the number of subscriptions unsubscribed from
                    if total is None:
                        print(_("All subscriptions have been removed at the server."))
                    else:
                        count = total["deletedRecords"]
                        print(
                            ungettext(
                                "%s subscription removed at the server.",
                                "%s subscriptions removed at the server.",
                                count,
                            )
                            % count
                        )
                else:
                    # Try to remove subscriptions defined by pool IDs first (remove --pool=...)
                    if self.options.pool_ids:
                        (
                            removed_pools,
                            unremoved_pools,
                            removed_serials,
                        ) = ent_service.remove_entilements_by_pool_ids(self.options.pool_ids)
                        if not removed_pools:
                            return_code = 1
                        self._print_unbind_ids_result(removed_pools, unremoved_pools, "pools")
                    else:
                        removed_serials = []
                    # Then try to remove subscriptions defined by serials (remove --serial=...)
                    unremoved_serials = []
                    if self.options.serials:
                        serials = unique_list_items(self.options.serials)
                        # Don't remove serials already removed by a pool
                        serials_to_remove = [serial for serial in serials if serial not in removed_serials]
                        _removed_serials, unremoved_serials = ent_service.remove_entitlements_by_serials(
                            serials_to_remove
                        )
                        removed_serials.extend(_removed_serials)
                        if not _removed_serials:
                            return_code = 1
                    # Print final result of removing pools
                    self._print_unbind_ids_result(removed_serials, unremoved_serials, "serial numbers")
            except connection.GoneException as ge:
                raise ge
            except connection.RestlibException as err:
                log.error(err)

                mapped_message: str = ExceptionMapper().get_message(err)
                system_exit(os.EX_SOFTWARE, mapped_message)
            except Exception as e:
                handle_exception(
                    _("Unable to perform remove due to the following exception: {e}").format(e=e), e
                )
        else:
            # We never got registered, just remove the cert
            try:
                if self.options.all:
                    total = 0
                    for ent in self.entitlement_dir.list():
                        ent.delete()
                        total = total + 1
                    print(_("{total} subscriptions removed from this system.").format(total=total))
                else:
                    if self.options.serials or self.options.pool_ids:
                        serials = self.options.serials or []
                        pool_ids = self.options.pool_ids or []
                        count = 0
                        for ent in self.entitlement_dir.list():
                            ent_pool_id = str(getattr(ent.pool, "id", None) or "")
                            if str(ent.serial) in serials or ent_pool_id in pool_ids:
                                ent.delete()
                                print(
                                    _(
                                        "Subscription with serial number {serial} removed from this system"
                                    ).format(serial=str(ent.serial))
                                )
                                count = count + 1
                        if count == 0:
                            return_code = 1
            except Exception as e:
                handle_exception(
                    _("Unable to perform remove due to the following exception: {e}").format(e=e), e
                )

        # it is okay to call this no matter what happens above,
        # it's just a notification to perform a check
        self._request_validity_check()
        return return_code
Ejemplo n.º 5
0
    def _do_command(self):
        # list status and all reasons it is not valid
        on_date = None
        if self.options.on_date:
            try:
                on_date = entitlement.EntitlementService.parse_date(
                    self.options.on_date)
            except ValueError as err:
                system_exit(os.EX_DATAERR, err)

        print("+-------------------------------------------+")
        print("   " + _("System Status Details"))
        print("+-------------------------------------------+")

        service_status = entitlement.EntitlementService(None).get_status(
            on_date)
        reasons = service_status['reasons']

        if service_status['valid']:
            result = 0
        else:
            result = 1

        ca_message = ""
        has_cert = (_(
            "Content Access Mode is set to Simple Content Access. This host has access to content, regardless of subscription status.\n"
        ))

        certs = self.entitlement_dir.list_with_content_access()
        ca_certs = [
            cert for cert in certs
            if cert.entitlement_type == CONTENT_ACCESS_CERT_TYPE
        ]
        if ca_certs:
            ca_message = has_cert
        else:
            if is_simple_content_access(uep=self.cp, identity=self.identity):
                ca_message = has_cert

        print(
            _("Overall Status: {status}\n{message}").format(
                status=service_status['status'], message=ca_message))

        columns = get_terminal_width()
        for name in reasons:
            print(format_name(name + ':', 0, columns))
            for message in reasons[name]:
                print("- {name}".format(name=format_name(message, 2, columns)))
            print('')

        try:
            store = syspurposelib.get_sys_purpose_store()
            if store:
                store.sync()
        except (OSError, ConnectionException) as ne:
            log.exception(ne)

        syspurpose_cache = inj.require(
            inj.SYSTEMPURPOSE_COMPLIANCE_STATUS_CACHE)
        syspurpose_cache.load_status(self.cp, self.identity.uuid, on_date)
        print(
            _("System Purpose Status: {status}").format(
                status=syspurpose_cache.get_overall_status()))

        syspurpose_status_code = syspurpose_cache.get_overall_status_code()
        if syspurpose_status_code != 'matched':
            reasons = syspurpose_cache.get_status_reasons()
            if reasons is not None:
                for reason in reasons:
                    print("- {reason}".format(reason=reason))
        print('')

        return result