예제 #1
0
 def run_subcommand(self, argv):
     subcommand = self.command_manager.find_command(argv)
     cmd_factory, cmd_name, sub_argv = subcommand
     cmd = cmd_factory(self, self.options)
     err = None
     result = 1
     try:
         self.prepare_to_run_command(cmd)
         full_name = (cmd_name if self.interactive_mode else ' '.join(
             [self.NAME, cmd_name]))
         cmd_parser = cmd.get_parser(full_name)
         return run_command(cmd, cmd_parser, sub_argv)
     except Exception as err:
         if self.options.verbose_level == self.DEBUG_LEVEL:
             self.log.exception(unicode(err))
         else:
             self.log.error(unicode(err))
         try:
             self.clean_up(cmd, result, err)
         except Exception as err2:
             if self.options.verbose_level == self.DEBUG_LEVEL:
                 self.log.exception(unicode(err2))
             else:
                 self.log.error(_('Could not clean up: %s'), unicode(err2))
         if self.options.verbose_level == self.DEBUG_LEVEL:
             raise
     else:
         try:
             self.clean_up(cmd, result, None)
         except Exception as err3:
             if self.options.verbose_level == self.DEBUG_LEVEL:
                 self.log.exception(unicode(err3))
             else:
                 self.log.error(_('Could not clean up: %s'), unicode(err3))
     return result
예제 #2
0
 def run(self, parsed_args):
     self.log.debug('run(%s)', parsed_args)
     tacker_client = self.get_client()
     tacker_client.format = parsed_args.request_format
     _extra_values = parse_args_to_dict(self.values_specs)
     _merge_args(self, parsed_args, _extra_values,
                 self.values_specs)
     body = self.args2body(parsed_args)
     if self.resource in body:
         body[self.resource].update(_extra_values)
     else:
         body[self.resource] = _extra_values
     if not body[self.resource]:
         raise exceptions.CommandError(
             _("Must specify new values to update %s") % self.resource)
     if self.allow_names:
         _id = find_resourceid_by_name_or_id(
             tacker_client, self.resource, parsed_args.id)
     else:
         _id = find_resourceid_by_id(
             tacker_client, self.resource, parsed_args.id)
     obj_updator = getattr(tacker_client,
                           "update_%s" % self.resource)
     obj_updator(_id, body)
     print((_('Updated %(resource)s: %(id)s') %
            {'id': parsed_args.id, 'resource': self.resource}),
           file=self.app.stdout)
     return
예제 #3
0
    def args2body(self, parsed_args):
        body = {
            self.resource: {
                'template_id': parsed_args.device_template_id,
            }
        }
        if parsed_args.attributes:
            try:
                attributes = dict(key_value.split('=', 1)
                                  for key_value in parsed_args.attributes)
            except ValueError:
                msg = (_('invalid argument for --attributes %s') %
                       parsed_args.attributes)
                raise exceptions.TackerCLIError(msg)
            if attributes:
                body[self.resource]['attributes'] = attributes
        if parsed_args.service_context:
            try:
                service_contexts = [dict(
                    (k.replace('-', '_'), v)
                    for k, v in (key_value.split('=', 1)
                                 for key_value in entry_string.split(',')))
                    for entry_string in parsed_args.service_context]
            except ValueError:
                msg = (_('invalid argument for --service-context %s') %
                       parsed_args.service_context)
                raise exceptions.TackerCLIError(msg)

            if service_contexts:
                body[self.resource]['service_contexts'] = service_contexts

        tackerV10.update_dict(parsed_args, body[self.resource], ['tenant_id'])
        return body
예제 #4
0
def to_bytes(text, default=0):
    """Converts a string into an integer of bytes.

    Looks at the last characters of the text to determine
    what conversion is needed to turn the input text into a byte number.
    Supports "B, K(B), M(B), G(B), and T(B)". (case insensitive)

    :param text: String input for bytes size conversion.
    :param default: Default return value when text is blank.

    """
    match = BYTE_REGEX.search(text)
    if match:
        magnitude = int(match.group(1))
        mult_key_org = match.group(2)
        if not mult_key_org:
            return magnitude
    elif text:
        msg = _('Invalid string format: %s') % text
        raise TypeError(msg)
    else:
        return default
    mult_key = mult_key_org.lower().replace('b', '', 1)
    multiplier = BYTE_MULTIPLIERS.get(mult_key)
    if multiplier is None:
        msg = _('Unknown byte multiplier: %s') % mult_key_org
        raise TypeError(msg)
    return magnitude * multiplier
예제 #5
0
 def run(self, parsed_args):
     self.log.debug('run(%s)', parsed_args)
     tacker_client = self.get_client()
     tacker_client.format = parsed_args.request_format
     _extra_values = parse_args_to_dict(self.values_specs)
     _merge_args(self, parsed_args, _extra_values, self.values_specs)
     body = self.args2body(parsed_args)
     if self.resource in body:
         body[self.resource].update(_extra_values)
     else:
         body[self.resource] = _extra_values
     if not body[self.resource]:
         raise exceptions.CommandError(
             _("Must specify new values to update %s") % self.resource)
     if self.allow_names:
         _id = find_resourceid_by_name_or_id(tacker_client, self.resource,
                                             parsed_args.id)
     else:
         _id = find_resourceid_by_id(tacker_client, self.resource,
                                     parsed_args.id)
     obj_updator = getattr(tacker_client, "update_%s" % self.resource)
     obj_updator(_id, body)
     print((_('Updated %(resource)s: %(id)s') % {
         'id': parsed_args.id,
         'resource': self.resource
     }),
           file=self.app.stdout)
     return
예제 #6
0
def to_bytes(text, default=0):
    """Converts a string into an integer of bytes.

    Looks at the last characters of the text to determine
    what conversion is needed to turn the input text into a byte number.
    Supports "B, K(B), M(B), G(B), and T(B)". (case insensitive)

    :param text: String input for bytes size conversion.
    :param default: Default return value when text is blank.

    """
    match = BYTE_REGEX.search(text)
    if match:
        magnitude = int(match.group(1))
        mult_key_org = match.group(2)
        if not mult_key_org:
            return magnitude
    elif text:
        msg = _('Invalid string format: %s') % text
        raise TypeError(msg)
    else:
        return default
    mult_key = mult_key_org.lower().replace('b', '', 1)
    multiplier = BYTE_MULTIPLIERS.get(mult_key)
    if multiplier is None:
        msg = _('Unknown byte multiplier: %s') % mult_key_org
        raise TypeError(msg)
    return magnitude * multiplier
예제 #7
0
 def get_parser(self, prog_name):
     parser = super(DeleteCommand, self).get_parser(prog_name)
     if self.allow_names:
         help_str = _('ID or name of %s to delete')
     else:
         help_str = _('ID of %s to delete')
     parser.add_argument(
         'id', metavar=self.resource.upper(),
         help=help_str % self.resource)
     return parser
예제 #8
0
 def get_parser(self, prog_name):
     parser = super(DeleteCommand, self).get_parser(prog_name)
     if self.allow_names:
         help_str = _('ID or name of %s to delete')
     else:
         help_str = _('ID of %s to delete')
     parser.add_argument('id',
                         metavar=self.resource.upper(),
                         help=help_str % self.resource)
     return parser
예제 #9
0
 def get_parser(self, prog_name):
     parser = super(ShowCommand, self).get_parser(prog_name)
     add_show_list_common_argument(parser)
     if self.allow_names:
         help_str = _('ID or name of %s to look up')
     else:
         help_str = _('ID of %s to look up')
     parser.add_argument(
         'id', metavar=self.resource.upper(),
         help=help_str % self.resource)
     return parser
예제 #10
0
 def get_parser(self, prog_name):
     parser = super(ShowCommand, self).get_parser(prog_name)
     add_show_list_common_argument(parser)
     if self.allow_names:
         help_str = _('ID or name of %s to look up')
     else:
         help_str = _('ID of %s to look up')
     parser.add_argument('id',
                         metavar=self.resource.upper(),
                         help=help_str % self.resource)
     return parser
예제 #11
0
def add_pagination_argument(parser):
    parser.add_argument(
        '-P', '--page-size',
        dest='page_size', metavar='SIZE', type=int,
        help=_("Specify retrieve unit of each request, then split one request "
               "to several requests"),
        default=None)
예제 #12
0
 def get_parser(self, prog_name):
     parser = super(cmd_base.ShowCommand, self).get_parser(prog_name)
     cmd_base.add_show_list_common_argument(parser)
     parser.add_argument('id',
                         metavar='EXT-ALIAS',
                         help=_('The extension alias'))
     return parser
예제 #13
0
def bool_from_string(subject, strict=False):
    """Interpret a string as a boolean.

    A case-insensitive match is performed such that strings matching 't',
    'true', 'on', 'y', 'yes', or '1' are considered True and, when
    `strict=False`, anything else is considered False.

    Useful for JSON-decoded stuff and config file parsing.

    If `strict=True`, unrecognized values, including None, will raise a
    ValueError which is useful when parsing values passed in from an API call.
    Strings yielding False are 'f', 'false', 'off', 'n', 'no', or '0'.
    """
    if not isinstance(subject, six.string_types):
        subject = str(subject)

    lowered = subject.strip().lower()

    if lowered in TRUE_STRINGS:
        return True
    elif lowered in FALSE_STRINGS:
        return False
    elif strict:
        acceptable = ', '.join(
            "'%s'" % s for s in sorted(TRUE_STRINGS + FALSE_STRINGS))
        msg = _("Unrecognized value '%(val)s', acceptable values are:"
                " %(acceptable)s") % {'val': subject,
                                      'acceptable': acceptable}
        raise ValueError(msg)
    else:
        return False
예제 #14
0
def safe_encode(text, incoming=None,
                encoding='utf-8', errors='strict'):
    """Encodes incoming str/unicode using `encoding`.

    If incoming is not specified, text is expected to be encoded with
    current python's default encoding. (`sys.getdefaultencoding`)

    :param incoming: Text's current encoding
    :param encoding: Expected encoding for text (Default UTF-8)
    :param errors: Errors handling policy. See here for valid
        values http://docs.python.org/2/library/codecs.html
    :returns: text or a bytestring `encoding` encoded
                representation of it.
    :raises TypeError: If text is not an isntance of str
    """
    if not isinstance(text, six.string_types):
        raise TypeError(_("%s can't be encoded") % type(text).capitalize())

    if not incoming:
        incoming = (sys.stdin.encoding or
                    sys.getdefaultencoding())

    if isinstance(text, six.text_type):
        return text.encode(encoding, errors)
    elif text and encoding != incoming:
        # Decode text before encoding it with `encoding`
        text = safe_decode(text, incoming, errors)
        return text.encode(encoding, errors)

    return text
예제 #15
0
 def get_parser(self, prog_name):
     parser = super(UpdateCommand, self).get_parser(prog_name)
     parser.add_argument(
         'id', metavar=self.resource.upper(),
         help=_('ID or name of %s to update') % self.resource)
     self.add_known_arguments(parser)
     return parser
예제 #16
0
def bool_from_string(subject, strict=False):
    """Interpret a string as a boolean.

    A case-insensitive match is performed such that strings matching 't',
    'true', 'on', 'y', 'yes', or '1' are considered True and, when
    `strict=False`, anything else is considered False.

    Useful for JSON-decoded stuff and config file parsing.

    If `strict=True`, unrecognized values, including None, will raise a
    ValueError which is useful when parsing values passed in from an API call.
    Strings yielding False are 'f', 'false', 'off', 'n', 'no', or '0'.
    """
    if not isinstance(subject, six.string_types):
        subject = str(subject)

    lowered = subject.strip().lower()

    if lowered in TRUE_STRINGS:
        return True
    elif lowered in FALSE_STRINGS:
        return False
    elif strict:
        acceptable = ', '.join("'%s'" % s
                               for s in sorted(TRUE_STRINGS + FALSE_STRINGS))
        msg = _("Unrecognized value '%(val)s', acceptable values are:"
                " %(acceptable)s") % {
                    'val': subject,
                    'acceptable': acceptable
                }
        raise ValueError(msg)
    else:
        return False
예제 #17
0
 def get_parser(self, prog_name):
     parser = super(cmd_base.ShowCommand, self).get_parser(prog_name)
     cmd_base.add_show_list_common_argument(parser)
     parser.add_argument(
         'id', metavar='EXT-ALIAS',
         help=_('The extension alias'))
     return parser
예제 #18
0
def make_client(instance):
    """Returns an tacker client.
    """
    tacker_client = utils.get_client_class(
        API_NAME,
        instance._api_version[API_NAME],
        API_VERSIONS,
    )
    instance.initialize()
    url = instance._url
    url = url.rstrip("/")
    if '1.0' == instance._api_version[API_NAME]:
        client = tacker_client(username=instance._username,
                               tenant_name=instance._tenant_name,
                               password=instance._password,
                               region_name=instance._region_name,
                               auth_url=instance._auth_url,
                               endpoint_url=url,
                               endpoint_type=instance._endpoint_type,
                               token=instance._token,
                               auth_strategy=instance._auth_strategy,
                               insecure=instance._insecure,
                               ca_cert=instance._ca_cert,
                               retries=instance._retries,
                               raise_errors=instance._raise_errors,
                               session=instance._session,
                               auth=instance._auth)
        return client
    else:
        raise exceptions.UnsupportedVersion(_("API version %s is not "
                                              "supported") %
                                            instance._api_version[API_NAME])
예제 #19
0
def safe_encode(text, incoming=None, encoding='utf-8', errors='strict'):
    """Encodes incoming str/unicode using `encoding`.

    If incoming is not specified, text is expected to be encoded with
    current python's default encoding. (`sys.getdefaultencoding`)

    :param incoming: Text's current encoding
    :param encoding: Expected encoding for text (Default UTF-8)
    :param errors: Errors handling policy. See here for valid
        values http://docs.python.org/2/library/codecs.html
    :returns: text or a bytestring `encoding` encoded
                representation of it.
    :raises TypeError: If text is not an isntance of str
    """
    if not isinstance(text, six.string_types):
        raise TypeError(_("%s can't be encoded") % type(text).capitalize())

    if not incoming:
        incoming = (sys.stdin.encoding or sys.getdefaultencoding())

    if isinstance(text, six.text_type):
        return text.encode(encoding, errors)
    elif text and encoding != incoming:
        # Decode text before encoding it with `encoding`
        text = safe_decode(text, incoming, errors)
        return text.encode(encoding, errors)

    return text
예제 #20
0
 def _from_xml(self, datastring):
     if datastring is None:
         return None
     plurals = set(self.metadata.get('plurals', {}))
     try:
         node = etree.fromstring(datastring)
         root_tag = self._get_key(node.tag)
         links = self._get_links(root_tag, node)
         result = self._from_xml_node(node, plurals)
         # There is no case where root_tag = constants.VIRTUAL_ROOT_KEY
         # and links is not None because of the way data are serialized
         if root_tag == constants.VIRTUAL_ROOT_KEY:
             return result
         return dict({root_tag: result}, **links)
     except Exception as e:
         parseError = False
         # Python2.7
         if (hasattr(etree, 'ParseError') and
             isinstance(e, getattr(etree, 'ParseError'))):
             parseError = True
         # Python2.6
         elif isinstance(e, expat.ExpatError):
             parseError = True
         if parseError:
             msg = _("Cannot understand XML")
             raise exception.MalformedResponseBody(reason=msg)
         else:
             raise
예제 #21
0
def make_client(instance):
    """Returns an tacker client.
    """
    tacker_client = utils.get_client_class(
        API_NAME,
        instance._api_version[API_NAME],
        API_VERSIONS,
    )
    instance.initialize()
    url = instance._url
    url = url.rstrip("/")
    if '1.0' == instance._api_version[API_NAME]:
        client = tacker_client(username=instance._username,
                               tenant_name=instance._tenant_name,
                               password=instance._password,
                               region_name=instance._region_name,
                               auth_url=instance._auth_url,
                               endpoint_url=url,
                               endpoint_type=instance._endpoint_type,
                               token=instance._token,
                               auth_strategy=instance._auth_strategy,
                               insecure=instance._insecure,
                               ca_cert=instance._ca_cert,
                               retries=instance._retries,
                               raise_errors=instance._raise_errors,
                               session=instance._session,
                               auth=instance._auth)
        return client
    else:
        raise exceptions.UnsupportedVersion(
            _("API version %s is not "
              "supported") % instance._api_version[API_NAME])
예제 #22
0
 def authenticate(self):
     if self.auth_strategy == 'keystone':
         self._authenticate_keystone()
     elif self.auth_strategy == 'noauth':
         self._authenticate_noauth()
     else:
         err_msg = _('Unknown auth strategy: %s') % self.auth_strategy
         raise exceptions.Unauthorized(message=err_msg)
예제 #23
0
 def get_parser(self, prog_name):
     parser = super(CreateCommand, self).get_parser(prog_name)
     parser.add_argument(
         '--tenant-id',
         metavar='TENANT_ID',
         help=_('The owner tenant ID'),
     )
     parser.add_argument('--tenant_id', help=argparse.SUPPRESS)
     self.add_known_arguments(parser)
     return parser
예제 #24
0
def validate_ip_subnet(parsed_args, attr_name):
    val = getattr(parsed_args, attr_name)
    if not val:
        return
    try:
        netaddr.IPNetwork(val)
    except (netaddr.AddrFormatError, ValueError):
        raise exceptions.CommandError(
            (_('%(attr_name)s "%(val)s" is not a valid CIDR.') %
             {'attr_name': attr_name.replace('_', '-'), 'val': val}))
def import_class(import_str):
    """Returns a class from a string including module and class."""
    mod_str, _sep, class_str = import_str.rpartition('.')
    try:
        __import__(mod_str)
        return getattr(sys.modules[mod_str], class_str)
    except (ValueError, AttributeError):
        raise ImportError(_('Class %s cannot be found (%s)') %
                          (class_str,
                           traceback.format_exception(*sys.exc_info())))
예제 #26
0
def add_sorting_argument(parser):
    parser.add_argument(
        '--sort-key',
        dest='sort_key', metavar='FIELD',
        action='append',
        help=_("Sorts the list by the specified fields in the specified "
               "directions. You can repeat this option, but you must "
               "specify an equal number of sort_dir and sort_key values. "
               "Extra sort_dir options are ignored. Missing sort_dir options "
               "use the default asc value."),
        default=[])
    parser.add_argument(
        '--sort-dir',
        dest='sort_dir', metavar='{asc,desc}',
        help=_("Sorts the list in the specified direction. You can repeat "
               "this option."),
        action='append',
        default=[],
        choices=['asc', 'desc'])
예제 #27
0
 def get_parser(self, prog_name):
     parser = super(CreateCommand, self).get_parser(prog_name)
     parser.add_argument(
         '--tenant-id', metavar='TENANT_ID',
         help=_('The owner tenant ID'), )
     parser.add_argument(
         '--tenant_id',
         help=argparse.SUPPRESS)
     self.add_known_arguments(parser)
     return parser
예제 #28
0
def import_class(import_str):
    """Returns a class from a string including module and class."""
    mod_str, _sep, class_str = import_str.rpartition('.')
    try:
        __import__(mod_str)
        return getattr(sys.modules[mod_str], class_str)
    except (ValueError, AttributeError):
        raise ImportError(
            _('Class %s cannot be found (%s)') %
            (class_str, traceback.format_exception(*sys.exc_info())))
예제 #29
0
    def get_parser(self, prog_name):
        parser = super(TackerCommand, self).get_parser(prog_name)
        parser.add_argument(
            '--request-format',
            help=_('The xml or json request format'),
            default='json',
            choices=['json', 'xml', ], )
        parser.add_argument(
            '--request_format',
            choices=['json', 'xml', ],
            help=argparse.SUPPRESS)

        return parser
예제 #30
0
    def args2body(self, parsed_args):
        body = {
            self.resource: {
                'service_type_id': parsed_args.service_type_id,
                'service_table_id': parsed_args.service_table_id,
                'devices': [parsed_args.device],
            }
        }
        if parsed_args.name is not None:
            body[self.resource]['name'] = parsed_args.name
        if parsed_args.mgmt_driver is not None:
            body[self.resource]['mgmt_driver'] = parsed_args.mgmt_driver
        if parsed_args.kwargs:
            try:
                kwargs = dict(key_value.split('=', 1)
                              for key_value in parsed_args.kwargs)
            except ValueError:
                msg = (_('invalid argument for --kwargs %s') %
                       parsed_args.kwargs)
                raise exceptions.TackerCLIError(msg)
            if kwargs:
                body[self.resource]['kwargs'] = kwargs
        if parsed_args.service_context:
            try:
                service_context = [dict(
                    (k.replace('-', '_'), v)
                    for k, v in (key_value.split('=', 1)
                                 for key_value in entry_string.split(',')))
                    for entry_string in parsed_args.service_context]
            except ValueError:
                msg = (_('invalid argument for --service-context %s') %
                       parsed_args.service_context)
                raise exceptions.TackerCLIError(msg)

            if service_context:
                body[self.resource]['service_context'] = service_context

        tackerV10.update_dict(parsed_args, body[self.resource], ['tenant_id'])
        return body
예제 #31
0
def add_show_list_common_argument(parser):
    parser.add_argument(
        '-D', '--show-details',
        help=_('Show detailed info'),
        action='store_true',
        default=False, )
    parser.add_argument(
        '--show_details',
        action='store_true',
        help=argparse.SUPPRESS)
    parser.add_argument(
        '--fields',
        help=argparse.SUPPRESS,
        action='append',
        default=[])
    parser.add_argument(
        '-F', '--field',
        dest='fields', metavar='FIELD',
        help=_('Specify the field(s) to be returned by server. You can '
               'repeat this option.'),
        action='append',
        default=[])
예제 #32
0
 def args2body(self, parsed_args):
     body = {self.resource: {}}
     if parsed_args.attributes:
         try:
             attributes = dict(key_value.split('=', 1)
                               for key_value in parsed_args.attributes)
         except ValueError:
             msg = (_('invalid argument for --attributes %s') %
                    parsed_args.attributes)
             raise exceptions.TackerCLIError(msg)
         if attributes:
             body[self.resource]['attributes'] = attributes
     tackerV10.update_dict(parsed_args, body[self.resource], ['tenant_id'])
     return body
예제 #33
0
def validate_int_range(parsed_args, attr_name, min_value=None, max_value=None):
    val = getattr(parsed_args, attr_name, None)
    if val is None:
        return
    try:
        if not isinstance(val, int):
            int_val = int(val, 0)
        else:
            int_val = val
        if ((min_value is None or min_value <= int_val) and
            (max_value is None or int_val <= max_value)):
            return
    except (ValueError, TypeError):
        pass

    if min_value is not None and max_value is not None:
        msg = (_('%(attr_name)s "%(val)s" should be an integer '
                 '[%(min)i:%(max)i].') %
               {'attr_name': attr_name.replace('_', '-'),
                'val': val, 'min': min_value, 'max': max_value})
    elif min_value is not None:
        msg = (_('%(attr_name)s "%(val)s" should be an integer '
                 'greater than or equal to %(min)i.') %
               {'attr_name': attr_name.replace('_', '-'),
                'val': val, 'min': min_value})
    elif max_value is not None:
        msg = (_('%(attr_name)s "%(val)s" should be an integer '
                 'smaller than or equal to %(max)i.') %
               {'attr_name': attr_name.replace('_', '-'),
                'val': val, 'max': max_value})
    else:
        msg = (_('%(attr_name)s "%(val)s" should be an integer.') %
               {'attr_name': attr_name.replace('_', '-'),
                'val': val})

    raise exceptions.CommandError(msg)
예제 #34
0
 def args2body(self, parsed_args):
     body = {self.resource: {}}
     if parsed_args.kwargs:
         try:
             kwargs = dict(
                 key_value.split('=', 1)
                 for key_value in parsed_args.kwargs)
         except ValueError:
             msg = (_('invalid argument for --kwargs %s') %
                    parsed_args.kwargs)
             raise exceptions.TackerCLIError(msg)
         if kwargs:
             body[self.resource]['kwargs'] = kwargs
     tackerV10.update_dict(parsed_args, body[self.resource], ['tenant_id'])
     return body
예제 #35
0
def find_resourceid_by_id(client, resource, resource_id):
    resource_plural = _get_resource_plural(resource, client)
    obj_lister = getattr(client, "list_%s" % resource_plural)
    # perform search by id only if we are passing a valid UUID
    match = re.match(UUID_PATTERN, resource_id)
    collection = resource_plural
    if match:
        data = obj_lister(id=resource_id, fields='id')
        if data and data[collection]:
            return data[collection][0]['id']
    not_found_message = (_("Unable to find %(resource)s with id "
                           "'%(id)s'") %
                         {'resource': resource, 'id': resource_id})
    # 404 is used to simulate server side behavior
    raise exceptions.TackerClientException(
        message=not_found_message, status_code=404)
예제 #36
0
 def __call__(self, parser, namespace, values, option_string=None):
     outputs = []
     max_len = 0
     app = self.default
     parser.print_help(app.stdout)
     app.stdout.write(_('\nCommands for API v%s:\n') % app.api_version)
     command_manager = app.command_manager
     for name, ep in sorted(command_manager):
         factory = ep.load()
         cmd = factory(self, None)
         one_liner = cmd.get_description().split('\n')[0]
         outputs.append((name, one_liner))
         max_len = max(len(name), max_len)
     for (name, one_liner) in outputs:
         app.stdout.write('  %s  %s\n' % (name.ljust(max_len), one_liner))
     sys.exit(0)
예제 #37
0
 def run(self, parsed_args):
     self.log.debug('run(%s)', parsed_args)
     tacker_client = self.get_client()
     tacker_client.format = parsed_args.request_format
     obj_deleter = getattr(tacker_client, "delete_%s" % self.resource)
     if self.allow_names:
         _id = find_resourceid_by_name_or_id(tacker_client, self.resource,
                                             parsed_args.id)
     else:
         _id = parsed_args.id
     obj_deleter(_id)
     print((_('Deleted %(resource)s: %(id)s') % {
         'id': parsed_args.id,
         'resource': self.resource
     }),
           file=self.app.stdout)
     return
예제 #38
0
 def run(self, parsed_args):
     self.log.debug('run(%s)', parsed_args)
     tacker_client = self.get_client()
     tacker_client.format = parsed_args.request_format
     obj_deleter = getattr(tacker_client,
                           "delete_%s" % self.resource)
     if self.allow_names:
         _id = find_resourceid_by_name_or_id(tacker_client, self.resource,
                                             parsed_args.id)
     else:
         _id = parsed_args.id
     obj_deleter(_id)
     print((_('Deleted %(resource)s: %(id)s')
            % {'id': parsed_args.id,
               'resource': self.resource}),
           file=self.app.stdout)
     return
예제 #39
0
def _find_resourceid_by_name(client, resource, name):
    resource_plural = _get_resource_plural(resource, client)
    obj_lister = getattr(client, "list_%s" % resource_plural)
    data = obj_lister(name=name, fields='id')
    collection = resource_plural
    info = data[collection]
    if len(info) > 1:
        raise exceptions.TackerClientNoUniqueMatch(resource=resource,
                                                   name=name)
    elif len(info) == 0:
        not_found_message = (_("Unable to find %(resource)s with name "
                               "'%(name)s'") %
                             {'resource': resource, 'name': name})
        # 404 is used to simulate server side behavior
        raise exceptions.TackerClientException(
            message=not_found_message, status_code=404)
    else:
        return info[0]['id']
예제 #40
0
def _process_previous_argument(current_arg, _value_number, current_type_str,
                               _list_flag, _values_specs, _clear_flag,
                               values_specs):
    if current_arg is not None:
        if _value_number == 0 and (current_type_str or _list_flag):
                # This kind of argument should have value
                raise exceptions.CommandError(
                    _("Invalid values_specs %s") % ' '.join(values_specs))
        if _value_number > 1 or _list_flag or current_type_str == 'list':
            current_arg.update({'nargs': '+'})
        elif _value_number == 0:
            if _clear_flag:
                # if we have action=clear, we use argument's default
                # value None for argument
                _values_specs.pop()
            else:
                # We assume non value argument as bool one
                current_arg.update({'action': 'store_true'})
예제 #41
0
 def get_data(self, parsed_args):
     self.log.debug('get_data(%s)' % parsed_args)
     tacker_client = self.get_client()
     tacker_client.format = parsed_args.request_format
     _extra_values = parse_args_to_dict(self.values_specs)
     _merge_args(self, parsed_args, _extra_values, self.values_specs)
     body = self.args2body(parsed_args)
     body[self.resource].update(_extra_values)
     obj_creator = getattr(tacker_client, "create_%s" % self.resource)
     data = obj_creator(body)
     self.format_output_data(data)
     # {u'network': {u'id': u'e9424a76-6db4-4c93-97b6-ec311cd51f19'}}
     info = self.resource in data and data[self.resource] or None
     if info:
         print(_('Created a new %s:') % self.resource, file=self.app.stdout)
     else:
         info = {'': ''}
     return zip(*sorted(info.iteritems()))
예제 #42
0
def _process_previous_argument(current_arg, _value_number, current_type_str,
                               _list_flag, _values_specs, _clear_flag,
                               values_specs):
    if current_arg is not None:
        if _value_number == 0 and (current_type_str or _list_flag):
            # This kind of argument should have value
            raise exceptions.CommandError(
                _("Invalid values_specs %s") % ' '.join(values_specs))
        if _value_number > 1 or _list_flag or current_type_str == 'list':
            current_arg.update({'nargs': '+'})
        elif _value_number == 0:
            if _clear_flag:
                # if we have action=clear, we use argument's default
                # value None for argument
                _values_specs.pop()
            else:
                # We assume non value argument as bool one
                current_arg.update({'action': 'store_true'})
예제 #43
0
 def get_data(self, parsed_args):
     self.log.debug('get_data(%s)' % parsed_args)
     tacker_client = self.get_client()
     tacker_client.format = parsed_args.request_format
     _extra_values = parse_args_to_dict(self.values_specs)
     _merge_args(self, parsed_args, _extra_values,
                 self.values_specs)
     body = self.args2body(parsed_args)
     body[self.resource].update(_extra_values)
     obj_creator = getattr(tacker_client,
                           "create_%s" % self.resource)
     data = obj_creator(body)
     self.format_output_data(data)
     # {u'network': {u'id': u'e9424a76-6db4-4c93-97b6-ec311cd51f19'}}
     info = self.resource in data and data[self.resource] or None
     if info:
         print(_('Created a new %s:') % self.resource,
               file=self.app.stdout)
         for f in self.remove_output_fields:
             if f in info:
                 info.pop(f)
     else:
         info = {'': ''}
     return zip(*sorted(info.iteritems()))
예제 #44
0
 def get_parser(self, prog_name):
     parser = super(_XtachInterface, self).get_parser(prog_name)
     parser.add_argument('port_id', metavar='PORT',
                         help=_('port to attach/detach'))
     self.add_known_arguments(parser)
     return parser
예제 #45
0
def parse_args_to_dict(values_specs):
    '''It is used to analyze the extra command options to command.

    Besides known options and arguments, our commands also support user to
    put more options to the end of command line. For example,
    list_nets -- --tag x y --key1 value1, where '-- --tag x y --key1 value1'
    is extra options to our list_nets. This feature can support V1.0 API's
    fields selection and filters. For example, to list networks which has name
    'test4', we can have list_nets -- --name=test4.

    value spec is: --key type=int|bool|... value. Type is one of Python
    built-in types. By default, type is string. The key without value is
    a bool option. Key with two values will be a list option.

    '''

    # values_specs for example: '-- --tag x y --key1 type=int value1'
    # -- is a pseudo argument
    values_specs_copy = values_specs[:]
    if values_specs_copy and values_specs_copy[0] == '--':
        del values_specs_copy[0]
    # converted ArgumentParser arguments for each of the options
    _options = {}
    # the argument part for current option in _options
    current_arg = None
    # the string after remove meta info in values_specs
    # for example, '--tag x y --key1 value1'
    _values_specs = []
    # record the count of values for an option
    # for example: for '--tag x y', it is 2, while for '--key1 value1', it is 1
    _value_number = 0
    # list=true
    _list_flag = False
    # action=clear
    _clear_flag = False
    # the current item in values_specs
    current_item = None
    # the str after 'type='
    current_type_str = None
    for _item in values_specs_copy:
        if _item.startswith('--'):
            # Deal with previous argument if any
            _process_previous_argument(
                current_arg, _value_number, current_type_str,
                _list_flag, _values_specs, _clear_flag, values_specs)

            # Init variables for current argument
            current_item = _item
            _list_flag = False
            _clear_flag = False
            current_type_str = None
            if "=" in _item:
                _value_number = 1
                _item = _item.split('=')[0]
            else:
                _value_number = 0
            if _item in _options:
                raise exceptions.CommandError(
                    _("Duplicated options %s") % ' '.join(values_specs))
            else:
                _options.update({_item: {}})
            current_arg = _options[_item]
            _item = current_item
        elif _item.startswith('type='):
            if current_arg is None:
                raise exceptions.CommandError(
                    _("Invalid values_specs %s") % ' '.join(values_specs))
            if 'type' not in current_arg:
                current_type_str = _item.split('=', 2)[1]
                current_arg.update({'type': eval(current_type_str)})
                if current_type_str == 'bool':
                    current_arg.update({'type': utils.str2bool})
                elif current_type_str == 'dict':
                    current_arg.update({'type': utils.str2dict})
                continue
        elif _item == 'list=true':
            _list_flag = True
            continue
        elif _item == 'action=clear':
            _clear_flag = True
            continue

        if not _item.startswith('--'):
            # All others are value items
            # Make sure '--' occurs first and allow minus value
            if (not current_item or '=' in current_item or
                _item.startswith('-') and not is_number(_item)):
                raise exceptions.CommandError(
                    _("Invalid values_specs %s") % ' '.join(values_specs))
            _value_number += 1

        _values_specs.append(_item)

    # Deal with last one argument
    _process_previous_argument(
        current_arg, _value_number, current_type_str,
        _list_flag, _values_specs, _clear_flag, values_specs)

    # populate the parser with arguments
    _parser = argparse.ArgumentParser(add_help=False)
    for opt, optspec in _options.iteritems():
        _parser.add_argument(opt, **optspec)
    _args = _parser.parse_args(_values_specs)

    result_dict = {}
    for opt in _options.iterkeys():
        _opt = opt.split('--', 2)[1]
        _opt = _opt.replace('-', '_')
        _value = getattr(_args, _opt)
        result_dict.update({_opt: _value})
    return result_dict
예제 #46
0
 def _from_json(self, datastring):
     try:
         return jsonutils.loads(datastring)
     except ValueError:
         msg = _("Cannot understand JSON")
         raise exception.MalformedResponseBody(reason=msg)
예제 #47
0
def parse_args_to_dict(values_specs):
    '''It is used to analyze the extra command options to command.

    Besides known options and arguments, our commands also support user to
    put more options to the end of command line. For example,
    list_nets -- --tag x y --key1 value1, where '-- --tag x y --key1 value1'
    is extra options to our list_nets. This feature can support V1.0 API's
    fields selection and filters. For example, to list networks which has name
    'test4', we can have list_nets -- --name=test4.

    value spec is: --key type=int|bool|... value. Type is one of Python
    built-in types. By default, type is string. The key without value is
    a bool option. Key with two values will be a list option.

    '''

    # values_specs for example: '-- --tag x y --key1 type=int value1'
    # -- is a pseudo argument
    values_specs_copy = values_specs[:]
    if values_specs_copy and values_specs_copy[0] == '--':
        del values_specs_copy[0]
    # converted ArgumentParser arguments for each of the options
    _options = {}
    # the argument part for current option in _options
    current_arg = None
    # the string after remove meta info in values_specs
    # for example, '--tag x y --key1 value1'
    _values_specs = []
    # record the count of values for an option
    # for example: for '--tag x y', it is 2, while for '--key1 value1', it is 1
    _value_number = 0
    # list=true
    _list_flag = False
    # action=clear
    _clear_flag = False
    # the current item in values_specs
    current_item = None
    # the str after 'type='
    current_type_str = None
    for _item in values_specs_copy:
        if _item.startswith('--'):
            # Deal with previous argument if any
            _process_previous_argument(current_arg, _value_number,
                                       current_type_str, _list_flag,
                                       _values_specs, _clear_flag,
                                       values_specs)

            # Init variables for current argument
            current_item = _item
            _list_flag = False
            _clear_flag = False
            current_type_str = None
            if "=" in _item:
                _value_number = 1
                _item = _item.split('=')[0]
            else:
                _value_number = 0
            if _item in _options:
                raise exceptions.CommandError(
                    _("Duplicated options %s") % ' '.join(values_specs))
            else:
                _options.update({_item: {}})
            current_arg = _options[_item]
            _item = current_item
        elif _item.startswith('type='):
            if current_arg is None:
                raise exceptions.CommandError(
                    _("Invalid values_specs %s") % ' '.join(values_specs))
            if 'type' not in current_arg:
                current_type_str = _item.split('=', 2)[1]
                current_arg.update({'type': eval(current_type_str)})
                if current_type_str == 'bool':
                    current_arg.update({'type': utils.str2bool})
                elif current_type_str == 'dict':
                    current_arg.update({'type': utils.str2dict})
                continue
        elif _item == 'list=true':
            _list_flag = True
            continue
        elif _item == 'action=clear':
            _clear_flag = True
            continue

        if not _item.startswith('--'):
            # All others are value items
            # Make sure '--' occurs first and allow minus value
            if (not current_item or '=' in current_item
                    or _item.startswith('-') and not is_number(_item)):
                raise exceptions.CommandError(
                    _("Invalid values_specs %s") % ' '.join(values_specs))
            _value_number += 1

        _values_specs.append(_item)

    # Deal with last one argument
    _process_previous_argument(current_arg, _value_number, current_type_str,
                               _list_flag, _values_specs, _clear_flag,
                               values_specs)

    # populate the parser with arguments
    _parser = argparse.ArgumentParser(add_help=False)
    for opt, optspec in _options.iteritems():
        _parser.add_argument(opt, **optspec)
    _args = _parser.parse_args(_values_specs)

    result_dict = {}
    for opt in _options.iterkeys():
        _opt = opt.split('--', 2)[1]
        _opt = _opt.replace('-', '_')
        _value = getattr(_args, _opt)
        result_dict.update({_opt: _value})
    return result_dict