Esempio n. 1
0
    def delete(self, org_id, system_group_id, delete_systems):
        if delete_systems:
            path = "/api/organizations/%s/system_groups/%s/destroy_systems" % (u_str(org_id), u_str(system_group_id))
        else:
            path = "/api/organizations/%s/system_groups/%s" % (u_str(org_id), u_str(system_group_id))

        return self.server.DELETE(path)[1]
Esempio n. 2
0
    def _store_item_with_product(self, option, opt_str, value, parser):
        if (parser.values.from_product == None) and \
           (parser.values.from_product_label == None) and \
           (parser.values.from_product_id == None):
            raise OptionValueError(
                _("%s must be preceded by %s, %s or %s") %
                (option, "--from_product", "--from_product_label",
                 "--from_product_id"))

        if self.current_product_option == 'product_label':
            self.items[option.dest].append({
                "name":
                u_str(value),
                "product_label":
                self.current_product
            })
        elif self.current_product_option == 'product_id':
            self.items[option.dest].append({
                "name": u_str(value),
                "product_id": self.current_product
            })
        else:
            self.items[option.dest].append({
                "name": u_str(value),
                "product": self.current_product
            })
Esempio n. 3
0
    def _print_item(self, item, columns):
        """
        Print one record.

        :type item: hash
        :param item: data to print
        :type columns: list of dicts
        :param columns: columns definition
        """
        self._println()
        for column in columns:
            if not self._column_has_value(column, item):
                continue

            value = self._get_column_value(column, item)

            if not column.get('multiline', False):
                col_width = self._max_label_width(columns)
                if not isinstance(value, (list, tuple)):
                    value = [value]
                for v in value:
                    self._println(
                        ("{0:<" + u_str(col_width) + "} : {1}").format(
                            u_str(column['name']), u_str(v)))
            else:
                self._println(column['name'] + ":")
                self._println(indent_text(value, "    "))
class OrganizationDefaultInfoAPI(KatelloAPI):
    """
    Connection class to access default info keys under an organization
    """
    def create(self, org_name, informable_type, keyname):
        data = {'keyname': keyname}
        path = "/api/organizations/%s/default_info/%s" % (
            u_str(org_name), u_str(informable_type))
        return self.server.POST(path, data)[1]

    def index(self, org_name, informable_type):
        path = "/api/organizations/%s/default_info/%s" % (
            u_str(org_name), u_str(informable_type))
        return self.server.GET(path)[1]

    def destroy(self, org_name, informable_type, keyname):
        path = "/api/organizations/%s/default_info/%s/%s" % (
            u_str(org_name), u_str(informable_type), u_str(keyname))
        return self.server.DELETE(path)[1]

    def apply(self, org_name, informable_type, async=True):
        data = {'async': async}
        path = "/api/organizations/%s/default_info/%s/apply" % (
            u_str(org_name), u_str(informable_type))
        return self.server.POST(path, data)[1]
Esempio n. 5
0
    def _print_item(self, item, columns):
        """
        Print one record.

        :type item: hash
        :param item: data to print
        :type columns: list of dicts
        :param columns: columns definition
        """
        self._println()
        for column in columns:
            if not self._column_has_value(column, item):
                continue

            value = self._get_column_value(column, item)

            if not column.get('multiline', False):
                col_width = self._max_label_width(columns)
                if not isinstance(value, (list, tuple)):
                    value = [value]
                for v in value:
                    self._println(("{0:<" + u_str(col_width) + "} : {1}").format(u_str(column['name']), u_str(v)))
            else:
                self._println(column['name'] + ":")
                self._println(indent_text(value, "    "))
Esempio n. 6
0
 def products(self, filter_id, def_id, org_id):
     path = "/api/organizations/%(org_id)s/content_view_definitions/" + \
                                     "%(definition)s/filters/%(filter_id)s/products"
     path = path % {"org_id": u_str(org_id), "definition": u_str(def_id),
                          "filter_id": u_str(filter_id)}
     data = self.server.GET(path)[1]
     return data
Esempio n. 7
0
    def _store_item(self, option, opt_str, value, parser):
        if option.dest == 'add_product_label' or option.dest == 'remove_product_label':
            self.items[option.dest].append({"product_label": u_str(value)})
        elif option.dest == 'add_product_id' or option.dest == 'remove_product_id':
            self.items[option.dest].append({"product_id": u_str(value)})
        else:
            self.items[option.dest].append({"name": u_str(value)})

        setattr(parser.values, option.dest, value)
Esempio n. 8
0
 def error(self, exception, errorMsg=None):
     msg = errorMsg if errorMsg else u_str(exception)
     print >> sys.stderr, _(
         "error: %(msg)s (more in the log file %(log)s)") % {
             "msg": msg,
             "log": logfile()
         }
     _log.error(u_str(exception))
     _log.error(format_exc(exception))
Esempio n. 9
0
    def update(self, org_id, plan_id, name, sync_date, interval, description):
        data = {}
        data = update_dict_unless_none(data, "name", name)
        data = update_dict_unless_none(data, "description", description)
        data = update_dict_unless_none(data, "interval", interval)
        data = update_dict_unless_none(data, "sync_date", sync_date)

        path = "/api/organizations/%s/sync_plans/%s" % (u_str(org_id), u_str(plan_id))
        return self.server.PUT(path, {"sync_plan": data})[1]
Esempio n. 10
0
    def delete(self, org_id, system_group_id, delete_systems):
        if delete_systems:
            path = "/api/organizations/%s/system_groups/%s/destroy_systems" % (
                u_str(org_id), u_str(system_group_id))
        else:
            path = "/api/organizations/%s/system_groups/%s" % (
                u_str(org_id), u_str(system_group_id))

        return self.server.DELETE(path)[1]
Esempio n. 11
0
 def products(self, filter_id, def_id, org_id):
     path = "/api/organizations/%(org_id)s/content_view_definitions/" + \
                                     "%(definition)s/filters/%(filter_id)s/products"
     path = path % {
         "org_id": u_str(org_id),
         "definition": u_str(def_id),
         "filter_id": u_str(filter_id)
     }
     data = self.server.GET(path)[1]
     return data
Esempio n. 12
0
    def update(self, org_id, plan_id, name, sync_date, interval, description):
        data = {}
        data = update_dict_unless_none(data, "name", name)
        data = update_dict_unless_none(data, "description", description)
        data = update_dict_unless_none(data, "interval", interval)
        data = update_dict_unless_none(data, "sync_date", sync_date)

        path = "/api/organizations/%s/sync_plans/%s" % (u_str(org_id),
                                                        u_str(plan_id))
        return self.server.PUT(path, {"sync_plan": data})[1]
Esempio n. 13
0
    def _store_item(self, option, opt_str, value, parser):
        if option.dest == "add_content_view" or option.dest == "remove_content_view":
            self.items[option.dest].append({"view_name": u_str(value)})
        elif option.dest == "add_content_view_label" or option.dest == "remove_content_view_label":
            self.items[option.dest].append({"view_label": u_str(value)})
        elif option.dest == "add_content_view_id" or option.dest == "remove_content_view_id":
            self.items[option.dest].append({"view_id": u_str(value)})
        else:
            self.items[option.dest].append({"name": u_str(value)})

        setattr(parser.values, option.dest, value)
Esempio n. 14
0
    def update(self, orgName, prodId, description, gpgkey, nogpgkey, gpgkey_recursive):
        product = {}
        update_dict_unless_none(product, "description", description)
        update_dict_unless_none(product, "gpg_key_name", gpgkey)
        update_dict_unless_none(product, "recursive", gpgkey_recursive)
        if nogpgkey:
            product["gpg_key_name"] = ""

        path = "/api/organizations/%s/products/%s/" % (u_str(orgName), u_str(prodId))
        result = self.server.PUT(path, {"product": product})[1]
        return result
Esempio n. 15
0
    def run(self):
        option = self.opts.option

        Config()
        Config.parser.remove_option("options", option)
        try:
            Config.save()
            print _("Successfully forgot option [ %s ]") % u_str(option)
        except (Exception):
            print _("Unsuccessfully forgot option [ %s ]") % u_str(option)
            raise  # re-raise to get into main method -> log

        return os.EX_OK
Esempio n. 16
0
    def _store_item_with_product(self, option, opt_str, value, parser):
        if (parser.values.from_product == None) and \
           (parser.values.from_product_label == None) and \
           (parser.values.from_product_id == None):
            raise OptionValueError(_("%s must be preceded by %s, %s or %s") %
                  (option, "--from_product", "--from_product_label", "--from_product_id"))

        if self.current_product_option == 'product_label':
            self.items[option.dest].append({"name": u_str(value), "product_label": self.current_product})
        elif self.current_product_option == 'product_id':
            self.items[option.dest].append({"name": u_str(value), "product_id": self.current_product})
        else:
            self.items[option.dest].append({"name": u_str(value), "product": self.current_product})
Esempio n. 17
0
    def update(self, orgName, prodId, description, gpgkey, nogpgkey,
               gpgkey_recursive):
        product = {}
        update_dict_unless_none(product, "description", description)
        update_dict_unless_none(product, "gpg_key_name", gpgkey)
        update_dict_unless_none(product, "recursive", gpgkey_recursive)
        if nogpgkey:
            product["gpg_key_name"] = ""

        path = "/api/organizations/%s/products/%s/" % (u_str(orgName),
                                                       u_str(prodId))
        result = self.server.PUT(path, {"product": product})[1]
        return result
Esempio n. 18
0
    def run(self):
        option = self.opts.option

        Config()
        Config.parser.remove_option('options', option)
        try:
            Config.save()
            print _("Successfully forgot option [ %s ]") % u_str(option)
        except (Exception):
            print _("Unsuccessfully forgot option [ %s ]") % u_str(option)
            raise  # re-raise to get into main method -> log

        return os.EX_OK
Esempio n. 19
0
    def _store_item_with_product(self, option, opt_str, value, parser):
        if (parser.values.from_product == None) and \
           (parser.values.from_product_label == None) and \
           (parser.values.from_product_id == None):
            raise OptionValueError(_("%(option)s must be preceded by %(from_product)s, \
                %(from_product_label)s or %(from_product_id)s") 
                    % {'option':option, 'from_product':"--from_product",
                    'from_product_label':"--from_product_label", 'from_product_id':"--from_product_id"})

        if self.current_product_option == 'from_product_label':
            self.items[option.dest].append({"name": u_str(value), "from_product_label": self.current_product})
        elif self.current_product_option == 'from_product_id':
            self.items[option.dest].append({"name": u_str(value), "from_product_id": self.current_product})
        else:
            self.items[option.dest].append({"name": u_str(value), "from_product": self.current_product})
Esempio n. 20
0
    def _print_item(self, item, columns, column_widths):
        """
        Print item of a list on single line

        :type item: hash
        :param item: data to print
        :type columns: list of dicts
        :param columns: columns definition
        :type column_widths:
        :param column_widths:
        """
        for column in columns:
            #get defined width
            width = column_widths.get(column['attr_name'], 0)

            #skip missing attributes
            if not self._column_has_value(column, item):
                if self.__delim:
                    self._print(" " * width)
                else:
                    self._print(self.__delim)
                continue
            value = self._get_column_value(column, item)

            if column.get('multiline', False):
                value = text_to_line(value)
            value = u_str(value)

            if self.__delim:
                self._print('%s' % (value) + self.__delim)
            else:
                self._print('%s%s' % (value, ' ' * (width - unicode_len(
                    (value)))))
Esempio n. 21
0
 def import_manifest(self, provId, manifestFile, force=False):
     path = "/api/providers/%s/import_manifest" % u_str(provId)
     params = {"import": manifestFile}
     if force:
         params["force"] = "true"
     result = self.server.POST(path, params, multipart=True)[1]
     return result
Esempio n. 22
0
    def run(self):
        errId = self.get_option("id")
        repoId = self.get_option("repo_id")
        repoName = self.get_option("repo")
        orgName = self.get_option("org")
        envName = self.get_option("environment")
        prodName = self.get_option("product")
        prodLabel = self.get_option("product_label")
        prodId = self.get_option("product_id")

        if not repoId:
            repo = get_repo(orgName, prodName, prodLabel, prodId, repoName, envName)
            repoId = repo["id"]

        pack = self.api.errata(errId, repoId)

        pack["affected_packages"] = [u_str(pinfo["filename"]) for pkg in pack["pkglist"] for pinfo in pkg["packages"]]

        batch_add_columns(self.printer, {"id": _("ID")}, {"title": _("Title")})
        self.printer.add_column("description", _("Description"), multiline=True)
        batch_add_columns(
            self.printer,
            {"type": _("Type")},
            {"issued": _("Issued")},
            {"updated": _("Updated")},
            {"version": _("Version")},
            {"release": _("Release")},
            {"status": _("Status")},
            {"reboot_suggested": _("Reboot Suggested")},
        )
        self.printer.add_column("affected_packages", _("Affected Packages"), multiline=True)

        self.printer.set_header(_("Errata Information"))
        self.printer.print_item(pack)
        return os.EX_OK
Esempio n. 23
0
    def run(self):
        errId     = self.get_option('id')
        repoId    = self.get_option('repo_id')
        repoName  = self.get_option('repo')
        orgName   = self.get_option('org')
        envName   = self.get_option('environment')
        prodName  = self.get_option('product')
        prodLabel = self.get_option('product_label')
        prodId    = self.get_option('product_id')
        viewName  = self.get_option('view_name')
        viewLabel = self.get_option('view_label')
        viewId    = self.get_option('view_id')

        if not repoId:
            repo = get_repo(orgName, repoName, prodName, prodLabel, prodId, envName,
                            viewName, viewLabel, viewId)
            repoId = repo["id"]

        pack = self.api.errata(errId, repoId)

        pack['affected_packages'] = [u_str(pinfo['filename'])
                         for pkg in pack['pkglist']
                         for pinfo in pkg['packages']]

        batch_add_columns(self.printer, {'errata_id': _("ID")}, {'title': _("Title")})
        self.printer.add_column('description', _("Description"), multiline=True)
        batch_add_columns(self.printer, {'type': _("Type")}, {'issued': _("Issued")}, \
            {'updated': _("Updated")}, {'version': _("Version")}, {'release': _("Release")}, \
            {'status': _("Status")}, {'reboot_suggested': _("Reboot Suggested")})
        self.printer.add_column('affected_packages', _("Affected Packages"), multiline=True)

        self.printer.set_header(_("Errata Information"))
        self.printer.print_item(pack)
        return os.EX_OK
Esempio n. 24
0
    def update(self, name, description):

        orgdata = {}
        orgdata = update_dict_unless_none(orgdata, "description", description)

        path = "/api/organizations/%s" % u_str(name)
        return self.server.PUT(path, {"organization": orgdata})[1]
Esempio n. 25
0
    def _print_item(self, item, columns, column_widths):
        """
        Print item of a list on single line

        :type item: hash
        :param item: data to print
        :type columns: list of dicts
        :param columns: columns definition
        :type column_widths:
        :param column_widths:
        """
        for column in columns:
            #get defined width
            width = column_widths.get(column['attr_name'], 0)

            #skip missing attributes
            if not self._column_has_value(column, item):
                if self.__delim:
                    self._print(" " * width)
                else:
                    self._print(self.__delim)
                continue
            value = self._get_column_value(column, item)

            if column.get('multiline', False):
                value = text_to_line(value)
            value = u_str(value)

            if self.__delim:
                self._print('%s' % (value) + self.__delim)
            else:
                self._print('%s%s' % (value, ' '*(width-unicode_len((value)))))
Esempio n. 26
0
    def _store_parameter_value(self, option, opt_str, value, parser):
        if self.current_parameter == None:
            raise OptionValueError(_("each %(option)s must be preceeded by %(paramater)s") \
                % {'option':option, 'parameter':"--add_parameter"} )

        self.items['add_parameters'][self.current_parameter] = u_str(value)
        self.current_parameter = None
Esempio n. 27
0
 def import_manifest(self, provId, manifestFile, force=False):
     path = "/api/providers/%s/import_manifest" % u_str(provId)
     params = {"import": manifestFile}
     if force:
         params["force"] = "true"
     result = self.server.POST(path, params, multipart=True)[1]
     return result
Esempio n. 28
0
 def template_by_name(self, envId, tplName):
     path = "/api/environments/%s/templates/" % u_str(envId)
     tpls = self.server.GET(path, {"name": tplName})[1]
     if len(tpls) > 0:
         #show provides more information than index
         return self.template(tpls[0]["id"])
     else:
         return None
Esempio n. 29
0
 def entitlements():
     for entitlement in result['entitlements']:
         entitlement_ext = entitlement.copy()
         provided_products = ', '.join([e['name'] for e in entitlement_ext['providedProducts']])
         entitlement_ext['providedProductsFormatted'] = provided_products
         serial_ids = ', '.join([u_str(s['id']) for s in entitlement_ext['serials']])
         entitlement_ext['serialIds'] = serial_ids
         yield entitlement_ext
Esempio n. 30
0
 def product_by_name_or_label_or_id(self, orgName, prodName, prodLabel, prodId):
     params = {}
     update_dict_unless_none(params, "name", prodName)
     update_dict_unless_none(params, "label", prodLabel)
     update_dict_unless_none(params, "cp_id", prodId)
     path = "/api/organizations/%s/products" % u_str(orgName)
     products = self.server.GET(path, params)[1]
     return products
Esempio n. 31
0
 def checkin(self, system_uuid, checkin_time=None):
     path = "/api/systems/%s/checkin" % u_str(system_uuid)
     if not checkin_time:
         checkin_time = datetime.datetime.now()
     params = {
         "date": checkin_time.isoformat()
     }
     return self.server.PUT(path, params)[1]
Esempio n. 32
0
 def create(self, org_id, name, sync_date, interval, description):
     data = {
         "name": name,
         "description": description,
         "interval": interval,
         "sync_date": sync_date
     }
     path = "/api/organizations/%s/sync_plans/" % u_str(org_id)
     return self.server.POST(path, {"sync_plan": data})[1]
Esempio n. 33
0
    def error(self, error_msg):
        """
        Logs an error and prints it to stderr
        """
        error_msg = u_str(error_msg)
        error_msg = error_msg if error_msg else _('operation failed')

        _log.error("error: " + error_msg)
        print >> sys.stderr, error_msg
Esempio n. 34
0
    def update(self, provId, name, description=None, url=None):

        provdata = {}
        provdata = update_dict_unless_none(provdata, "name", name)
        provdata = update_dict_unless_none(provdata, "description", description)
        provdata = update_dict_unless_none(provdata, "repository_url", url)

        path = "/api/providers/%s" % u_str(provId)
        return self.server.PUT(path, {"provider": provdata})[1]
Esempio n. 35
0
def indent_text(text, indent="\t"):
    """
    Indents given text.

    :type text: string or list of strings
    :param text: text to be indented
    :type indent: string
    :param indent: value that is added at the beggining of each line of the text
    :rtype: string
    """
    if text is None:
        text = u_str(None)

    if isinstance(text, list):
        glue = "\n" + indent
        return indent + glue.join([u_str(l) for l in text])
    else:
        return indent_text(text.split("\n"), indent)
Esempio n. 36
0
 def create(self, org_id, name, sync_date, interval, description):
     data = {
         "name": name,
         "description": description,
         "interval": interval,
         "sync_date": sync_date
     }
     path = "/api/organizations/%s/sync_plans/" % u_str(org_id)
     return self.server.POST(path, {"sync_plan": data})[1]
Esempio n. 37
0
    def error(self, error_msg):
        """
        Logs an error and prints it to stderr
        """
        error_msg = u_str(error_msg)
        error_msg = error_msg if error_msg else _('operation failed')

        _log.error("error: %s" % error_msg)
        print >> sys.stderr, error_msg
Esempio n. 38
0
def indent_text(text, indent="\t"):
    """
    Indents given text.

    :type text: string or list of strings
    :param text: text to be indented
    :type indent: string
    :param indent: value that is added at the beggining of each line of the text
    :rtype: string
    """
    if text is None:
        text = u_str(None)

    if isinstance(text, list):
        glue = "\n"+indent
        return indent+glue.join([u_str(l) for l in text])
    else:
        return indent_text(text.split("\n"), indent)
Esempio n. 39
0
 def product_by_name_or_label_or_id(self, orgName, prodName, prodLabel,
                                    prodId):
     params = {}
     update_dict_unless_none(params, "name", prodName)
     update_dict_unless_none(params, "label", prodLabel)
     update_dict_unless_none(params, "cp_id", prodId)
     path = "/api/organizations/%s/products" % u_str(orgName)
     products = self.server.GET(path, params)[1]
     return products
Esempio n. 40
0
    def update(self, provId, name, description=None, url=None):

        provdata = {}
        provdata = update_dict_unless_none(provdata, "name", name)
        provdata = update_dict_unless_none(provdata, "description",
                                           description)
        provdata = update_dict_unless_none(provdata, "repository_url", url)

        path = "/api/providers/%s" % u_str(provId)
        return self.server.PUT(path, {"provider": provdata})[1]
Esempio n. 41
0
    def create(self, provId, name, label, description, gpgkey):
        product = {
            "name": name,
            "label": label,
            "description": description,
            "gpg_key_name": gpgkey
        }

        path = "/api/providers/%s/product_create" % u_str(provId)
        result = self.server.POST(path, {"product": product})[1]
        return result
Esempio n. 42
0
    def create(self, provId, name, label, description, gpgkey):
        product = {
            "name": name,
            "label": label,
            "description": description,
            "gpg_key_name": gpgkey
        }

        path = "/api/providers/%s/product_create" % u_str(provId)
        result = self.server.POST(path, {"product": product})[1]
        return result
Esempio n. 43
0
 def entitlements():
     for entitlement in result["entitlements"]:
         entitlement_ext = entitlement.copy()
         provided_products = ", ".join([e["name"] for e in entitlement_ext["providedProducts"]])
         if provided_products:
             entitlement_ext["providedProductsFormatted"] = _("Not Applicable")
         else:
             entitlement_ext["providedProductsFormatted"] = provided_products
         serial_ids = ", ".join([u_str(s["id"]) for s in entitlement_ext["serials"]])
         entitlement_ext["serialIds"] = serial_ids
         yield entitlement_ext
Esempio n. 44
0
    def run(self):
        option = self.opts.option
        value = self.opts.value

        Config()
        if not Config.parser.has_section("options"):
            Config.parser.add_section("options")

        has_option = Config.parser.has_option("options", option)
        Config.parser.set("options", option, value)

        try:
            Config.save()
            if has_option:
                print _("Successfully overwrote option [ %s ] ") % u_str(option)
            else:
                print _("Successfully remembered option [ %s ] ") % u_str(option)
        except (Exception):
            print _("Unsuccessfully remembered option [ %s ]") % u_str(option)
            raise  # re-raise to get into main method -> log

        return os.EX_OK
Esempio n. 45
0
    def update(self, tplId, newName, description, parentId):

        tplData = {}
        tplData = update_dict_unless_none(tplData, "name", newName)
        tplData = update_dict_unless_none(tplData, "description", description)
        tplData = update_dict_unless_none(tplData, "parent_id", parentId)

        tplData = {
            "template": tplData
        }

        path = "/api/templates/%s" % u_str(tplId)
        return self.server.PUT(path, tplData)[1]
Esempio n. 46
0
    def _process_response(self, response):
        """
        Try to parse the response
        @type response: HTTPResponse
        @param response: http response
        @rtype: (int, string)
        @return: tuple of the response status and response body
        """
        response_body = response.read()
        try:
            response_body = json.loads(response_body, encoding='utf-8')
        except ValueError:
            content_type = response.getheader('content-type')
            if content_type and (content_type.startswith('text/') or content_type.startswith('application/json')):
                response_body = u_str(response_body)
            else:
                pass

        if response_body and self._log.isEnabledFor(logging.DEBUG):
            content_type = response.getheader('content-type')
            if content_type and (content_type.startswith('text/') or content_type.startswith('application/json')):
                self._log.debug("processing response %s\n%s" % (response.status, u_str(response_body)))
            else:
                self._log.debug("processing response %s of %s" % (response.status, content_type))
        else:
            self._log.debug("processing empty response %s" % (response.status))

        if response.status >= 300:
            # if the server has responded with a python traceback
            # try to split it out
            if isinstance(response_body, basestring) and not response_body.startswith('<html'): # pylint: disable=E1103
                response_body += "\n"
                message, traceback = response_body.split('\n', 1)
                raise ServerRequestError(response.status, message.strip(), traceback.strip())
            raise ServerRequestError(response.status, response_body, None)
        return (response.status, response_body, response.getheaders())
Esempio n. 47
0
    def run(self):
        option = self.opts.option
        value = self.opts.value

        Config()
        if not Config.parser.has_section('options'):
            Config.parser.add_section('options')

        has_option = Config.parser.has_option('options', option)
        Config.parser.set('options', option, value)

        try:
            Config.save()
            if has_option:
                print _("Successfully overwrote option [ %s ] ") % u_str(
                    option)
            else:
                print _("Successfully remembered option [ %s ] ") % u_str(
                    option)
        except (Exception):
            print _("Unsuccessfully remembered option [ %s ]") % u_str(option)
            raise  # re-raise to get into main method -> log

        return os.EX_OK
Esempio n. 48
0
    def update(self, user_id, pw, email, disabled, default_environment, default_locale=None):
        userdata = {}
        userdata = update_dict_unless_none(userdata, "password", pw)
        userdata = update_dict_unless_none(userdata, "email", email)
        userdata = update_dict_unless_none(userdata, "disabled", disabled)

        if default_environment is None:
            userdata.update(default_environment_id=None)                        # pylint: disable=E1101
        elif default_environment is not False:
            userdata.update(default_environment_id=default_environment['id'])   # pylint: disable=E1101

        if default_locale is not None:
            userdata = update_dict_unless_none(userdata, "default_locale", default_locale)

        path = "/api/users/%s" % u_str(user_id)
        return self.server.PUT(path, {"user": userdata})[1]
Esempio n. 49
0
    def update(self, user_id, pw, email, disabled, default_environment, default_locale=None):
        userdata = {}
        userdata = update_dict_unless_none(userdata, "password", pw)
        userdata = update_dict_unless_none(userdata, "email", email)
        userdata = update_dict_unless_none(userdata, "disabled", disabled)

        if default_environment is None:
            userdata.update(default_environment_id=None)                        # pylint: disable=E1101
        elif default_environment is not False:
            userdata.update(default_environment_id=default_environment['id'])   # pylint: disable=E1101

        if default_locale is not None:
            userdata = update_dict_unless_none(userdata, "default_locale", default_locale)

        path = "/api/users/%s" % u_str(user_id)
        return self.server.PUT(path, {"user": userdata})[1]
Esempio n. 50
0
 def entitlements():
     for entitlement in result['entitlements']:
         entitlement_ext = entitlement.copy()
         provided_products = ', '.join([
             e['name'] for e in entitlement_ext['providedProducts']
         ])
         if provided_products:
             entitlement_ext['providedProductsFormatted'] = _(
                 'Not Applicable')
         else:
             entitlement_ext[
                 'providedProductsFormatted'] = provided_products
         serial_ids = ', '.join(
             [u_str(s['id']) for s in entitlement_ext['serials']])
         entitlement_ext['serialIds'] = serial_ids
         yield entitlement_ext
Esempio n. 51
0
def text_to_line(text, glue=" "):
    """
    Squeezes a block of text to one line.

    :type text: string
    :param text: text to be processed
    :type glue: string
    :param glue: string used for joining lines of the text
    :rtype: string
    """
    if text is None:
        text = u_str(None)

    if isinstance(text, list):
        return glue.join(text)
    else:
        return glue.join(text.split("\n"))
Esempio n. 52
0
    def _column_width(self, items, column):
        """
        Returns maximum width for the column to ensure that all the data
        and the label fits in.

        :type columns: list of dicts
        :param columns: columns definition
        :type column: dict
        :param column: column definition
        :rtype: int
        """
        width = unicode_len(column['name']) + 1
        for column_value in [
                u_str(self._get_column_value(column, item)) for item in items
        ]:
            new_width = unicode_len(column_value)
            if width <= new_width:
                width = new_width + 1
        return width
Esempio n. 53
0
    def _store_item(self, option, opt_str, value, parser):
        if option.dest == 'add_product_label' or option.dest == 'remove_product_label':
            self.items[option.dest].append({"product_label": u_str(value)})
        elif option.dest == 'add_product_id' or option.dest == 'remove_product_id':
            self.items[option.dest].append({"product_id": u_str(value)})
        elif option.dest == "add_content_view" or option.dest == "remove_content_view":
            self.items[option.dest].append({"view_name": u_str(value)})
        elif option.dest == "add_content_view_label" or option.dest == "remove_content_view_label":
            self.items[option.dest].append({"view_label": u_str(value)})
        elif option.dest == "add_content_view_id" or option.dest == "remove_content_view_id":
            self.items[option.dest].append({"view_id": u_str(value)})
        else:
            self.items[option.dest].append({"name": u_str(value)})

        setattr(parser.values, option.dest, value)
Esempio n. 54
0
    def create(self, roleId, name, description, type_in, verbs, tagIds, 
               orgId = None, all_tags = False, all_verbs = False):
        data = {
            "name": name,
            "description": description,
            "type": type_in,
            "organization_id": orgId
        }

        if all_tags:
            data["all_tags"] = "True"
        else:
            data["tags"] = tagIds

        if all_verbs:
            data["all_verbs"] = "True"
        else:
            data["verbs"] = verbs

        path = "/api/roles/%s/permissions/" % u_str(roleId)
        return self.server.POST(path, data)[1]
Esempio n. 55
0
    def run(self):
        errId = self.get_option('id')
        repoId = self.get_option('repo_id')
        repoName = self.get_option('repo')
        orgName = self.get_option('org')
        envName = self.get_option('environment')
        prodName = self.get_option('product')
        prodLabel = self.get_option('product_label')
        prodId = self.get_option('product_id')
        viewName = self.get_option('view_name')
        viewLabel = self.get_option('view_label')
        viewId = self.get_option('view_id')

        if not repoId:
            repo = get_repo(orgName, repoName, prodName, prodLabel, prodId,
                            envName, viewName, viewLabel, viewId)
            repoId = repo["id"]

        pack = self.api.errata(errId, repoId)

        pack['affected_packages'] = [
            u_str(pinfo['filename']) for pkg in pack['pkglist']
            for pinfo in pkg['packages']
        ]

        batch_add_columns(self.printer, {'errata_id': _("ID")},
                          {'title': _("Title")})
        self.printer.add_column('description',
                                _("Description"),
                                multiline=True)
        batch_add_columns(self.printer, {'type': _("Type")}, {'issued': _("Issued")}, \
            {'updated': _("Updated")}, {'version': _("Version")}, {'release': _("Release")}, \
            {'status': _("Status")}, {'reboot_suggested': _("Reboot Suggested")})
        self.printer.add_column('affected_packages',
                                _("Affected Packages"),
                                multiline=True)

        self.printer.set_header(_("Errata Information"))
        self.printer.print_item(pack)
        return os.EX_OK
Esempio n. 56
0
    def select_repositories(self, repourls, assumeyes, our_raw_input = raw_input):
        selection = Selection()
        if not assumeyes:
            proceed = ''
            num_selects = [u_str(i+1) for i in range(len(repourls))]
            select_range_str = constants.SELECTION_QUERY % len(repourls)
            while proceed.strip().lower() not in  ['q', 'y']:
                if not proceed.strip().lower() == 'h':
                    self.__print_urls(repourls, selection)
                proceed = our_raw_input(
                    _("\nSelect urls for which candidate repos should be created; use `y` to confirm (h for help):"))
                select_val = proceed.strip().lower()
                if select_val == 'h':
                    print select_range_str
                elif select_val == 'a':
                    selection.add_selection(repourls)
                elif select_val in num_selects:
                    selection.add_selection([repourls[int(proceed.strip().lower())-1]])
                elif select_val == 'q':
                    selection = Selection()
                    system_exit(os.EX_OK, _("Operation aborted upon user request."))
                elif set(select_val.split(":")).issubset(num_selects):
                    lower, upper = tuple(select_val.split(":"))
                    selection.add_selection(repourls[int(lower)-1:int(upper)])
                elif select_val == 'c':
                    selection = Selection()
                elif select_val == 'y':
                    if not len(selection):
                        proceed = ''
                        continue
                    else:
                        break
                else:
                    continue
        else:
            #select all
            selection.add_selection(repourls)
            self.__print_urls(repourls, selection)

        return selection
Esempio n. 57
0
 def _store_from_product(self, option, opt_str, value, parser):
     self.current_product = u_str(value)
     self.current_product_option = option.dest
     setattr(parser.values, option.dest, value)
Esempio n. 58
0
        except SocketError, se:
            self.error(se.args[1])
            return se.args[0]

        except OptionParserExitError, opee:
            return opee.args[0]

        except ApiDataError, ade:
            print >> sys.stderr, ade.args[0]
            return os.EX_DATAERR

        except SystemExitRequest, ser:
            msg = "\n".join(ser.args[1]).strip()
            if ser.args[0] == os.EX_OK:
                out = sys.stdout
                _log.info(u_str(msg))
            else:
                out = sys.stderr

            if msg != "":
                print >> out, msg
            return ser.args[0]

        except KeyboardInterrupt:
            return os.EX_NOUSER

        print ''


# optparse type extenstions --------------------------------------------------
Esempio n. 59
0
 def remove_content(self, csId, contentType, attrs):
     path = "/api/changesets/%s/%s/%s/" % (u_str(csId), contentType, u_str(attrs['content_id']))
     return self.server.DELETE(path, attrs)[1]
Esempio n. 60
0
 def add_content(self, csId, contentType, attrs):
     path = "/api/changesets/%s/%s/" % (u_str(csId), contentType)
     return self.server.POST(path, attrs)[1]