Example #1
0
 def test_columnize_multibyte(self, term_width_mock):
     multibyte_str = u"このシステム用に"
     term_width_mock.return_value = 40
     result = columnize([multibyte_str], _echo, multibyte_str)
     expected = u"このシステム用に このシステム用に"
     self.assertEquals(result, expected)
     term_width_mock.return_value = 14
     result = columnize([multibyte_str], _echo, multibyte_str)
     expected = u"このシ\nステム\n用に   このシ\n       ステム\n       用に"
     self.assertEquals(result, expected)
 def test_columnize_multibyte(self, term_width_mock):
     multibyte_str = u"このシステム用に"
     term_width_mock.return_value = 40
     result = columnize([multibyte_str], _echo, multibyte_str)
     expected = u"このシステム用に このシステム用に"
     self.assertEquals(result, expected)
     term_width_mock.return_value = 14
     result = columnize([multibyte_str], _echo, multibyte_str)
     expected = u"このシ\nステム\n用に   このシ\n       ステム\n       用に"
     self.assertEquals(result, expected)
 def test_columnize_with_small_term(self, term_width_mock):
     result = columnize(["Hello Hello Hello Hello:", "Foo Foo Foo Foo:"],
             _echo, "This is a testing string", "This_is_another_testing_string")
     expected = 'Hello\nHello\nHello\nHello\n:     This\n      is a\n      ' \
             'testin\n      g\n      string\nFoo\nFoo\nFoo\nFoo:  ' \
             'This_i\n      s_anot\n      her_te\n      sting_\n      string'
     self.assertNotEquals(result, expected)
     term_width_mock.return_value = 12
     result = columnize(["Hello Hello Hello Hello:", "Foo Foo Foo Foo:"],
             _echo, "This is a testing string", "This_is_another_testing_string")
     self.assertEquals(result, expected)
Example #4
0
 def test_columnize_with_small_term(self, term_width_mock):
     result = columnize(["Hello Hello Hello Hello:", "Foo Foo Foo Foo:"],
             _echo, "This is a testing string", "This_is_another_testing_string")
     expected = 'Hello\nHello\nHello\nHello\n:     This\n      is a\n      ' \
             'testin\n      g\n      string\nFoo\nFoo\nFoo\nFoo:  ' \
             'This_i\n      s_anot\n      her_te\n      sting_\n      string'
     self.assertNotEquals(result, expected)
     term_width_mock.return_value = 12
     result = columnize(["Hello Hello Hello Hello:", "Foo Foo Foo Foo:"],
             _echo, "This is a testing string", "This_is_another_testing_string")
     self.assertEquals(result, expected)
Example #5
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."))
Example #6
0
def show_autosubscribe_output(uep, identity):
    """
    Try to show auto-attach output
    :param uep: object with connection to candlepin
    :param identity: object with identity
    :return: return 1, when all installed products are subscribed, otherwise return 0
    """

    if is_simple_content_access(uep=uep, identity=identity):
        return 0

    installed_products = products.InstalledProducts(uep).list()

    if not installed_products:
        # Returning an error code here breaks registering when no products are installed, and the
        # AttachCommand already performs this check before calling.
        print(_("No products installed."))
        return 0

    log.debug("Attempted to auto-attach/heal the system.")
    print(_("Installed Product Current Status:"))
    subscribed = 1
    all_subscribed = True
    for product in installed_products:
        if product[4] == SUBSCRIBED:
            subscribed = 0
        status = STATUS_MAP[product[4]]
        if product[4] == NOT_SUBSCRIBED:
            all_subscribed = False
        print(columnize(PRODUCT_STATUS, echo_columnize_callback, product[0], status) + "\n")
    if not all_subscribed:
        print(_("Unable to find available subscriptions for all your installed products."))
    return subscribed
Example #7
0
    def _list(self, all_overrides, specific_repos):
        overrides = {}
        for override in all_overrides:
            repo = override.repo_id
            name = override.name
            value = override.value
            # overrides is a hash of hashes.  Like this: {'repo_x': {'enabled': '1', 'gpgcheck': '1'}}
            overrides.setdefault(repo, {})[name] = value

        to_show = set(overrides.keys())
        if specific_repos:
            specific_repos = set(specific_repos)
            for r in specific_repos.difference(to_show):
                print(_("Nothing is known about '{r}'").format(r=r))
            # Take the intersection of the sets
            to_show &= specific_repos

        for repo in sorted(to_show):
            print(_("Repository: {repo}").format(repo=repo))
            repo_data = sorted(list(overrides[repo].items()),
                               key=lambda x: x[0])
            # Split the list of 2-tuples into a list of names and a list of keys
            names, values = list(zip(*repo_data))
            names = ["{x}:".format(x=x) for x in names]
            print(
                columnize(names, echo_columnize_callback, *values, indent=2) +
                "\n")
 def test_columnize_with_small_term(self, term_width_mock):
     term_width_mock.return_value = None
     result = columnize(
         ["Hello Hello Hello Hello:", "Foo Foo Foo Foo:"],
         echo_columnize_callback,
         "This is a testing string",
         "This_is_another_testing_string",
     )
     expected = (
         "Hello\nHello\nHello\nHello\n:     This\n      is a\n      "
         "testin\n      g\n      string\nFoo\nFoo\nFoo\nFoo:  "
         "This_i\n      s_anot\n      her_te\n      sting_\n      string"
     )
     self.assertNotEqual(result, expected)
     term_width_mock.return_value = 12
     result = columnize(
         ["Hello Hello Hello Hello:", "Foo Foo Foo Foo:"],
         echo_columnize_callback,
         "This is a testing string",
         "This_is_another_testing_string",
     )
     self.assertEqual(result, expected)
Example #9
0
    def _list_environments(self):
        """
        List the environments based on the option selected in the command line
        enabled/disabled/all
        """
        if not self.cp.has_capability(MULTI_ENV) and (self.options.enabled or
                                                      self.options.disabled):
            system_exit(
                os.EX_UNAVAILABLE,
                _("Error: Server does not support multi-environment operations."
                  ))
        environments = []
        if self.options.enabled:
            environments = self.cp.getConsumer(
                self.identity.uuid)["environments"] or []
        else:
            org_environments = self._get_environments(self.org)
            if self.options.disabled:
                consumer_id_list = []
                for env in self.cp.getConsumer(
                        self.identity.uuid)["environments"]:
                    consumer_id_list.append(env["id"])
                for env in org_environments:
                    if env["id"] not in consumer_id_list:
                        environments.append(env)
            else:
                environments = org_environments

        if len(environments):
            print("+-------------------------------------------+")
            print("          {env}".format(env=_("Environments")))
            print("+-------------------------------------------+")
            for env in environments:
                print(
                    columnize(
                        ENVIRONMENT_LIST,
                        echo_columnize_callback,
                        env["name"],
                        env["description"] or "",
                    ) + "\n")
        else:
            print(
                _("This list operation does not have any environments to report."
                  ))
Example #10
0
    def _do_command(self):

        try:
            # get a UEP
            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()
            owners = self.cp.getOwnerList(self.username)
            log.debug("Successfully retrieved org list from server.")
            if len(owners):
                print("+-------------------------------------------+")
                print("          {name} {label}".format(
                    name=self.username, label=_("Organizations")))
                print("+-------------------------------------------+")
                print("")
                for owner in owners:
                    print(
                        columnize(ORG_LIST, echo_columnize_callback,
                                  owner["displayName"], owner["key"]) + "\n")
            else:
                print(
                    _("{username} cannot register with any organizations.").
                    format(username=self.username))

        except connection.RestlibException as re:
            log.exception(re)
            log.error(
                "Error: Unable to retrieve org list from server: {re}".format(
                    re=re))

            mapped_message: str = ExceptionMapper().get_message(re)
            system_exit(os.EX_SOFTWARE, mapped_message)
        except Exception as e:
            handle_exception(
                _("Error: Unable to retrieve org list from server"), e)
    def _do_command(self):
        self._validate_options()
        try:
            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()
            supported_resources = get_supported_resources()
            if 'environments' in supported_resources:
                environments = self._get_environments(self.org)

                if len(environments):
                    print("+-------------------------------------------+")
                    print("          {env}".format(env=_('Environments')))
                    print("+-------------------------------------------+")
                    for env in environments:
                        print(
                            columnize(ENVIRONMENT_LIST,
                                      echo_columnize_callback, env['name'],
                                      env['description'] or "") + "\n")
                else:
                    print(_("This org does not have any environments."))
            else:
                system_exit(os.EX_UNAVAILABLE,
                            _("Error: Server does not support environments."))

            log.debug("Successfully retrieved environment list from server.")
        except connection.RestlibException as re:
            log.exception(re)
            log.error(
                "Error: Unable to retrieve environment list from server: {re}".
                format(re=re))
            system_exit(os.EX_SOFTWARE, str(re))
        except Exception as e:
            handle_exception(
                _("Error: Unable to retrieve environment list from server"), e)
Example #12
0
 def _do_columnize(self, items_list):
     modules, descriptions = list(zip(*items_list))
     print(
         columnize(modules, echo_columnize_callback, *descriptions) + '\n')
Example #13
0
 def _do_columnize(self, items_list):
     modules, descriptions = zip(*items_list)
     print columnize(modules, echo_columnize_callback, *descriptions) + "\n"
Example #14
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,
            )
 def test_columnize_with_empty_list(self):
     result = columnize(["Hello:", "Foo:"], echo_columnize_callback, [],
                        "bar")
     self.assertEqual(result, "Hello: \nFoo:   bar")
Example #16
0
 def _do_columnize(self, items_list):
     modules, descriptions = list(zip(*items_list))
     print(columnize(modules, echo_columnize_callback, *descriptions) + '\n')
Example #17
0
 def test_columnize(self):
     result = columnize(["Hello:", "Foo:"], _echo, "world", "bar")
     self.assertEquals(result, "Hello: world\nFoo:   bar")
 def test_columnize_with_list(self):
     result = columnize(["Hello:", "Foo:"], _echo, ["world", "space"], "bar")
     self.assertEquals(result, "Hello: world\n       space\nFoo:   bar")
Example #19
0
    def _do_command(self):
        self._reconcile_list_options()
        rc = 0
        if not manage_repos_enabled():
            print(_("Repositories disabled by configuration."))
            return rc

        # Pull down any new entitlements and refresh the entitlements directory
        if self.identity.is_valid():
            cert_action_client = ActionClient(skips=[PackageProfileActionInvoker])
            cert_action_client.update()
            self._request_validity_check()

        if self.is_registered():
            supported_resources = get_supported_resources()
            self.use_overrides = "content_overrides" in supported_resources
        else:
            self.use_overrides = False

        # specifically, yum repos, for now.
        rl = RepoActionInvoker()
        repos = rl.get_repos()

        if self.options.repo_actions is not None:
            rc = self._set_repo_status(repos, rl, self.options.repo_actions)

        if self.identity.is_valid():
            profile_action_client = ProfileActionClient()
            profile_action_client.update()

        if self.list:
            if len(repos):
                # TODO: Perhaps this should be abstracted out as well...?
                def filter_repos(repo):
                    disabled_values = ["false", "0"]
                    repo_enabled = repo["enabled"].lower()
                    show_enabled = self.list_enabled and repo_enabled not in disabled_values
                    show_disabled = self.list_disabled and repo_enabled in disabled_values

                    return show_enabled or show_disabled

                repos = list(filter(filter_repos, repos))

                if len(repos):
                    print("+----------------------------------------------------------+")
                    print(_("    Available Repositories in {file}").format(file=rl.get_repo_file()))
                    print("+----------------------------------------------------------+")

                    for repo in repos:
                        print(
                            columnize(
                                REPOS_LIST,
                                echo_columnize_callback,
                                repo.id,
                                repo["name"],
                                repo["baseurl"],
                                repo["enabled"],
                            )
                            + "\n"
                        )
                else:
                    print(_("There were no available repositories matching the specified criteria."))
            else:
                print(_("This system has no repositories available through subscriptions."))

        return rc
 def test_columnize(self):
     result = columnize(["Hello:", "Foo:"], _echo, "world", "bar")
     self.assertEquals(result, "Hello: world\nFoo:   bar")
 def test_columnize(self):
     result = columnize(["Hello:", "Foo:"], echo_columnize_callback,
                        "world", "bar")
     self.assertEqual(result, "Hello: world\nFoo:   bar")
 def test_columnize_with_empty_list(self):
     result = columnize(["Hello:", "Foo:"], _echo, [], "bar")
     self.assertEquals(result, "Hello: \nFoo:   bar")
 def test_columnize_with_list(self):
     result = columnize(["Hello:", "Foo:"], echo_columnize_callback,
                        ["world", "space"], "bar")
     self.assertEqual(result, "Hello: world\n       space\nFoo:   bar")
Example #24
0
 def _do_columnize(self, items_list):
     modules, descriptions = zip(*items_list)
     print columnize(modules, _echo, *descriptions) + '\n'
Example #25
0
 def _do_columnize(self, items_list):
     modules, descriptions = zip(*items_list)
     print columnize(modules, _echo, *descriptions) + '\n'