def __str__(self):
     self.details = _("Requested version of osvmexpire API is not"
                      "available.")
     return (_("%(name)s (HTTP %(code)s) %(details)s") % {
         'name': reflection.get_class_name(self, fully_qualified=False),
         'code': self.code,
         'details': self.details
     })
 def __str__(self):
     message = self.error['error'].get('message', 'Internal Error')
     if verbose:
         traceback = self.error['error'].get('traceback', '')
         return (_('ERROR: %(message)s\n%(traceback)s') % {
             'message': message,
             'traceback': traceback
         })
     else:
         return _('ERROR: %s') % message
 def get_parser(self, prog_name):
     parser = super(CreateExclude, self).get_parser(prog_name)
     parser.add_argument(
         'id',
         metavar='<osvmexclude-object-id>',
         help=_('Id of the element to exclude (domain, project, user)'))
     parser.add_argument(
         'type',
         metavar='<osvmexclude-object-type>',
         help=_('Type of the element to exclude [domain, project, user]'))
     return parser
Exemple #4
0
def format_parameters(params, parse_semicolon=True):
    '''Reformat parameters into dict of format expected by the API.'''

    if not params:
        return {}

    if parse_semicolon:
        # expect multiple invocations of --parameters but fall back
        # to ; delimited if only one --parameters is specified
        if len(params) == 1:
            params = params[0].split(';')

    parameters = {}
    for p in params:
        try:
            (n, v) = p.split(('='), 1)
        except ValueError:
            msg = _('Malformed parameter(%s). Use the key=value format.') % p
            raise exc.CommandError(msg)

        if n not in parameters:
            parameters[n] = v
        else:
            if not isinstance(parameters[n], list):
                parameters[n] = [parameters[n]]
            parameters[n].append(v)

    return parameters
Exemple #5
0
def find_resource(manager, name_or_id):
    """Helper for the _find_* methods."""
    # first try to get entity as integer id
    try:
        if isinstance(name_or_id, int) or name_or_id.isdigit():
            return manager.get(int(name_or_id))
    except exc.NotFound:
        pass

    # now try to get entity as uuid
    try:
        uuid.UUID(str(name_or_id))
        return manager.get(name_or_id)
    except (ValueError, exc.NotFound):
        pass

    # finally try to find entity by name
    try:
        return manager.find(name=name_or_id)
    except exc.NotFound:
        msg = (_("No %(name)s with a name or ID of "
                 "'%(name_or_id)s' exists.") % {
                     'name': manager.resource_class.__name__.lower(),
                     'name_or_id': name_or_id
                 })
        raise exc.CommandError(msg)
 def get_parser(self, prog_name):
     parser = super(ListExpire, self).get_parser(prog_name)
     parser.add_argument(
         '--all',
         action='store_true',
         help=_('List expirations for all projects (admin only)'))
     return parser
Exemple #7
0
def format_output(output, format='yaml'):
    """Format the supplied dict as specified."""
    output_format = format.lower()
    try:
        return supported_formats[output_format](output)
    except KeyError:
        raise exc.HTTPUnsupported(
            _("The format(%s) is unsupported.") % output_format)
Exemple #8
0
def print_list(objs,
               fields,
               formatters=None,
               sortby_index=0,
               mixed_case_fields=None,
               field_labels=None):
    """Print a list of objects as a table, one row per object.

    :param objs: iterable of :class:`Resource`
    :param fields: attributes that correspond to columns, in order
    :param formatters: `dict` of callables for field formatting
    :param sortby_index: index of the field for sorting table rows
    :param mixed_case_fields: fields corresponding to object attributes that
        have mixed case names (e.g., 'serverId')
    :param field_labels: Labels to use in the heading of the table, default to
        fields.
    """
    formatters = formatters or {}
    mixed_case_fields = mixed_case_fields or []
    field_labels = field_labels or fields
    if len(field_labels) != len(fields):
        raise ValueError(
            _("Field labels list %(labels)s has different number "
              "of elements than fields list %(fields)s"), {
                  'labels': field_labels,
                  'fields': fields
              })

    if sortby_index is None:
        kwargs = {}
    else:
        kwargs = {'sortby': field_labels[sortby_index]}
    pt = prettytable.PrettyTable(field_labels)
    pt.align = 'l'

    for o in objs:
        row = []
        for field in fields:
            if field in formatters:
                row.append(formatters[field](o))
            else:
                if field in mixed_case_fields:
                    field_name = field.replace(' ', '_')
                else:
                    field_name = field.lower().replace(' ', '_')
                data = getattr(o, field_name, '')
                row.append(data)
        pt.add_row(row)

    if six.PY3:
        print(encodeutils.safe_encode(pt.get_string(**kwargs)).decode())
    else:
        print(encodeutils.safe_encode(pt.get_string(**kwargs)))
Exemple #9
0
def read_url_content(url):
    try:
        content = request.urlopen(url).read()
    except error.URLError:
        raise exc.CommandError(_('Could not fetch contents for %s') % url)

    if content:
        try:
            content.decode('utf-8')
        except ValueError:
            content = base64.encodestring(content)
    return content
 def __init__(self, message=None, code=None):
     super(HTTPException, self).__init__(message)
     try:
         self.error = jsonutils.loads(message)
         if 'error' not in self.error:
             raise KeyError(_('Key "error" not exists'))
     except KeyError:
         # NOTE(jianingy): If key 'error' happens not exist,
         # self.message becomes no sense. In this case, we
         # return doc of current exception class instead.
         self.error = {'error': {'message': self.__class__.__doc__}}
     except Exception:
         self.error = {
             'error': {
                 'message': self.message or self.__class__.__doc__
             }
         }
     if self.code == "N/A" and code is not None:
         self.code = code
 def get_parser(self, prog_name):
     parser = super(ShowExclude, self).get_parser(prog_name)
     parser.add_argument('id',
                         metavar='<osvmexclude-id>',
                         help=_('Id of the exclude'))
     return parser
 def get_parser(self, prog_name):
     parser = super(DeleteExpire, self).get_parser(prog_name)
     parser.add_argument('id',
                         metavar='<osvmexpire-id>',
                         help=_('Name of the osvmexpire'))
     return parser