def format_args(args, parse_comma=True):
    '''Reformat a list of key-value arguments into a dict.

    Convert arguments into format expected by the API.
    '''
    if not args:
        return {}

    if parse_comma:
        # expect multiple invocations of --label (or other arguments) but fall
        # back to either , or ; delimited if only one --label is specified
        if len(args) == 1:
            args = args[0].replace(';', ',').split(',')

    fmt_args = {}
    for arg in args:
        try:
            (k, v) = arg.split(('='), 1)
        except ValueError:
            raise exc.CommandError(
                _('arguments must be a list of KEY=VALUE '
                  'not %s') % arg)
        if k not in fmt_args:
            fmt_args[k] = v
        else:
            if not isinstance(fmt_args[k], list):
                fmt_args[k] = [fmt_args[k]]
            fmt_args[k].append(v)

    return fmt_args
Exemple #2
0
def do_update(cs, args):
    """Update one or more attributes of the container."""
    opts = {}
    opts['memory'] = args.memory
    opts['cpu'] = args.cpu
    opts = zun_utils.remove_null_parms(**opts)
    if not opts:
        raise exc.CommandError("You must update at least one property")
    container = cs.containers.update(args.container, **opts)
    _show_container(container)
Exemple #3
0
 def do_help(self, args):
     """Display help about this program or one of its subcommands."""
     # NOTE(jamespage): args.command is not guaranteed with python >= 3.4
     command = getattr(args, 'command', '')
     if command:
         if args.command in self.subcommands:
             self.subcommands[args.command].print_help()
         else:
             raise exc.CommandError("'%s' is not a valid subcommand" %
                                    args.command)
     else:
         self.parser.print_help()
 def take_action(self, parsed_args):
     client = _get_client(self, parsed_args)
     container = parsed_args.container
     opts = {}
     opts['memory'] = parsed_args.memory
     opts['cpu'] = parsed_args.cpu
     opts = zun_utils.remove_null_parms(**opts)
     if not opts:
         raise exc.CommandError("You must update at least one property")
     container = client.containers.update(container, **opts)
     columns = _container_columns(container)
     return columns, utils.get_item_properties(container, columns)
def do_registry_update(cs, args):
    """Update one or more attributes of the registry."""
    opts = {}
    opts['username'] = args.username
    opts['password'] = args.password
    opts['domain'] = args.domain
    opts['name'] = args.name
    opts = zun_utils.remove_null_parms(**opts)
    if not opts:
        raise exc.CommandError("You must update at least one property")
    registry = cs.registries.update(args.registry, **opts)
    _show_registry(registry)
 def take_action(self, parsed_args):
     client = _get_client(self, parsed_args)
     registry = parsed_args.registry
     opts = {}
     opts['username'] = parsed_args.username
     opts['password'] = parsed_args.password
     opts['domain'] = parsed_args.domain
     opts['name'] = parsed_args.name
     opts = zun_utils.remove_null_parms(**opts)
     if not opts:
         raise exc.CommandError("You must update at least one property")
     registry = client.registries.update(registry, **opts)
     return zip(*sorted(registry._info['registry'].items()))
Exemple #7
0
def do_update(cs, args):
    """Update one or more attributes of the container."""
    opts = {}
    opts['memory'] = args.memory
    opts['cpu'] = args.cpu
    opts['name'] = args.name
    if 'auto_heal' in args and args.auto_heal:
        opts['auto_heal'] = True
    if 'no_auto_heal' in args and args.no_auto_heal:
        opts['auto_heal'] = False
    opts = zun_utils.remove_null_parms(**opts)
    if not opts:
        raise exc.CommandError("You must update at least one property")
    container = cs.containers.update(args.container, **opts)
    _show_container(container)
Exemple #8
0
def args_array_to_patch(op, attributes):
    patch = []
    for attr in attributes:
        # Sanitize
        if not attr.startswith('/'):
            attr = '/' + attr
        if op in ['add', 'replace']:
            path, value = split_and_deserialize(attr)
            patch.append({'op': op, 'path': path, 'value': value})

        elif op == "remove":
            # For remove only the key is needed
            patch.append({'op': op, 'path': attr})
        else:
            raise exc.CommandError(_('Unknown PATCH operation: %s') % op)
    return patch
Exemple #9
0
def split_and_deserialize(string):
    """Split and try to JSON deserialize a string.

    Gets a string with the KEY=VALUE format, split it (using '=' as the
    separator) and try to JSON deserialize the VALUE.
    :returns: A tuple of (key, value).
    """
    try:
        key, value = string.split("=", 1)
    except ValueError:
        raise exc.CommandError(_('Attributes must be a list of '
                                 'PATH=VALUE not "%s"') % string)
    try:
        value = json.loads(value)
    except ValueError:
        pass

    return (key, value)
Exemple #10
0
def decode_file_data(data):
    # Py3 raises binascii.Error instead of TypeError as in Py27
    try:
        return base64.b64decode(data)
    except (TypeError, binascii.Error):
        raise exc.CommandError(_('Invalid Base 64 file data.'))
Exemple #11
0
    def main(self, argv):

        # NOTE(Christoph Jansen): With Python 3.4 argv somehow becomes a Map.
        #                         This hack fixes it.
        argv = list(argv)

        # Parse args once to find version and debug settings
        parser = self.get_base_parser()
        (options, args) = parser.parse_known_args(argv)
        self.setup_debugging(options.debug)

        api_version = api_versions.get_api_version(options.zun_api_version)

        # NOTE(dtroyer): Hackery to handle --endpoint_type due to argparse
        #                thinking usage-list --end is ambiguous; but it
        #                works fine with only --endpoint-type present
        #                Go figure.
        if '--endpoint_type' in argv:
            spot = argv.index('--endpoint_type')
            argv[spot] = '--endpoint-type'

        do_help = "help" in args
        subcommand_parser = self.get_subcommand_parser(
            api_version, do_help=do_help)

        self.parser = subcommand_parser

        if options.help or not argv:
            subcommand_parser.print_help()
            return 0

        args = subcommand_parser.parse_args(argv)

        # Short-circuit and deal with help right away.
        # NOTE(jamespage): args.func is not guaranteed with python >= 3.4
        if not hasattr(args, 'func') or args.func == self.do_help:
            self.do_help(args)
            return 0
        elif args.func == self.do_bash_completion:
            self.do_bash_completion(args)
            return 0

        (os_username, os_project_name, os_project_id,
         os_user_domain_id, os_user_domain_name,
         os_project_domain_id, os_project_domain_name,
         os_auth_url, os_auth_system, endpoint_type,
         service_type, bypass_url, insecure, os_cacert) = (
            (args.os_username, args.os_project_name, args.os_project_id,
             args.os_user_domain_id, args.os_user_domain_name,
             args.os_project_domain_id, args.os_project_domain_name,
             args.os_auth_url, args.os_auth_system, args.endpoint_type,
             args.service_type, args.bypass_url, args.insecure,
             args.os_cacert)
        )

        if os_auth_system and os_auth_system != "keystone":
            auth_plugin = auth.load_plugin(os_auth_system)
        else:
            auth_plugin = None

        # Fetched and set later as needed
        os_password = None

        if not endpoint_type:
            endpoint_type = DEFAULT_ENDPOINT_TYPE

        if not service_type:
            service_type = DEFAULT_SERVICE_TYPE

# NA - there is only one service this CLI accesses
#            service_type = utils.get_service_type(args.func) or service_type

        # FIXME(usrleon): Here should be restrict for project id same as
        # for os_username or os_password but for compatibility it is not.
        if not cliutils.isunauthenticated(args.func):
            if auth_plugin:
                auth_plugin.parse_opts(args)

            if not auth_plugin or not auth_plugin.opts:
                if not os_username:
                    raise exc.CommandError("You must provide a username "
                                           "via either --os-username or "
                                           "env[OS_USERNAME]")

            if not os_project_name and not os_project_id:
                raise exc.CommandError("You must provide a project name "
                                       "or project id via --os-project-name, "
                                       "--os-project-id, env[OS_PROJECT_NAME] "
                                       "or env[OS_PROJECT_ID]")

            if not os_auth_url:
                if os_auth_system and os_auth_system != 'keystone':
                    os_auth_url = auth_plugin.get_auth_url()

            if not os_auth_url:
                raise exc.CommandError("You must provide an auth url "
                                       "via either --os-auth-url or "
                                       "env[OS_AUTH_URL] or specify an "
                                       "auth_system which defines a "
                                       "default url with --os-auth-system "
                                       "or env[OS_AUTH_SYSTEM]")

        # NOTE: The Zun client authenticates when you create it. So instead of
        #       creating here and authenticating later, which is what the
        #       novaclient does, we just create the client later.

        # Now check for the password/token of which pieces of the
        # identifying keyring key can come from the underlying client
        if not cliutils.isunauthenticated(args.func):
            # NA - Client can't be used with SecretsHelper
            if (auth_plugin and auth_plugin.opts and
                    "os_password" not in auth_plugin.opts):
                use_pw = False
            else:
                use_pw = True

            if use_pw:
                # Auth using token must have failed or not happened
                # at all, so now switch to password mode and save
                # the token when its gotten... using our keyring
                # saver
                os_password = args.os_password
                if not os_password:
                    raise exc.CommandError(
                        'Expecting a password provided via either '
                        '--os-password, env[OS_PASSWORD], or '
                        'prompted response')

        client = base_client

        if not do_help:
            if api_version.is_latest():
                # This client is just used to discover api version.
                # Version API needn't microversion, so we just pass
                # version 1.1 at here.
                self.cs = client.Client(
                    version=api_versions.APIVersion("1.1"),
                    username=os_username,
                    password=os_password,
                    project_id=os_project_id,
                    project_name=os_project_name,
                    user_domain_id=os_user_domain_id,
                    user_domain_name=os_user_domain_name,
                    project_domain_id=os_project_domain_id,
                    project_domain_name=os_project_domain_name,
                    auth_url=os_auth_url,
                    service_type=service_type,
                    region_name=args.os_region_name,
                    endpoint_override=bypass_url,
                    interface=endpoint_type,
                    insecure=insecure,
                    cacert=os_cacert)
                api_version = api_versions.discover_version(self.cs,
                                                            api_version)

            min_version = api_versions.APIVersion(api_versions.MIN_API_VERSION)
            max_version = api_versions.APIVersion(api_versions.MAX_API_VERSION)
            if not api_version.matches(min_version, max_version):
                raise exc.CommandError(
                    _("The specified version isn't supported by "
                      "client. The valid version range is '%(min)s' "
                      "to '%(max)s'") % {
                        "min": min_version.get_string(),
                        "max": max_version.get_string()}
                )

        kwargs = {}
        if profiler:
            kwargs["profile"] = args.profile

        self.cs = client.Client(version=api_version,
                                username=os_username,
                                password=os_password,
                                project_id=os_project_id,
                                project_name=os_project_name,
                                user_domain_id=os_user_domain_id,
                                user_domain_name=os_user_domain_name,
                                project_domain_id=os_project_domain_id,
                                project_domain_name=os_project_domain_name,
                                auth_url=os_auth_url,
                                service_type=service_type,
                                region_name=args.os_region_name,
                                endpoint_override=bypass_url,
                                interface=endpoint_type,
                                insecure=insecure,
                                cacert=os_cacert,
                                **kwargs)

        args.func(self.cs, args)

        if profiler and args.profile:
            trace_id = profiler.get().get_base_id()
            print("To display trace use the command:\n\n"
                  "  osprofiler trace show --html %s " % trace_id)
Exemple #12
0
    def main(self, argv):

        # NOTE(Christoph Jansen): With Python 3.4 argv somehow becomes a Map.
        #                         This hack fixes it.
        argv = list(argv)

        # Parse args once to find version and debug settings
        parser = self.get_base_parser()
        (options, args) = parser.parse_known_args(argv)
        self.setup_debugging(options.debug)

        # NOTE(dtroyer): Hackery to handle --endpoint_type due to argparse
        #                thinking usage-list --end is ambiguous; but it
        #                works fine with only --endpoint-type present
        #                Go figure.
        if '--endpoint_type' in argv:
            spot = argv.index('--endpoint_type')
            argv[spot] = '--endpoint-type'

        subcommand_parser = (self.get_subcommand_parser(
            options.zun_api_version))
        self.parser = subcommand_parser

        if options.help or not argv:
            subcommand_parser.print_help()
            return 0

        args = subcommand_parser.parse_args(argv)

        # Short-circuit and deal with help right away.
        # NOTE(jamespage): args.func is not guaranteed with python >= 3.4
        if not hasattr(args, 'func') or args.func == self.do_help:
            self.do_help(args)
            return 0
        elif args.func == self.do_bash_completion:
            self.do_bash_completion(args)
            return 0

        (os_username, os_project_name, os_project_id, os_user_domain_id,
         os_user_domain_name, os_project_domain_id, os_project_domain_name,
         os_auth_url, os_auth_system, endpoint_type, service_type, bypass_url,
         insecure) = ((args.os_username, args.os_project_name,
                       args.os_project_id, args.os_user_domain_id,
                       args.os_user_domain_name, args.os_project_domain_id,
                       args.os_project_domain_name, args.os_auth_url,
                       args.os_auth_system, args.endpoint_type,
                       args.service_type, args.bypass_url, args.insecure))

        if os_auth_system and os_auth_system != "keystone":
            auth_plugin = auth.load_plugin(os_auth_system)
        else:
            auth_plugin = None

        # Fetched and set later as needed
        os_password = None

        if not endpoint_type:
            endpoint_type = DEFAULT_ENDPOINT_TYPE

        if not service_type:
            service_type = DEFAULT_SERVICE_TYPE
# NA - there is only one service this CLI accesses
#            service_type = utils.get_service_type(args.func) or service_type

# FIXME(usrleon): Here should be restrict for project id same as
# for os_username or os_password but for compatibility it is not.
        if not cliutils.isunauthenticated(args.func):
            if auth_plugin:
                auth_plugin.parse_opts(args)

            if not auth_plugin or not auth_plugin.opts:
                if not os_username:
                    raise exc.CommandError("You must provide a username "
                                           "via either --os-username or "
                                           "env[OS_USERNAME]")

            if not os_project_name and not os_project_id:
                raise exc.CommandError("You must provide a project name "
                                       "or project id via --os-project-name, "
                                       "--os-project-id, env[OS_PROJECT_NAME] "
                                       "or env[OS_PROJECT_ID]")

            if not os_auth_url:
                if os_auth_system and os_auth_system != 'keystone':
                    os_auth_url = auth_plugin.get_auth_url()

            if not os_auth_url:
                raise exc.CommandError("You must provide an auth url "
                                       "via either --os-auth-url or "
                                       "env[OS_AUTH_URL] or specify an "
                                       "auth_system which defines a "
                                       "default url with --os-auth-system "
                                       "or env[OS_AUTH_SYSTEM]")

# NOTE: The Zun client authenticates when you create it. So instead of
#       creating here and authenticating later, which is what the novaclient
#       does, we just create the client later.

# Now check for the password/token of which pieces of the
# identifying keyring key can come from the underlying client
        if not cliutils.isunauthenticated(args.func):
            # NA - Client can't be used with SecretsHelper
            if (auth_plugin and auth_plugin.opts
                    and "os_password" not in auth_plugin.opts):
                use_pw = False
            else:
                use_pw = True

            if use_pw:
                # Auth using token must have failed or not happened
                # at all, so now switch to password mode and save
                # the token when its gotten... using our keyring
                # saver
                os_password = args.os_password
                if not os_password:
                    raise exc.CommandError(
                        'Expecting a password provided via either '
                        '--os-password, env[OS_PASSWORD], or '
                        'prompted response')

        try:
            client = {
                '1': client_v1,
            }[options.zun_api_version]
        except KeyError:
            client = client_v1

        self.cs = client.Client(username=os_username,
                                api_key=os_password,
                                project_id=os_project_id,
                                project_name=os_project_name,
                                user_domain_id=os_user_domain_id,
                                user_domain_name=os_user_domain_name,
                                project_domain_id=os_project_domain_id,
                                project_domain_name=os_project_domain_name,
                                auth_url=os_auth_url,
                                service_type=service_type,
                                region_name=args.os_region_name,
                                zun_url=bypass_url,
                                endpoint_type=endpoint_type,
                                insecure=insecure)

        args.func(self.cs, args)