def create(self, parent_group_id, ip_protocol=None, from_port=None,
               to_port=None, cidr=None, group_id=None):
        """
        Create a security group rule

        :param ip_protocol: IP protocol, one of 'tcp', 'udp' or 'icmp'
        :param from_port: Beginning of port range
        :param to_port: End of port range
        :param cidr: Destination IP address(es) in CIDR notation
        :param group_id: Security group id (int)
        :param parent_group_id: Parent security group id (int)
        """

        try:
            from_port = int(from_port)
        except (TypeError, ValueError):
            raise exceptions.CommandError(_("From port must be an integer."))
        try:
            to_port = int(to_port)
        except (TypeError, ValueError):
            raise exceptions.CommandError(_("To port must be an integer."))
        if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']:
            raise exceptions.CommandError(_("IP protocol must be 'tcp', 'udp'"
                                            ", or 'icmp'."))

        body = {"security_group_rule": {
            "ip_protocol": ip_protocol,
            "from_port": from_port,
            "to_port": to_port,
            "cidr": cidr,
            "group_id": group_id,
            "parent_group_id": parent_group_id}}

        return self._create('/os-security-group-rules', body,
                            'security_group_rule')
def discover_version(client, requested_version):
    """Checks ``requested_version`` and returns the most recent version
    supported by both the API and the client.

    :param client: client object
    :param requested_version: requested version represented by APIVersion obj
    :returns: APIVersion
    """

    server_start_version, server_end_version = _get_server_version_range(
        client)

    if (not requested_version.is_latest() and
            requested_version != APIVersion('2.0')):
        if server_start_version.is_null() and server_end_version.is_null():
            raise exceptions.UnsupportedVersion(
                _("Server doesn't support microversions"))
        if not requested_version.matches(server_start_version,
                                         server_end_version):
            raise exceptions.UnsupportedVersion(
                _("The specified version isn't supported by server. The valid "
                  "version range is '%(min)s' to '%(max)s'") % {
                    "min": server_start_version.get_string(),
                    "max": server_end_version.get_string()})
        return requested_version

    if requested_version == APIVersion('2.0'):
        if (server_start_version == APIVersion('2.1') or
                (server_start_version.is_null() and
                 server_end_version.is_null())):
            return APIVersion('2.0')
        else:
            raise exceptions.UnsupportedVersion(
                _("The server isn't backward compatible with Nova V2 REST "
                  "API"))

    if server_start_version.is_null() and server_end_version.is_null():
        return APIVersion('2.0')
    elif novaclient.API_MIN_VERSION > server_end_version:
        raise exceptions.UnsupportedVersion(
            _("Server version is too old. The client valid version range is "
              "'%(client_min)s' to '%(client_max)s'. The server valid version "
              "range is '%(server_min)s' to '%(server_max)s'.") % {
                  'client_min': novaclient.API_MIN_VERSION.get_string(),
                  'client_max': novaclient.API_MAX_VERSION.get_string(),
                  'server_min': server_start_version.get_string(),
                  'server_max': server_end_version.get_string()})
    elif novaclient.API_MAX_VERSION < server_start_version:
        raise exceptions.UnsupportedVersion(
            _("Server version is too new. The client valid version range is "
              "'%(client_min)s' to '%(client_max)s'. The server valid version "
              "range is '%(server_min)s' to '%(server_max)s'.") % {
                  'client_min': novaclient.API_MIN_VERSION.get_string(),
                  'client_max': novaclient.API_MAX_VERSION.get_string(),
                  'server_min': server_start_version.get_string(),
                  'server_max': server_end_version.get_string()})
    elif novaclient.API_MAX_VERSION <= server_end_version:
        return novaclient.API_MAX_VERSION
    elif server_end_version < novaclient.API_MAX_VERSION:
        return server_end_version
Exemple #3
0
def do_cell_capacities(cs, args):
    """Get cell capacities for all cells or a given cell."""
    cell = cs.cells.capacities(args.cell)
    print(_("Ram Available: %s MB") % cell.capacities["ram_free"]["total_mb"])
    utils.print_dict(cell.capacities["ram_free"]["units_by_mb"], dict_property="Ram(MB)", dict_value="Units")
    print(_("\nDisk Available: %s MB") % cell.capacities["disk_free"]["total_mb"])
    utils.print_dict(cell.capacities["disk_free"]["units_by_mb"], dict_property="Disk(MB)", dict_value="Units")
    def create(self, ip_protocol=None, from_port=None, to_port=None,
               cidr=None):
        """
        Create a security group default rule

        :param ip_protocol: IP protocol, one of 'tcp', 'udp' or 'icmp'
        :param from_port: Source port
        :param to_port: Destination port
        :param cidr: Destination IP address(es) in CIDR notation
        """

        try:
            from_port = int(from_port)
        except (TypeError, ValueError):
            raise exceptions.CommandError(_("From port must be an integer."))
        try:
            to_port = int(to_port)
        except (TypeError, ValueError):
            raise exceptions.CommandError(_("To port must be an integer."))
        if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']:
            raise exceptions.CommandError(_("Ip protocol must be 'tcp', 'udp'"
                                            ", or 'icmp'."))

        body = {"security_group_default_rule": {
            "ip_protocol": ip_protocol,
            "from_port": from_port,
            "to_port": to_port,
            "cidr": cidr}}

        return self._create('/os-security-group-default-rules', body,
                            'security_group_default_rule')
Exemple #5
0
    def __call__(self, parser, namespace, values, option_string):
        """Implement the action.

        Emits the deprecation warning message (only once for any given
        option string), then calls the real action (if any).

        :param parser: The ``argparse.ArgumentParser`` instance.
        :param namespace: The ``argparse.Namespace`` object which
                          should have an attribute set.
        :param values: Any arguments provided to the option.
        :param option_string: The option string that was used.
        """

        action = self._get_action(parser)

        # Only emit the deprecation warning once per option
        if option_string not in self.emitted:
            if self.use:
                print(_('WARNING: Option "%(option)s" is deprecated; '
                        '%(use)s') % {
                    'option': option_string,
                    'use': self.use,
                }, file=sys.stderr)
            else:
                print(_('WARNING: Option "%(option)s" is deprecated') %
                      {'option': option_string}, file=sys.stderr)
            self.emitted.add(option_string)

        if action:
            action(parser, namespace, values, option_string)
Exemple #6
0
    def _extract_service_catalog(self, url, resp, body, extract_token=True):
        """See what the auth service told us and process the response.
        We may get redirected to another site, fail or actually get
        back a service catalog with a token and our endpoints.
        """

        # content must always present
        if resp.status_code == 200 or resp.status_code == 201:
            try:
                self.auth_url = url
                self.service_catalog = \
                    service_catalog.ServiceCatalog(body)
                if extract_token:
                    self.auth_token = self.service_catalog.get_token()
                    self.tenant_id = self.service_catalog.get_tenant_id()

                self.management_url = self.get_service_url(self.service_type)
                return None
            except exceptions.AmbiguousEndpoints:
                print(_("Found more than one valid endpoint. Use a more "
                      "restrictive filter"))
                raise
            except KeyError:
                raise exceptions.AuthorizationFailure()
            except exceptions.EndpointNotFound:
                print(_("Could not find any suitable endpoint. Correct "
                        "region?"))
                raise

        elif resp.status_code == 305:
            return resp.headers['location']
        else:
            raise exceptions.from_response(resp, body, url)
def _check_arguments(kwargs, release, deprecated_name, right_name=None):
    """Process deprecation of arguments.

    Checks presence of deprecated argument in kwargs, prints proper warning
    message, renames key to right one it needed.
    """
    if deprecated_name in kwargs:
        if right_name:
            if right_name in kwargs:
                msg = _("The '%(old)s' argument is deprecated in "
                        "%(release)s and its use may result in errors "
                        "in future releases. As '%(new)s' is provided, "
                        "the '%(old)s' argument will be ignored.") % {
                    "old": deprecated_name, "release": release,
                    "new": right_name}
                kwargs.pop(deprecated_name)
            else:
                msg = _("The '%(old)s' argument is deprecated in "
                        "%(release)s and its use may result in errors in "
                        "future releases. Use '%(right)s' instead.") % {
                    "old": deprecated_name, "release": release,
                    "right": right_name}
                kwargs[right_name] = kwargs.pop(deprecated_name)

        else:
            msg = _("The '%(old)s' argument is deprecated in %(release)s "
                    "and its use may result in errors in future "
                    "releases.") % {
                "old": deprecated_name, "release": release}
            # just ignore it
            kwargs.pop(deprecated_name)

        warnings.warn(msg)
Exemple #8
0
def find_resource(manager, name_or_id, wrap_exception=True, **find_args):
    """Helper for the _find_* methods."""
    # for str id which is not uuid (for Flavor, Keypair and hypervsior in cells
    # environments search currently)
    if getattr(manager, "is_alphanum_id_allowed", False):
        try:
            return manager.get(name_or_id)
        except exceptions.NotFound:
            pass

    # first try to get entity as uuid
    try:
        tmp_id = encodeutils.safe_encode(name_or_id)

        if six.PY3:
            tmp_id = tmp_id.decode()

        uuid.UUID(tmp_id)
        return manager.get(tmp_id)
    except (TypeError, ValueError, exceptions.NotFound):
        pass

    # then try to get entity as name
    try:
        try:
            resource = getattr(manager, "resource_class", None)
            name_attr = resource.NAME_ATTR if resource else "name"
            kwargs = {name_attr: name_or_id}
            kwargs.update(find_args)
            return manager.find(**kwargs)
        except exceptions.NotFound:
            pass

        # then try to find entity by human_id
        try:
            return manager.find(human_id=name_or_id, **find_args)
        except exceptions.NotFound:
            pass
    except exceptions.NoUniqueMatch:
        msg = _("Multiple %(class)s matches found for '%(name)s', use an ID " "to be more specific.") % {
            "class": manager.resource_class.__name__.lower(),
            "name": name_or_id,
        }
        if wrap_exception:
            raise exceptions.CommandError(msg)
        raise exceptions.NoUniqueMatch(msg)

    # finally try to get entity as integer id
    try:
        return manager.get(int(name_or_id))
    except (TypeError, ValueError, exceptions.NotFound):
        msg = _("No %(class)s with a name or ID of '%(name)s' exists.") % {
            "class": manager.resource_class.__name__.lower(),
            "name": name_or_id,
        }
        if wrap_exception:
            raise exceptions.CommandError(msg)
        raise exceptions.NotFound(404, msg)
Exemple #9
0
    def __init__(self, option_strings, dest, help=None,
                 real_action=None, use=None, **kwargs):
        """Initialize a ``DeprecatedAction`` instance.

        :param option_strings: The recognized option strings.
        :param dest: The attribute that will be set.
        :param help: Help text.  This will be updated to indicate the
                     deprecation, and if ``use`` is provided, that
                     text will be included as well.
        :param real_action: The actual action to invoke.  This is
                            interpreted the same way as the ``action``
                            parameter.
        :param use: Text explaining which option to use instead.
        """

        # Update the help text
        if not help:
            if use:
                help = _('Deprecated; %(use)s') % {'use': use}
            else:
                help = _('Deprecated')
        elif help != argparse.SUPPRESS:
            if use:
                help = _('%(help)s (Deprecated; %(use)s)') % {
                    'help': help,
                    'use': use,
                }
            else:
                help = _('%(help)s (Deprecated)') % {'help': help}

        # Initialize ourself appropriately
        super(DeprecatedAction, self).__init__(
            option_strings, dest, help=help, **kwargs)

        # 'emitted' tracks which warnings we've emitted
        self.emitted = set()
        self.use = use

        # Select the appropriate action
        if real_action == 'nothing':
            # NOTE(Vek): "nothing" is distinct from a real_action=None
            # argument.  When real_action=None, the argparse default
            # action of "store" is used; when real_action='nothing',
            # however, we explicitly inhibit doing anything with the
            # option
            self.real_action_args = False
            self.real_action = None
        elif real_action is None or isinstance(real_action, six.string_types):
            # Specified by string (or None); we have to have a parser
            # to look up the actual action, so defer to later
            self.real_action_args = (option_strings, dest, help, kwargs)
            self.real_action = real_action
        else:
            self.real_action_args = False
            self.real_action = real_action(
                option_strings, dest, help=help, **kwargs)
def do_cell_capacities(cs, args):
    """Get cell capacities for all cells or a given cell."""
    cell = cs.cells.capacities(args.cell)
    print(_("Ram Available: %s MB") % cell.capacities['ram_free']['total_mb'])
    utils.print_dict(cell.capacities['ram_free']['units_by_mb'],
                     dict_property='Ram(MB)', dict_value="Units")
    print(_("\nDisk Available: %s MB") %
          cell.capacities['disk_free']['total_mb'])
    utils.print_dict(cell.capacities['disk_free']['units_by_mb'],
                     dict_property='Disk(MB)', dict_value="Units")
Exemple #11
0
def positive_non_zero_float(text):
    if text is None:
        return None
    try:
        value = float(text)
    except ValueError:
        msg = _("%s must be a float") % text
        raise argparse.ArgumentTypeError(msg)
    if value <= 0:
        msg = _("%s must be greater than 0") % text
        raise argparse.ArgumentTypeError(msg)
    return value
Exemple #12
0
def find_resource(manager, name_or_id, **find_args):
    """Helper for the _find_* methods."""
    # for str id which is not uuid (for Flavor and Keypair search currently)
    if getattr(manager, 'is_alphanum_id_allowed', False):
        try:
            return manager.get(name_or_id)
        except exceptions.NotFound:
            pass

    # try to get entity as integer id
    try:
        return manager.get(int(name_or_id))
    except (TypeError, ValueError, exceptions.NotFound):
        pass

    # now try to get entity as uuid
    try:
        tmp_id = encodeutils.safe_encode(name_or_id)

        if six.PY3:
            tmp_id = tmp_id.decode()

        uuid.UUID(tmp_id)
        return manager.get(tmp_id)
    except (TypeError, ValueError, exceptions.NotFound):
        pass

    try:
        try:
            return manager.find(human_id=name_or_id, **find_args)
        except exceptions.NotFound:
            pass

        # finally try to find entity by name
        try:
            resource = getattr(manager, 'resource_class', None)
            name_attr = resource.NAME_ATTR if resource else 'name'
            kwargs = {name_attr: name_or_id}
            kwargs.update(find_args)
            return manager.find(**kwargs)
        except exceptions.NotFound:
            msg = (_("No %(class)s with a name or ID of '%(name)s' exists.") %
                   {'class': manager.resource_class.__name__.lower(),
                    'name': name_or_id})
            raise exceptions.CommandError(msg)
    except exceptions.NoUniqueMatch:
        msg = (_("Multiple %(class)s matches found for '%(name)s', use an ID "
                 "to be more specific.") %
               {'class': manager.resource_class.__name__.lower(),
                'name': name_or_id})
        raise exceptions.CommandError(msg)
Exemple #13
0
    def create(self, name, ram, vcpus, disk, cache=0,flavorid="auto",
               ephemeral=0, swap=0, rxtx_factor=1.0, is_public=True):
        """Create a flavor.
        :param name: Descriptive name of the flavor
        :param ram: Memory in MB for the flavor
        :param vcpus: Number of VCPUs for the flavor
        :param disk: Size of local disk in GB
        :param flavorid: ID for the flavor (optional). You can use the reserved
                         value ``"auto"`` to have Nova generate a UUID for the
                         flavor in cases where you cannot simply pass ``None``.
        :param swap: Swap space in MB
        :param rxtx_factor: RX/TX factor
        :returns: :class:`Flavor`
        """

        try:
            ram = int(ram)
        except (TypeError, ValueError):
            raise exceptions.CommandError(_("Ram must be an integer."))
        try:
            vcpus = int(vcpus)
        except (TypeError, ValueError):
            raise exceptions.CommandError(_("VCPUs must be an integer."))
        try:
            disk = int(disk)
        except (TypeError, ValueError):
            raise exceptions.CommandError(_("Disk must be an integer."))

        try:
            cache = int(cache)
        except (TypeError, ValueError):
            raise exceptions.CommandError(_("Cache must be an integer."))
        
        if flavorid == "auto":
            flavorid = None

        try:
            swap = int(swap)
        except (TypeError, ValueError):
            raise exceptions.CommandError(_("Swap must be an integer."))
        try:
            ephemeral = int(ephemeral)
        except (TypeError, ValueError):
            raise exceptions.CommandError(_("Ephemeral must be an integer."))
        try:
            rxtx_factor = float(rxtx_factor)
        except (TypeError, ValueError):
            raise exceptions.CommandError(_("rxtx_factor must be a float."))

        try:
            is_public = strutils.bool_from_string(is_public, True)
        except Exception:
            raise exceptions.CommandError(_("is_public must be a boolean."))

        body = self._build_body(name, ram, vcpus, disk, cache, flavorid, swap,
                                ephemeral, rxtx_factor, is_public)

        LOG.info('before_cache %s',cache)
        LOG.info('body %s',body)
        return self._create("/flavors", body, "flavor")
def main():
    try:
        argv = [encodeutils.safe_decode(a) for a in sys.argv[1:]]
        OpenStackComputeShell().main(argv)
    except Exception as exc:
        logger.debug(exc, exc_info=1)
        print(_("ERROR (%(type)s): %(msg)s") % {
              'type': exc.__class__.__name__,
              'msg': encodeutils.exception_to_unicode(exc)},
              file=sys.stderr)
        sys.exit(1)
    except KeyboardInterrupt:
        print(_("... terminating nova client"), file=sys.stderr)
        sys.exit(130)
    def parse_opts(self, args):
        """
        Parse Opts from Argparse return.

        Currently the add_opts method appears to be
        Broken, so we rely on the existing parser options.
        """
        # add_opts method appears to be broken as of 5/4/16,
        # shell.py does not pass an instance of RackspaceAuthPlugin
        # as the first argument when called.

        parameters = [
            args.os_project_id,
            args.os_project_name,
            args.os_tenant_name
        ]

        project_id = ""
        for param in parameters:
            if param:
                project_id = param

        if not project_id:
            raise exc.CommandError(_("You must provide a project name or"
                                     " project id via --os-project-name,"
                                     " --os-project-id, env[OS_PROJECT_ID]"
                                     " or env[OS_PROJECT_NAME]. You may"
                                     " use os-project and os-tenant"
                                     " interchangeably."))

        if not args.os_password:
            raise exc.CommandError(_("You must provide an auth token"
                                     " via --os-password or env[OS_PASSWORD]"))
        if not args.os_region_name:
            raise exc.CommandError(_("You must provide a valid region via"
                                     " --os-region-name or"
                                     " env[OS_REGON_NAME]"))

        # Upstream novaclient does not pass --os-token
        # into the args passed to plugins, so we utilize
        # os_password
        self.opts = {
            "os_project_id": project_id,
            "os_auth_token": args.os_password,
            "os_auth_url": determine_auth_url(args)
        }

        return self.opts
    def __init__(self, version_str=None):
        """Create an API version object."""
        self.ver_major = 0
        self.ver_minor = 0

        if version_str is not None:
            match = re.match(r"^([1-9]\d*)\.([1-9]\d*|0|latest)$", version_str)
            if match:
                self.ver_major = int(match.group(1))
                if match.group(2) == "latest":
                    # NOTE(andreykurilin): Infinity allows to easily determine
                    # latest version and doesn't require any additional checks
                    # in comparison methods.
                    self.ver_minor = float("inf")
                else:
                    self.ver_minor = int(match.group(2))
            else:
                msg = (
                    _(
                        "Invalid format of client version '%s'. "
                        "Expected format 'X.Y', where X is a major part and Y "
                        "is a minor part of version."
                    )
                    % version_str
                )
                raise exceptions.UnsupportedVersion(msg)
def _server_live_migrate(cs, server, args):
    class HostEvacuateLiveResponse(object):
        def __init__(self, server_uuid, live_migration_accepted,
                     error_message):
            self.server_uuid = server_uuid
            self.live_migration_accepted = live_migration_accepted
            self.error_message = error_message
    success = True
    error_message = ""
    update_kwargs = {}
    try:
        # API >= 2.30
        if 'force' in args and args.force:
            update_kwargs['force'] = args.force
        # API 2.0->2.24
        if 'disk_over_commit' in args:
            update_kwargs['disk_over_commit'] = args.disk_over_commit
        cs.servers.live_migrate(server['uuid'], args.target_host,
                                args.block_migrate, **update_kwargs)
    except Exception as e:
        success = False
        error_message = _("Error while live migrating instance: %s") % e
    return HostEvacuateLiveResponse(server['uuid'],
                                    success,
                                    error_message)
def _server_evacuate(cs, server, args):
    success = True
    error_message = ""
    try:
        if api_versions.APIVersion("2.29") <= cs.api_version:
            # if microversion >= 2.29
            force = getattr(args, 'force', None)
            cs.servers.evacuate(server=server['uuid'], host=args.target_host,
                                force=force)
        elif api_versions.APIVersion("2.14") <= cs.api_version:
            # if microversion 2.14 - 2.28
            cs.servers.evacuate(server=server['uuid'], host=args.target_host)
        else:
            # else microversion 2.0 - 2.13
            on_shared_storage = getattr(args, 'on_shared_storage', None)
            cs.servers.evacuate(server=server['uuid'],
                                host=args.target_host,
                                on_shared_storage=on_shared_storage)
    except Exception as e:
        success = False
        error_message = _("Error while evacuating instance: %s") % e
    return EvacuateHostResponse(base.Manager,
                                {"server_uuid": server['uuid'],
                                 "evacuate_accepted": success,
                                 "error_message": error_message})
    def __init__(self, version_str=None):
        """Create an API version object.

        :param version_string: String representation of APIVersionRequest.
                               Correct format is 'X.Y', where 'X' and 'Y'
                               are int values. None value should be used
                               to create Null APIVersionRequest, which is
                               equal to 0.0
        """
        self.ver_major = 0
        self.ver_minor = 0

        if version_str is not None:
            match = re.match(r"^([1-9]\d*)\.([1-9]\d*|0|latest)$", version_str)
            if match:
                self.ver_major = int(match.group(1))
                if match.group(2) == "latest":
                    # NOTE(andreykurilin): Infinity allows to easily determine
                    # latest version and doesn't require any additional checks
                    # in comparison methods.
                    self.ver_minor = float("inf")
                else:
                    self.ver_minor = int(match.group(2))
            else:
                msg = (
                    _(
                        "Invalid format of client version '%s'. "
                        "Expected format 'X.Y', where X is a major part and Y "
                        "is a minor part of version."
                    )
                    % version_str
                )
                raise exceptions.UnsupportedVersion(msg)
    def find_image(self, name_or_id):
        """Find an image by name or id (user provided input)."""

        with self.alternate_service_type(
                'image', allowed_types=('image',)):
            # glance catalog entries are the unversioned endpoint, so
            # we need to jam a version bit in here.
            if uuidutils.is_uuid_like(name_or_id):
                # if it's a uuid, then just go collect the info and be
                # done with it.
                return self._get('/v2/images/%s' % name_or_id, None)
            else:
                matches = self._list('/v2/images?name=%s' % name_or_id,
                                     "images")
                num_matches = len(matches)
                if num_matches == 0:
                    msg = "No %s matching %s." % (
                        self.resource_class.__name__, name_or_id)
                    raise exceptions.NotFound(404, msg)
                elif num_matches > 1:
                    msg = (_("Multiple %(class)s matches found for "
                             "'%(name)s', use an ID to be more specific.") %
                           {'class': self.resource_class.__name__.lower(),
                            'name': name_or_id})
                    raise exceptions.NoUniqueMatch(msg)
                else:
                    matches[0].append_request_ids(matches.request_ids)
                    return matches[0]
Exemple #21
0
    def _get_action(self, parser):
        """Retrieve the action callable.

        This internal method is used to retrieve the callable
        implementing the action.  If ``real_action`` was specified as
        ``None`` or one of the standard string names, an internal
        method of the ``argparse.ArgumentParser`` instance is used to
        resolve it into an actual action class, which is then
        instantiated.  This is cached, in case the action is called
        multiple times.

        :param parser: The ``argparse.ArgumentParser`` instance.

        :returns: The action callable.
        """

        # If a lookup is needed, look up the action in the parser
        if self.real_action_args is not False:
            option_strings, dest, help, kwargs = self.real_action_args
            action_class = parser._registry_get('action', self.real_action)

            # Did we find the action class?
            if action_class is None:
                print(_('WARNING: Programming error: Unknown real action '
                        '"%s"') % self.real_action, file=sys.stderr)
                self.real_action = None
            else:
                # OK, instantiate the action class
                self.real_action = action_class(
                    option_strings, dest, help=help, **kwargs)

            # It's been resolved, no further need to look it up
            self.real_action_args = False

        return self.real_action
    def matches(self, min_version, max_version):
        """Matches the version object.

        Returns whether the version object represents a version
        greater than or equal to the minimum version and less than
        or equal to the maximum version.

        :param min_version: Minimum acceptable version.
        :param max_version: Maximum acceptable version.
        :returns: boolean

        If min_version is null then there is no minimum limit.
        If max_version is null then there is no maximum limit.
        If self is null then raise ValueError
        """

        if self.is_null():
            raise ValueError(_("Null APIVersion doesn't support 'matches'."))
        if max_version.is_null() and min_version.is_null():
            return True
        elif max_version.is_null():
            return min_version <= self
        elif min_version.is_null():
            return self <= max_version
        else:
            return min_version <= self <= max_version
 def list(self, **kwargs):
     if kwargs.get('flavor'):
         return self._list_by_flavor(kwargs['flavor'])
     elif kwargs.get('tenant'):
         return self._list_by_tenant(kwargs['tenant'])
     else:
         raise NotImplementedError(_('Unknown list options.'))
 def list(self, **kwargs):
     if kwargs.get("flavor"):
         return self._list_by_flavor(kwargs["flavor"])
     elif kwargs.get("tenant"):
         return self._list_by_tenant(kwargs["tenant"])
     else:
         raise NotImplementedError(_("Unknown list options."))
Exemple #25
0
    def _find_actions(self, subparsers, actions_module, version, do_help):
        msg = _(" (Supported by API versions '%(start)s' - '%(end)s')")
        for attr in (a for a in dir(actions_module) if a.startswith('do_')):
            # I prefer to be hyphen-separated instead of underscores.
            command = attr[3:].replace('_', '-')
            callback = getattr(actions_module, attr)
            desc = callback.__doc__ or ''
            if hasattr(callback, "versioned"):
                subs = api_versions.get_substitutions(
                    utils.get_function_name(callback))
                if do_help:
                    desc += msg % {'start': subs[0].start_version.get_string(),
                                   'end': subs[-1].end_version.get_string()}
                else:
                    for versioned_method in subs:
                        if version.matches(versioned_method.start_version,
                                           versioned_method.end_version):
                            callback = versioned_method.func
                            break
                    else:
                        continue

            action_help = desc.strip()
            arguments = getattr(callback, 'arguments', [])

            subparser = subparsers.add_parser(
                command,
                help=action_help,
                description=desc,
                add_help=False,
                formatter_class=OpenStackHelpFormatter)
            subparser.add_argument(
                '-h', '--help',
                action='help',
                help=argparse.SUPPRESS,
            )
            self.subcommands[command] = subparser
            for (args, kwargs) in arguments:
                start_version = kwargs.get("start_version", None)
                if start_version:
                    start_version = api_versions.APIVersion(start_version)
                    end_version = kwargs.get("end_version", None)
                    if end_version:
                        end_version = api_versions.APIVersion(end_version)
                    else:
                        end_version = api_versions.APIVersion(
                            "%s.latest" % start_version.ver_major)
                    if do_help:
                        kwargs["help"] = kwargs.get("help", "") + (msg % {
                            "start": start_version.get_string(),
                            "end": end_version.get_string()})
                    else:
                        if not version.matches(start_version, end_version):
                            continue
                kw = kwargs.copy()
                kw.pop("start_version", None)
                kw.pop("end_version", None)
                subparser.add_argument(*args, **kw)
            subparser.set_defaults(func=callback)
 def list(self, instance_id):
     """DEPRECATED"""
     warnings.warn(_('The os-virtual-interfaces API is deprecated. This '
                     'API binding will be removed in the first major '
                     'release after the Nova server 16.0.0 Pike release.'),
                   DeprecationWarning)
     return self._list('/servers/%s/os-virtual-interfaces' % instance_id,
                       'virtual_interfaces')
Exemple #27
0
def validate_flavor_metadata_keys(keys):
    for key in keys:
        valid_name = VALID_KEY_REGEX.match(key)
        if not valid_name:
            msg = _('Invalid key: "%s". Keys may only contain letters, '
                    'numbers, spaces, underscores, periods, colons and '
                    'hyphens.')
            raise exceptions.CommandError(msg % key)
 def get_string(self):
     """Converts object to string representation which if used to create
     an APIVersion object results in the same version.
     """
     if self.is_null():
         raise ValueError(_("Null APIVersion cannot be converted to string."))
     elif self.is_latest():
         return "%s.%s" % (self.ver_major, "latest")
     return "%s.%s" % (self.ver_major, self.ver_minor)
def check_major_version(api_version):
    """Checks major part of ``APIVersion`` obj is supported.

    :raises novaclient.exceptions.UnsupportedVersion: if major part is not
                                                      supported
    """
    available_versions = get_available_major_versions()
    if not api_version.is_null() and str(api_version.ver_major) not in available_versions:
        if len(available_versions) == 1:
            msg = _("Invalid client version '%(version)s'. " "Major part should be '%(major)s'") % {
                "version": api_version.get_string(),
                "major": available_versions[0],
            }
        else:
            msg = _("Invalid client version '%(version)s'. " "Major part must be one of: '%(major)s'") % {
                "version": api_version.get_string(),
                "major": ", ".join(available_versions),
            }
        raise exceptions.UnsupportedVersion(msg)
def _get_client_class_and_version(version):
    if not isinstance(version, api_versions.APIVersion):
        version = api_versions.get_api_version(version)
    else:
        api_versions.check_major_version(version)
    if version.is_latest():
        raise exceptions.UnsupportedVersion(
            _("The version should be explicit, not latest."))
    return version, importutils.import_class(
        "novaclient.v%s.client.Client" % version.ver_major)
Exemple #31
0
class OpenStackComputeShell(object):
    times = []

    def __init__(self):
        self.client_logger = None

    def _append_global_identity_args(self, parser, argv):
        # Register the CLI arguments that have moved to the session object.
        loading.register_session_argparse_arguments(parser)
        # Peek into argv to see if os-auth-token or os-token were given,
        # in which case, the token auth plugin is what the user wants
        # else, we'll default to password
        default_auth_plugin = 'password'
        if 'os-token' in argv:
            default_auth_plugin = 'token'
        loading.register_auth_argparse_arguments(
            parser, argv, default=default_auth_plugin)

        parser.set_defaults(insecure=strutils.bool_from_string(
            utils.env('NOVACLIENT_INSECURE', default=False)))
        parser.set_defaults(os_auth_url=utils.env('OS_AUTH_URL', 'NOVA_URL'))

        parser.set_defaults(os_username=utils.env('OS_USERNAME',
                                                  'NOVA_USERNAME'))
        parser.set_defaults(os_password=utils.env('OS_PASSWORD',
                                                  'NOVA_PASSWORD'))
        parser.set_defaults(os_project_name=utils.env(
            'OS_PROJECT_NAME', 'OS_TENANT_NAME', 'NOVA_PROJECT_ID'))
        parser.set_defaults(os_project_id=utils.env(
            'OS_PROJECT_ID', 'OS_TENANT_ID'))

    def get_base_parser(self, argv):
        parser = NovaClientArgumentParser(
            prog='nova',
            description=__doc__.strip(),
            epilog='See "nova help COMMAND" '
                   'for help on a specific command.',
            add_help=False,
            formatter_class=OpenStackHelpFormatter,
        )

        # Global arguments
        parser.add_argument(
            '-h', '--help',
            action='store_true',
            help=argparse.SUPPRESS,
        )

        parser.add_argument('--version',
                            action='version',
                            version=novaclient.__version__)

        parser.add_argument(
            '--debug',
            default=False,
            action='store_true',
            help=_("Print debugging output."))

        parser.add_argument(
            '--os-cache',
            default=strutils.bool_from_string(
                utils.env('OS_CACHE', default=False), True),
            action='store_true',
            help=_("Use the auth token cache. Defaults to False if "
                   "env[OS_CACHE] is not set."))

        parser.add_argument(
            '--timings',
            default=False,
            action='store_true',
            help=_("Print call timing info."))

        parser.add_argument(
            '--os-region-name',
            metavar='<region-name>',
            default=utils.env('OS_REGION_NAME', 'NOVA_REGION_NAME'),
            help=_('Defaults to env[OS_REGION_NAME].'))

        parser.add_argument(
            '--os-auth-system',
            metavar='<auth-system>',
            default=utils.env('OS_AUTH_SYSTEM'),
            help=argparse.SUPPRESS)

        parser.add_argument(
            '--service-type',
            metavar='<service-type>',
            help=_('Defaults to compute for most actions.'))

        parser.add_argument(
            '--service-name',
            metavar='<service-name>',
            default=utils.env('NOVA_SERVICE_NAME'),
            help=_('Defaults to env[NOVA_SERVICE_NAME].'))

        parser.add_argument(
            '--volume-service-name',
            action=DeprecatedAction,
            metavar='<volume-service-name>',
            default=utils.env('NOVA_VOLUME_SERVICE_NAME'),
            use=_('This option will be removed in novaclient 4.3.0.'),
            help=argparse.SUPPRESS)

        parser.add_argument(
            '--os-endpoint-type',
            metavar='<endpoint-type>',
            dest='endpoint_type',
            default=utils.env(
                'NOVA_ENDPOINT_TYPE', default=utils.env(
                    'OS_ENDPOINT_TYPE',
                    default=DEFAULT_NOVA_ENDPOINT_TYPE)),
            help=_('Defaults to env[NOVA_ENDPOINT_TYPE], '
                   'env[OS_ENDPOINT_TYPE] or ') +
                 DEFAULT_NOVA_ENDPOINT_TYPE + '.')

        parser.add_argument(
            '--os-compute-api-version',
            metavar='<compute-api-ver>',
            default=utils.env('OS_COMPUTE_API_VERSION',
                              default=DEFAULT_OS_COMPUTE_API_VERSION),
            help=_('Accepts X, X.Y (where X is major and Y is minor part) or '
                   '"X.latest", defaults to env[OS_COMPUTE_API_VERSION].'))

        parser.add_argument(
            '--bypass-url',
            metavar='<bypass-url>',
            dest='bypass_url',
            default=utils.env('NOVACLIENT_BYPASS_URL'),
            help=_("Use this API endpoint instead of the Service Catalog. "
                   "Defaults to env[NOVACLIENT_BYPASS_URL]."))

        # The auth-system-plugins might require some extra options
        novaclient.auth_plugin.load_auth_system_opts(parser)

        self._append_global_identity_args(parser, argv)

        return parser

    def get_subcommand_parser(self, version, do_help=False, argv=None):
        parser = self.get_base_parser(argv)

        self.subcommands = {}
        subparsers = parser.add_subparsers(metavar='<subcommand>')

        actions_module = importutils.import_module(
            "novaclient.v%s.shell" % version.ver_major)

        self._find_actions(subparsers, actions_module, version, do_help)
        self._find_actions(subparsers, self, version, do_help)

        for extension in self.extensions:
            self._find_actions(subparsers, extension.module, version, do_help)

        self._add_bash_completion_subparser(subparsers)

        return parser

    def _add_bash_completion_subparser(self, subparsers):
        subparser = subparsers.add_parser(
            'bash_completion',
            add_help=False,
            formatter_class=OpenStackHelpFormatter
        )
        self.subcommands['bash_completion'] = subparser
        subparser.set_defaults(func=self.do_bash_completion)

    def _find_actions(self, subparsers, actions_module, version, do_help):
        msg = _(" (Supported by API versions '%(start)s' - '%(end)s')")
        for attr in (a for a in dir(actions_module) if a.startswith('do_')):
            # I prefer to be hyphen-separated instead of underscores.
            command = attr[3:].replace('_', '-')
            callback = getattr(actions_module, attr)
            desc = callback.__doc__ or ''
            if hasattr(callback, "versioned"):
                additional_msg = ""
                subs = api_versions.get_substitutions(callback)
                if do_help:
                    additional_msg = msg % {
                        'start': subs[0].start_version.get_string(),
                        'end': subs[-1].end_version.get_string()}
                    if version.is_latest():
                        additional_msg += HINT_HELP_MSG
                subs = [versioned_method for versioned_method in subs
                        if version.matches(versioned_method.start_version,
                                           versioned_method.end_version)]
                if subs:
                    # use the "latest" substitution
                    callback = subs[-1].func
                else:
                    # there is no proper versioned method
                    continue
                desc = callback.__doc__ or desc
                desc += additional_msg

            action_help = desc.strip()
            arguments = getattr(callback, 'arguments', [])

            subparser = subparsers.add_parser(
                command,
                help=action_help,
                description=desc,
                add_help=False,
                formatter_class=OpenStackHelpFormatter)
            subparser.add_argument(
                '-h', '--help',
                action='help',
                help=argparse.SUPPRESS,
            )
            self.subcommands[command] = subparser
            for (args, kwargs) in arguments:
                start_version = kwargs.get("start_version", None)
                if start_version:
                    start_version = api_versions.APIVersion(start_version)
                    end_version = kwargs.get("end_version", None)
                    if end_version:
                        end_version = api_versions.APIVersion(end_version)
                    else:
                        end_version = api_versions.APIVersion(
                            "%s.latest" % start_version.ver_major)
                    if do_help:
                        kwargs["help"] = kwargs.get("help", "") + (msg % {
                            "start": start_version.get_string(),
                            "end": end_version.get_string()})
                    if not version.matches(start_version, end_version):
                        continue
                kw = kwargs.copy()
                kw.pop("start_version", None)
                kw.pop("end_version", None)
                subparser.add_argument(*args, **kw)
            subparser.set_defaults(func=callback)

    def setup_debugging(self, debug):
        if not debug:
            return

        streamformat = "%(levelname)s (%(module)s:%(lineno)d) %(message)s"
        # Set up the root logger to debug so that the submodules can
        # print debug messages
        logging.basicConfig(level=logging.DEBUG,
                            format=streamformat)
        logging.getLogger('iso8601').setLevel(logging.WARNING)

        self.client_logger = logging.getLogger(client.__name__)
        ch = logging.StreamHandler()
        self.client_logger.setLevel(logging.DEBUG)
        self.client_logger.addHandler(ch)

    def main(self, argv):
        # Parse args once to find version and debug settings
        parser = self.get_base_parser(argv)
        (args, args_list) = parser.parse_known_args(argv)

        self.setup_debugging(args.debug)
        self.extensions = []
        do_help = ('help' in argv) or (
            '--help' in argv) or ('-h' in argv) or not argv

        # bash-completion should not require authentication
        skip_auth = do_help or (
            'bash-completion' in argv)

        # Discover available auth plugins
        novaclient.auth_plugin.discover_auth_systems()

        if not args.os_compute_api_version:
            api_version = api_versions.get_api_version(
                DEFAULT_MAJOR_OS_COMPUTE_API_VERSION)
        else:
            api_version = api_versions.get_api_version(
                args.os_compute_api_version)

        os_username = args.os_username
        os_user_id = args.os_user_id
        os_password = None  # Fetched and set later as needed
        os_project_name = getattr(
            args, 'os_project_name', getattr(args, 'os_tenant_name', None))
        os_project_id = getattr(
            args, 'os_project_id', getattr(args, 'os_tenant_id', None))
        os_auth_url = args.os_auth_url
        os_region_name = args.os_region_name
        os_auth_system = args.os_auth_system

        if "v2.0" not in os_auth_url:
            # NOTE(andreykurilin): assume that keystone V3 is used and try to
            # be more user-friendly, i.e provide default values for domains
            if (not args.os_project_domain_id and
                    not args.os_project_domain_name):
                setattr(args, "os_project_domain_id", "default")
            if not args.os_user_domain_id and not args.os_user_domain_name:
                setattr(args, "os_user_domain_id", "default")

        endpoint_type = args.endpoint_type
        insecure = args.insecure
        service_type = args.service_type
        service_name = args.service_name
        volume_service_name = args.volume_service_name
        bypass_url = args.bypass_url
        os_cache = args.os_cache
        cacert = args.os_cacert
        timeout = args.timeout

        keystone_session = None
        keystone_auth = None

        # We may have either, both or none of these.
        # If we have both, we don't need USERNAME, PASSWORD etc.
        # Fill in the blanks from the SecretsHelper if possible.
        # Finally, authenticate unless we have both.
        # Note if we don't auth we probably don't have a tenant ID so we can't
        # cache the token.
        auth_token = getattr(args, 'os_token', None)
        management_url = bypass_url if bypass_url else None

        if os_auth_system and os_auth_system != "keystone":
            warnings.warn(_(
                'novaclient auth plugins that are not keystone are deprecated.'
                ' Auth plugins should now be done as plugins to keystoneauth'
                ' and selected with --os-auth-type or OS_AUTH_TYPE'))
            auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_system)
        else:
            auth_plugin = None

        if not endpoint_type:
            endpoint_type = DEFAULT_NOVA_ENDPOINT_TYPE

        # This allow users to use endpoint_type as (internal, public or admin)
        # just like other openstack clients (glance, cinder etc)
        if endpoint_type in ['internal', 'public', 'admin']:
            endpoint_type += 'URL'

        if not service_type:
            # Note(alex_xu): We need discover version first, so if there isn't
            # service type specified, we use default nova service type.
            service_type = DEFAULT_NOVA_SERVICE_TYPE

        # If we have an auth token but no management_url, we must auth anyway.
        # Expired tokens are handled by client.py:_cs_request
        must_auth = not (auth_token and management_url)

        # Do not use Keystone session for cases with no session support. The
        # presence of auth_plugin means os_auth_system is present and is not
        # keystone.
        use_session = True
        if auth_plugin or bypass_url or os_cache or volume_service_name:
            use_session = False

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

            if not auth_plugin or not auth_plugin.opts:
                if not os_username and not os_user_id:
                    raise exc.CommandError(
                        _("You must provide a username "
                          "or user ID via --os-username, --os-user-id, "
                          "env[OS_USERNAME] or env[OS_USER_ID]"))

            if not any([os_project_name, 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_ID]"
                                         " or env[OS_PROJECT_NAME]. You may"
                                         " use os-project and os-tenant"
                                         " interchangeably."))

            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]"))

            if use_session:
                # Not using Nova auth plugin, so use keystone
                with utils.record_time(self.times, args.timings,
                                       'auth_url', args.os_auth_url):
                    keystone_session = (
                        loading.load_session_from_argparse_arguments(args))
                    keystone_auth = (
                        loading.load_auth_from_argparse_arguments(args))
            else:
                # set password for auth plugins
                os_password = args.os_password

        if (not skip_auth and
                not any([os_project_name, 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_ID]"
                                     " or env[OS_PROJECT_NAME]. You may"
                                     " use os-project and os-tenant"
                                     " interchangeably."))

        if not os_auth_url and not skip_auth:
            raise exc.CommandError(
                _("You must provide an auth url "
                  "via either --os-auth-url or env[OS_AUTH_URL]"))

        # This client is just used to discover api version. Version API needn't
        # microversion, so we just pass version 2 at here.
        self.cs = client.Client(
            api_versions.APIVersion("2.0"),
            os_username, os_password, os_project_name,
            tenant_id=os_project_id, user_id=os_user_id,
            auth_url=os_auth_url, insecure=insecure,
            region_name=os_region_name, endpoint_type=endpoint_type,
            extensions=self.extensions, service_type=service_type,
            service_name=service_name, auth_system=os_auth_system,
            auth_plugin=auth_plugin, auth_token=auth_token,
            volume_service_name=volume_service_name,
            timings=args.timings, bypass_url=bypass_url,
            os_cache=os_cache, http_log_debug=args.debug,
            cacert=cacert, timeout=timeout,
            session=keystone_session, auth=keystone_auth,
            logger=self.client_logger)

        if not skip_auth:
            if not api_version.is_latest():
                if api_version > api_versions.APIVersion("2.0"):
                    if not api_version.matches(novaclient.API_MIN_VERSION,
                                               novaclient.API_MAX_VERSION):
                        raise exc.CommandError(
                            _("The specified version isn't supported by "
                              "client. The valid version range is '%(min)s' "
                              "to '%(max)s'") % {
                                "min": novaclient.API_MIN_VERSION.get_string(),
                                "max": novaclient.API_MAX_VERSION.get_string()}
                        )
            api_version = api_versions.discover_version(self.cs, api_version)

        # build available subcommands based on version
        self.extensions = client.discover_extensions(api_version)
        self._run_extension_hooks('__pre_parse_args__')

        subcommand_parser = self.get_subcommand_parser(
            api_version, do_help=do_help, argv=argv)
        self.parser = subcommand_parser

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

        args = subcommand_parser.parse_args(argv)
        self._run_extension_hooks('__post_parse_args__', args)

        # Short-circuit and deal with help right away.
        if 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

        if not args.service_type:
            service_type = (utils.get_service_type(args.func) or
                            DEFAULT_NOVA_SERVICE_TYPE)

        if utils.isunauthenticated(args.func):
            # NOTE(alex_xu): We need authentication for discover microversion.
            # But the subcommands may needn't it. If the subcommand needn't,
            # we clear the session arguments.
            keystone_session = None
            keystone_auth = None

        # Recreate client object with discovered version.
        self.cs = client.Client(
            api_version,
            os_username, os_password, os_project_name,
            tenant_id=os_project_id, user_id=os_user_id,
            auth_url=os_auth_url, insecure=insecure,
            region_name=os_region_name, endpoint_type=endpoint_type,
            extensions=self.extensions, service_type=service_type,
            service_name=service_name, auth_system=os_auth_system,
            auth_plugin=auth_plugin, auth_token=auth_token,
            volume_service_name=volume_service_name,
            timings=args.timings, bypass_url=bypass_url,
            os_cache=os_cache, http_log_debug=args.debug,
            cacert=cacert, timeout=timeout,
            session=keystone_session, auth=keystone_auth)

        # Now check for the password/token of which pieces of the
        # identifying keyring key can come from the underlying client
        if must_auth:
            helper = SecretsHelper(args, self.cs.client)
            self.cs.client.keyring_saver = helper
            if (auth_plugin and auth_plugin.opts and
                    "os_password" not in auth_plugin.opts):
                use_pw = False
            else:
                use_pw = True

            tenant_id = helper.tenant_id
            # Allow commandline to override cache
            if not auth_token:
                auth_token = helper.auth_token
            if not management_url:
                management_url = helper.management_url
            if tenant_id and auth_token and management_url:
                self.cs.client.tenant_id = tenant_id
                self.cs.client.auth_token = auth_token
                self.cs.client.management_url = management_url
                self.cs.client.password_func = lambda: helper.password
            elif use_pw:
                # We're missing something, so auth with user/pass and save
                # the result in our helper.
                self.cs.client.password = helper.password

        try:
            # This does a couple of bits which are useful even if we've
            # got the token + service URL already. It exits fast in that case.
            if not utils.isunauthenticated(args.func):
                if not use_session:
                    # Only call authenticate() if Nova auth plugin is used.
                    # If keystone is used, authentication is handled as part
                    # of session.
                    self.cs.authenticate()
        except exc.Unauthorized:
            raise exc.CommandError(_("Invalid OpenStack Nova credentials."))
        except exc.AuthorizationFailure:
            raise exc.CommandError(_("Unable to authorize user"))

        args.func(self.cs, args)

        if args.timings:
            self._dump_timings(self.times + self.cs.get_timings())

    def _dump_timings(self, timings):
        class Tyme(object):
            def __init__(self, url, seconds):
                self.url = url
                self.seconds = seconds
        results = [Tyme(url, end - start) for url, start, end in timings]
        total = 0.0
        for tyme in results:
            total += tyme.seconds
        results.append(Tyme("Total", total))
        utils.print_list(results, ["url", "seconds"], sortby_index=None)

    def _run_extension_hooks(self, hook_type, *args, **kwargs):
        """Run hooks for all registered extensions."""
        for extension in self.extensions:
            extension.run_hooks(hook_type, *args, **kwargs)

    def do_bash_completion(self, _args):
        """
        Prints all of the commands and options to stdout so that the
        nova.bash_completion script doesn't have to hard code them.
        """
        commands = set()
        options = set()
        for sc_str, sc in self.subcommands.items():
            commands.add(sc_str)
            for option in sc._optionals._option_string_actions.keys():
                options.add(option)

        commands.remove('bash-completion')
        commands.remove('bash_completion')
        print(' '.join(commands | options))

    @utils.arg(
        'command',
        metavar='<subcommand>',
        nargs='?',
        help=_('Display help for <subcommand>.'))
    def do_help(self, args):
        """
        Display help about this program or one of its subcommands.
        """
        if args.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()
Exemple #32
0
    def get_base_parser(self, argv):
        parser = NovaClientArgumentParser(
            prog='nova',
            description=__doc__.strip(),
            epilog='See "nova help COMMAND" '
                   'for help on a specific command.',
            add_help=False,
            formatter_class=OpenStackHelpFormatter,
        )

        # Global arguments
        parser.add_argument(
            '-h', '--help',
            action='store_true',
            help=argparse.SUPPRESS,
        )

        parser.add_argument('--version',
                            action='version',
                            version=novaclient.__version__)

        parser.add_argument(
            '--debug',
            default=False,
            action='store_true',
            help=_("Print debugging output."))

        parser.add_argument(
            '--os-cache',
            default=strutils.bool_from_string(
                utils.env('OS_CACHE', default=False), True),
            action='store_true',
            help=_("Use the auth token cache. Defaults to False if "
                   "env[OS_CACHE] is not set."))

        parser.add_argument(
            '--timings',
            default=False,
            action='store_true',
            help=_("Print call timing info."))

        parser.add_argument(
            '--os-region-name',
            metavar='<region-name>',
            default=utils.env('OS_REGION_NAME', 'NOVA_REGION_NAME'),
            help=_('Defaults to env[OS_REGION_NAME].'))

        parser.add_argument(
            '--os-auth-system',
            metavar='<auth-system>',
            default=utils.env('OS_AUTH_SYSTEM'),
            help=argparse.SUPPRESS)

        parser.add_argument(
            '--service-type',
            metavar='<service-type>',
            help=_('Defaults to compute for most actions.'))

        parser.add_argument(
            '--service-name',
            metavar='<service-name>',
            default=utils.env('NOVA_SERVICE_NAME'),
            help=_('Defaults to env[NOVA_SERVICE_NAME].'))

        parser.add_argument(
            '--volume-service-name',
            action=DeprecatedAction,
            metavar='<volume-service-name>',
            default=utils.env('NOVA_VOLUME_SERVICE_NAME'),
            use=_('This option will be removed in novaclient 4.3.0.'),
            help=argparse.SUPPRESS)

        parser.add_argument(
            '--os-endpoint-type',
            metavar='<endpoint-type>',
            dest='endpoint_type',
            default=utils.env(
                'NOVA_ENDPOINT_TYPE', default=utils.env(
                    'OS_ENDPOINT_TYPE',
                    default=DEFAULT_NOVA_ENDPOINT_TYPE)),
            help=_('Defaults to env[NOVA_ENDPOINT_TYPE], '
                   'env[OS_ENDPOINT_TYPE] or ') +
                 DEFAULT_NOVA_ENDPOINT_TYPE + '.')

        parser.add_argument(
            '--os-compute-api-version',
            metavar='<compute-api-ver>',
            default=utils.env('OS_COMPUTE_API_VERSION',
                              default=DEFAULT_OS_COMPUTE_API_VERSION),
            help=_('Accepts X, X.Y (where X is major and Y is minor part) or '
                   '"X.latest", defaults to env[OS_COMPUTE_API_VERSION].'))

        parser.add_argument(
            '--bypass-url',
            metavar='<bypass-url>',
            dest='bypass_url',
            default=utils.env('NOVACLIENT_BYPASS_URL'),
            help=_("Use this API endpoint instead of the Service Catalog. "
                   "Defaults to env[NOVACLIENT_BYPASS_URL]."))

        # The auth-system-plugins might require some extra options
        novaclient.auth_plugin.load_auth_system_opts(parser)

        self._append_global_identity_args(parser, argv)

        return parser
Exemple #33
0
    def main(self, argv):
        # Parse args once to find version and debug settings
        parser = self.get_base_parser(argv)
        (args, args_list) = parser.parse_known_args(argv)

        self.setup_debugging(args.debug)
        self.extensions = []
        do_help = ('help' in argv) or (
            '--help' in argv) or ('-h' in argv) or not argv

        # bash-completion should not require authentication
        skip_auth = do_help or (
            'bash-completion' in argv)

        # Discover available auth plugins
        novaclient.auth_plugin.discover_auth_systems()

        if not args.os_compute_api_version:
            api_version = api_versions.get_api_version(
                DEFAULT_MAJOR_OS_COMPUTE_API_VERSION)
        else:
            api_version = api_versions.get_api_version(
                args.os_compute_api_version)

        os_username = args.os_username
        os_user_id = args.os_user_id
        os_password = None  # Fetched and set later as needed
        os_project_name = getattr(
            args, 'os_project_name', getattr(args, 'os_tenant_name', None))
        os_project_id = getattr(
            args, 'os_project_id', getattr(args, 'os_tenant_id', None))
        os_auth_url = args.os_auth_url
        os_region_name = args.os_region_name
        os_auth_system = args.os_auth_system

        if "v2.0" not in os_auth_url:
            # NOTE(andreykurilin): assume that keystone V3 is used and try to
            # be more user-friendly, i.e provide default values for domains
            if (not args.os_project_domain_id and
                    not args.os_project_domain_name):
                setattr(args, "os_project_domain_id", "default")
            if not args.os_user_domain_id and not args.os_user_domain_name:
                setattr(args, "os_user_domain_id", "default")

        endpoint_type = args.endpoint_type
        insecure = args.insecure
        service_type = args.service_type
        service_name = args.service_name
        volume_service_name = args.volume_service_name
        bypass_url = args.bypass_url
        os_cache = args.os_cache
        cacert = args.os_cacert
        timeout = args.timeout

        keystone_session = None
        keystone_auth = None

        # We may have either, both or none of these.
        # If we have both, we don't need USERNAME, PASSWORD etc.
        # Fill in the blanks from the SecretsHelper if possible.
        # Finally, authenticate unless we have both.
        # Note if we don't auth we probably don't have a tenant ID so we can't
        # cache the token.
        auth_token = getattr(args, 'os_token', None)
        management_url = bypass_url if bypass_url else None

        if os_auth_system and os_auth_system != "keystone":
            warnings.warn(_(
                'novaclient auth plugins that are not keystone are deprecated.'
                ' Auth plugins should now be done as plugins to keystoneauth'
                ' and selected with --os-auth-type or OS_AUTH_TYPE'))
            auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_system)
        else:
            auth_plugin = None

        if not endpoint_type:
            endpoint_type = DEFAULT_NOVA_ENDPOINT_TYPE

        # This allow users to use endpoint_type as (internal, public or admin)
        # just like other openstack clients (glance, cinder etc)
        if endpoint_type in ['internal', 'public', 'admin']:
            endpoint_type += 'URL'

        if not service_type:
            # Note(alex_xu): We need discover version first, so if there isn't
            # service type specified, we use default nova service type.
            service_type = DEFAULT_NOVA_SERVICE_TYPE

        # If we have an auth token but no management_url, we must auth anyway.
        # Expired tokens are handled by client.py:_cs_request
        must_auth = not (auth_token and management_url)

        # Do not use Keystone session for cases with no session support. The
        # presence of auth_plugin means os_auth_system is present and is not
        # keystone.
        use_session = True
        if auth_plugin or bypass_url or os_cache or volume_service_name:
            use_session = False

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

            if not auth_plugin or not auth_plugin.opts:
                if not os_username and not os_user_id:
                    raise exc.CommandError(
                        _("You must provide a username "
                          "or user ID via --os-username, --os-user-id, "
                          "env[OS_USERNAME] or env[OS_USER_ID]"))

            if not any([os_project_name, 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_ID]"
                                         " or env[OS_PROJECT_NAME]. You may"
                                         " use os-project and os-tenant"
                                         " interchangeably."))

            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]"))

            if use_session:
                # Not using Nova auth plugin, so use keystone
                with utils.record_time(self.times, args.timings,
                                       'auth_url', args.os_auth_url):
                    keystone_session = (
                        loading.load_session_from_argparse_arguments(args))
                    keystone_auth = (
                        loading.load_auth_from_argparse_arguments(args))
            else:
                # set password for auth plugins
                os_password = args.os_password

        if (not skip_auth and
                not any([os_project_name, 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_ID]"
                                     " or env[OS_PROJECT_NAME]. You may"
                                     " use os-project and os-tenant"
                                     " interchangeably."))

        if not os_auth_url and not skip_auth:
            raise exc.CommandError(
                _("You must provide an auth url "
                  "via either --os-auth-url or env[OS_AUTH_URL]"))

        # This client is just used to discover api version. Version API needn't
        # microversion, so we just pass version 2 at here.
        self.cs = client.Client(
            api_versions.APIVersion("2.0"),
            os_username, os_password, os_project_name,
            tenant_id=os_project_id, user_id=os_user_id,
            auth_url=os_auth_url, insecure=insecure,
            region_name=os_region_name, endpoint_type=endpoint_type,
            extensions=self.extensions, service_type=service_type,
            service_name=service_name, auth_system=os_auth_system,
            auth_plugin=auth_plugin, auth_token=auth_token,
            volume_service_name=volume_service_name,
            timings=args.timings, bypass_url=bypass_url,
            os_cache=os_cache, http_log_debug=args.debug,
            cacert=cacert, timeout=timeout,
            session=keystone_session, auth=keystone_auth,
            logger=self.client_logger)

        if not skip_auth:
            if not api_version.is_latest():
                if api_version > api_versions.APIVersion("2.0"):
                    if not api_version.matches(novaclient.API_MIN_VERSION,
                                               novaclient.API_MAX_VERSION):
                        raise exc.CommandError(
                            _("The specified version isn't supported by "
                              "client. The valid version range is '%(min)s' "
                              "to '%(max)s'") % {
                                "min": novaclient.API_MIN_VERSION.get_string(),
                                "max": novaclient.API_MAX_VERSION.get_string()}
                        )
            api_version = api_versions.discover_version(self.cs, api_version)

        # build available subcommands based on version
        self.extensions = client.discover_extensions(api_version)
        self._run_extension_hooks('__pre_parse_args__')

        subcommand_parser = self.get_subcommand_parser(
            api_version, do_help=do_help, argv=argv)
        self.parser = subcommand_parser

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

        args = subcommand_parser.parse_args(argv)
        self._run_extension_hooks('__post_parse_args__', args)

        # Short-circuit and deal with help right away.
        if 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

        if not args.service_type:
            service_type = (utils.get_service_type(args.func) or
                            DEFAULT_NOVA_SERVICE_TYPE)

        if utils.isunauthenticated(args.func):
            # NOTE(alex_xu): We need authentication for discover microversion.
            # But the subcommands may needn't it. If the subcommand needn't,
            # we clear the session arguments.
            keystone_session = None
            keystone_auth = None

        # Recreate client object with discovered version.
        self.cs = client.Client(
            api_version,
            os_username, os_password, os_project_name,
            tenant_id=os_project_id, user_id=os_user_id,
            auth_url=os_auth_url, insecure=insecure,
            region_name=os_region_name, endpoint_type=endpoint_type,
            extensions=self.extensions, service_type=service_type,
            service_name=service_name, auth_system=os_auth_system,
            auth_plugin=auth_plugin, auth_token=auth_token,
            volume_service_name=volume_service_name,
            timings=args.timings, bypass_url=bypass_url,
            os_cache=os_cache, http_log_debug=args.debug,
            cacert=cacert, timeout=timeout,
            session=keystone_session, auth=keystone_auth)

        # Now check for the password/token of which pieces of the
        # identifying keyring key can come from the underlying client
        if must_auth:
            helper = SecretsHelper(args, self.cs.client)
            self.cs.client.keyring_saver = helper
            if (auth_plugin and auth_plugin.opts and
                    "os_password" not in auth_plugin.opts):
                use_pw = False
            else:
                use_pw = True

            tenant_id = helper.tenant_id
            # Allow commandline to override cache
            if not auth_token:
                auth_token = helper.auth_token
            if not management_url:
                management_url = helper.management_url
            if tenant_id and auth_token and management_url:
                self.cs.client.tenant_id = tenant_id
                self.cs.client.auth_token = auth_token
                self.cs.client.management_url = management_url
                self.cs.client.password_func = lambda: helper.password
            elif use_pw:
                # We're missing something, so auth with user/pass and save
                # the result in our helper.
                self.cs.client.password = helper.password

        try:
            # This does a couple of bits which are useful even if we've
            # got the token + service URL already. It exits fast in that case.
            if not utils.isunauthenticated(args.func):
                if not use_session:
                    # Only call authenticate() if Nova auth plugin is used.
                    # If keystone is used, authentication is handled as part
                    # of session.
                    self.cs.authenticate()
        except exc.Unauthorized:
            raise exc.CommandError(_("Invalid OpenStack Nova credentials."))
        except exc.AuthorizationFailure:
            raise exc.CommandError(_("Unable to authorize user"))

        args.func(self.cs, args)

        if args.timings:
            self._dump_timings(self.times + self.cs.get_timings())
Exemple #34
0
    def authenticate(self):
        if not self.auth_url:
            msg = _("Authentication requires 'auth_url', which should be "
                    "specified in '%s'") % self.__class__.__name__
            raise exceptions.AuthorizationFailure(msg)
        magic_tuple = netutils.urlsplit(self.auth_url)
        scheme, netloc, path, query, frag = magic_tuple
        port = magic_tuple.port
        if port is None:
            port = 80
        path_parts = path.split('/')
        for part in path_parts:
            if len(part) > 0 and part[0] == 'v':
                self.version = part
                break

        if self.auth_token and self.management_url:
            self._save_keys()
            return

        # TODO(sandy): Assume admin endpoint is 35357 for now.
        # Ideally this is going to have to be provided by the service catalog.
        new_netloc = netloc.replace(':%d' % port, ':%d' % (35357, ))
        admin_url = parse.urlunsplit((scheme, new_netloc, path, query, frag))

        auth_url = self.auth_url
        if self.version == "v2.0":  # FIXME(chris): This should be better.
            while auth_url:
                if not self.auth_system or self.auth_system == 'keystone':
                    auth_url = self._v2_auth(auth_url)
                else:
                    auth_url = self._plugin_auth(auth_url)

            # Are we acting on behalf of another user via an
            # existing token? If so, our actual endpoints may
            # be different than that of the admin token.
            if self.proxy_token:
                if self.bypass_url:
                    self.set_management_url(self.bypass_url)
                else:
                    self._fetch_endpoints_from_auth(admin_url)
                # Since keystone no longer returns the user token
                # with the endpoints any more, we need to replace
                # our service account token with the user token.
                self.auth_token = self.proxy_token
        else:
            try:
                while auth_url:
                    auth_url = self._v1_auth(auth_url)
            # In some configurations nova makes redirection to
            # v2.0 keystone endpoint. Also, new location does not contain
            # real endpoint, only hostname and port.
            except exceptions.AuthorizationFailure:
                if auth_url.find('v2.0') < 0:
                    auth_url = auth_url + '/v2.0'
                self._v2_auth(auth_url)

        if self.bypass_url:
            self.set_management_url(self.bypass_url)
        elif not self.management_url:
            raise exceptions.Unauthorized('Nova Client')

        self._save_keys()
Exemple #35
0
    def _boot(self,
              resource_url,
              response_key,
              name,
              image,
              flavor,
              meta=None,
              files=None,
              userdata=None,
              reservation_id=None,
              return_raw=False,
              min_count=None,
              max_count=None,
              security_groups=None,
              key_name=None,
              availability_zone=None,
              block_device_mapping=None,
              block_device_mapping_v2=None,
              nics=None,
              scheduler_hints=None,
              config_drive=None,
              admin_pass=None,
              disk_config=None,
              access_ip_v4=None,
              access_ip_v6=None,
              **kwargs):
        """
        Create (boot) a new server.
        """
        body = {
            "server": {
                "name": name,
                "imageRef": str(base.getid(image)) if image else '',
                "flavorRef": str(base.getid(flavor)),
            }
        }
        if userdata:
            if hasattr(userdata, 'read'):
                userdata = userdata.read()

            # NOTE(melwitt): Text file data is converted to bytes prior to
            # base64 encoding. The utf-8 encoding will fail for binary files.
            if six.PY3:
                try:
                    userdata = userdata.encode("utf-8")
                except AttributeError:
                    # In python 3, 'bytes' object has no attribute 'encode'
                    pass
            else:
                try:
                    userdata = encodeutils.safe_encode(userdata)
                except UnicodeDecodeError:
                    pass

            userdata_b64 = base64.b64encode(userdata).decode('utf-8')
            body["server"]["user_data"] = userdata_b64
        if meta:
            body["server"]["metadata"] = meta
        if reservation_id:
            body["server"]["reservation_id"] = reservation_id
        if key_name:
            body["server"]["key_name"] = key_name
        if scheduler_hints:
            body['os:scheduler_hints'] = scheduler_hints
        if config_drive:
            body["server"]["config_drive"] = config_drive
        if admin_pass:
            body["server"]["adminPass"] = admin_pass
        if not min_count:
            min_count = 1
        if not max_count:
            max_count = min_count
        body["server"]["min_count"] = min_count
        body["server"]["max_count"] = max_count

        if security_groups:
            body["server"]["security_groups"] = [{
                'name': sg
            } for sg in security_groups]

        # Files are a slight bit tricky. They're passed in a "personality"
        # list to the POST. Each item is a dict giving a file name and the
        # base64-encoded contents of the file. We want to allow passing
        # either an open file *or* some contents as files here.
        if files:
            personality = body['server']['personality'] = []
            for filepath, file_or_string in sorted(files.items(),
                                                   key=lambda x: x[0]):
                if hasattr(file_or_string, 'read'):
                    data = file_or_string.read()
                else:
                    data = file_or_string

                if six.PY3 and isinstance(data, str):
                    data = data.encode('utf-8')
                cont = base64.b64encode(data).decode('utf-8')
                personality.append({
                    'path': filepath,
                    'contents': cont,
                })

        if availability_zone:
            body["server"]["availability_zone"] = availability_zone

        # Block device mappings are passed as a list of dictionaries
        if block_device_mapping:
            body['server']['block_device_mapping'] = \
                self._parse_block_device_mapping(block_device_mapping)
        elif block_device_mapping_v2:
            # Following logic can't be removed because it will leaves
            # a valid boot with both --image and --block-device
            # failed , see bug 1433609 for more info
            if image:
                bdm_dict = {
                    'uuid': base.getid(image),
                    'source_type': 'image',
                    'destination_type': 'local',
                    'boot_index': 0,
                    'delete_on_termination': True
                }
                block_device_mapping_v2.insert(0, bdm_dict)
            body['server']['block_device_mapping_v2'] = block_device_mapping_v2

        if nics is not None:
            # NOTE(tr3buchet): nics can be an empty list
            all_net_data = []
            for nic_info in nics:
                net_data = {}
                # if value is empty string, do not send value in body
                if nic_info.get('net-id'):
                    net_data['uuid'] = nic_info['net-id']
                if (nic_info.get('v4-fixed-ip')
                        and nic_info.get('v6-fixed-ip')):
                    raise base.exceptions.CommandError(
                        _("Only one of 'v4-fixed-ip' and 'v6-fixed-ip' may be"
                          " provided."))
                elif nic_info.get('v4-fixed-ip'):
                    net_data['fixed_ip'] = nic_info['v4-fixed-ip']
                elif nic_info.get('v6-fixed-ip'):
                    net_data['fixed_ip'] = nic_info['v6-fixed-ip']
                if nic_info.get('port-id'):
                    net_data['port'] = nic_info['port-id']
                all_net_data.append(net_data)
            body['server']['networks'] = all_net_data

        if disk_config is not None:
            body['server']['OS-DCF:diskConfig'] = disk_config

        if access_ip_v4 is not None:
            body['server']['accessIPv4'] = access_ip_v4

        if access_ip_v6 is not None:
            body['server']['accessIPv6'] = access_ip_v6

        return self._create(resource_url,
                            body,
                            response_key,
                            return_raw=return_raw,
                            **kwargs)
Exemple #36
0
        cs.servers.live_migrate(server['uuid'], args.target_host,
                                args.block_migrate, **update_kwargs)
    except Exception as e:
        success = False
        error_message = _("Error while live migrating instance: %s") % e
    return HostEvacuateLiveResponse(server['uuid'],
                                    success,
                                    error_message)


@utils.arg('host', metavar='<host>', help='Name of host.')
@utils.arg(
    '--target-host',
    metavar='<target_host>',
    default=None,
    help=_('Name of target host.'))
@utils.arg(
    '--block-migrate',
    action='store_true',
    default=False,
    help=_('Enable block migration. (Default=False)'),
    start_version="2.0", end_version="2.24")
@utils.arg(
    '--block-migrate',
    action='store_true',
    default="auto",
    help=_('Enable block migration. (Default=auto)'),
    start_version="2.25")
@utils.arg(
    '--disk-over-commit',
    action='store_true',
Exemple #37
0
class OpenStackComputeShell(object):
    times = []

    def __init__(self):
        self.client_logger = None

    def _append_global_identity_args(self, parser, argv):
        # Register the CLI arguments that have moved to the session object.
        loading.register_session_argparse_arguments(parser)
        # Peek into argv to see if os-token was given,
        # in which case, the token auth plugin is what the user wants
        # else, we'll default to password
        default_auth_plugin = 'password'
        if "--os-token" in argv:
            default_auth_plugin = 'token'
        loading.register_auth_argparse_arguments(parser,
                                                 argv,
                                                 default=default_auth_plugin)

        parser.set_defaults(insecure=strutils.bool_from_string(
            utils.env('NOVACLIENT_INSECURE', default=False)))
        parser.set_defaults(os_auth_url=utils.env('OS_AUTH_URL', 'NOVA_URL'))

        parser.set_defaults(
            os_username=utils.env('OS_USERNAME', 'NOVA_USERNAME'))
        parser.set_defaults(
            os_password=utils.env('OS_PASSWORD', 'NOVA_PASSWORD'))
        parser.set_defaults(os_project_name=utils.env(
            'OS_PROJECT_NAME', 'OS_TENANT_NAME', 'NOVA_PROJECT_ID'))
        parser.set_defaults(
            os_project_id=utils.env('OS_PROJECT_ID', 'OS_TENANT_ID'))
        parser.set_defaults(
            os_project_domain_id=utils.env('OS_PROJECT_DOMAIN_ID'))
        parser.set_defaults(
            os_project_domain_name=utils.env('OS_PROJECT_DOMAIN_NAME'))
        parser.set_defaults(os_user_domain_id=utils.env('OS_USER_DOMAIN_ID'))
        parser.set_defaults(
            os_user_domain_name=utils.env('OS_USER_DOMAIN_NAME'))

    def get_base_parser(self, argv):
        parser = NovaClientArgumentParser(
            prog='nova',
            description=__doc__.strip(),
            epilog='See "nova help COMMAND" '
            'for help on a specific command.',
            add_help=False,
            formatter_class=OpenStackHelpFormatter,
        )

        # Global arguments
        parser.add_argument(
            '-h',
            '--help',
            action='store_true',
            help=argparse.SUPPRESS,
        )

        parser.add_argument('--version',
                            action='version',
                            version=novaclient.__version__)

        parser.add_argument('--debug',
                            default=False,
                            action='store_true',
                            help=_("Print debugging output."))

        parser.add_argument(
            '--os-cache',
            default=strutils.bool_from_string(
                utils.env('OS_CACHE', default=False), True),
            action='store_true',
            help=_("Use the auth token cache. Defaults to False if "
                   "env[OS_CACHE] is not set."))

        parser.add_argument('--timings',
                            default=False,
                            action='store_true',
                            help=_("Print call timing info."))

        parser.add_argument('--os-region-name',
                            metavar='<region-name>',
                            default=utils.env('OS_REGION_NAME',
                                              'NOVA_REGION_NAME'),
                            help=_('Defaults to env[OS_REGION_NAME].'))

        parser.add_argument('--service-type',
                            metavar='<service-type>',
                            help=_('Defaults to compute for most actions.'))

        parser.add_argument('--service-name',
                            metavar='<service-name>',
                            default=utils.env('NOVA_SERVICE_NAME'),
                            help=_('Defaults to env[NOVA_SERVICE_NAME].'))

        parser.add_argument('--os-endpoint-type',
                            metavar='<endpoint-type>',
                            dest='endpoint_type',
                            default=utils.env(
                                'NOVA_ENDPOINT_TYPE',
                                default=utils.env(
                                    'OS_ENDPOINT_TYPE',
                                    default=DEFAULT_NOVA_ENDPOINT_TYPE)),
                            help=_('Defaults to env[NOVA_ENDPOINT_TYPE], '
                                   'env[OS_ENDPOINT_TYPE] or ') +
                            DEFAULT_NOVA_ENDPOINT_TYPE + '.')

        parser.add_argument(
            '--os-compute-api-version',
            metavar='<compute-api-ver>',
            default=utils.env('OS_COMPUTE_API_VERSION',
                              default=DEFAULT_OS_COMPUTE_API_VERSION),
            help=_('Accepts X, X.Y (where X is major and Y is minor part) or '
                   '"X.latest", defaults to env[OS_COMPUTE_API_VERSION].'))

        parser.add_argument(
            '--os-endpoint-override',
            metavar='<bypass-url>',
            dest='endpoint_override',
            default=utils.env('OS_ENDPOINT_OVERRIDE',
                              'NOVACLIENT_ENDPOINT_OVERRIDE',
                              'NOVACLIENT_BYPASS_URL'),
            help=_("Use this API endpoint instead of the Service Catalog. "
                   "Defaults to env[OS_ENDPOINT_OVERRIDE]."))

        if osprofiler_profiler:
            parser.add_argument('--profile',
                                metavar='HMAC_KEY',
                                default=utils.env('OS_PROFILE'),
                                help='HMAC key to use for encrypting context '
                                'data for performance profiling of operation. '
                                'This key should be the value of the HMAC key '
                                'configured for the OSprofiler middleware in '
                                'nova; it is specified in the Nova '
                                'configuration file at "/etc/nova/nova.conf". '
                                'Without the key, profiling will not be '
                                'triggered even if OSprofiler is enabled on '
                                'the server side.')

        self._append_global_identity_args(parser, argv)

        return parser

    def get_subcommand_parser(self, version, do_help=False, argv=None):
        parser = self.get_base_parser(argv)

        self.subcommands = {}
        subparsers = parser.add_subparsers(metavar='<subcommand>')

        actions_module = importutils.import_module("novaclient.v%s.shell" %
                                                   version.ver_major)

        self._find_actions(subparsers, actions_module, version, do_help)
        self._find_actions(subparsers, self, version, do_help)

        for extension in self.extensions:
            self._find_actions(subparsers, extension.module, version, do_help)

        self._add_bash_completion_subparser(subparsers)

        return parser

    def _add_bash_completion_subparser(self, subparsers):
        subparser = subparsers.add_parser(
            'bash_completion',
            add_help=False,
            formatter_class=OpenStackHelpFormatter)
        self.subcommands['bash_completion'] = subparser
        subparser.set_defaults(func=self.do_bash_completion)

    def _find_actions(self, subparsers, actions_module, version, do_help):
        msg = _(" (Supported by API versions '%(start)s' - '%(end)s')")
        for attr in (a for a in dir(actions_module) if a.startswith('do_')):
            # I prefer to be hyphen-separated instead of underscores.
            command = attr[3:].replace('_', '-')
            callback = getattr(actions_module, attr)
            desc = callback.__doc__ or ''
            if hasattr(callback, "versioned"):
                additional_msg = ""
                subs = api_versions.get_substitutions(callback)
                if do_help:
                    additional_msg = msg % {
                        'start': subs[0].start_version.get_string(),
                        'end': subs[-1].end_version.get_string()
                    }
                    if version.is_latest():
                        additional_msg += HINT_HELP_MSG
                subs = [
                    versioned_method for versioned_method in subs
                    if version.matches(versioned_method.start_version,
                                       versioned_method.end_version)
                ]
                if subs:
                    # use the "latest" substitution
                    callback = subs[-1].func
                else:
                    # there is no proper versioned method
                    continue
                desc = callback.__doc__ or desc
                desc += additional_msg

            action_help = desc.strip()
            arguments = getattr(callback, 'arguments', [])

            subparser = subparsers.add_parser(
                command,
                help=action_help,
                description=desc,
                add_help=False,
                formatter_class=OpenStackHelpFormatter)
            subparser.add_argument(
                '-h',
                '--help',
                action='help',
                help=argparse.SUPPRESS,
            )
            self.subcommands[command] = subparser
            for (args, kwargs) in arguments:
                start_version = kwargs.get("start_version", None)
                if start_version:
                    start_version = api_versions.APIVersion(start_version)
                    end_version = kwargs.get("end_version", None)
                    if end_version:
                        end_version = api_versions.APIVersion(end_version)
                    else:
                        end_version = api_versions.APIVersion(
                            "%s.latest" % start_version.ver_major)
                    if do_help:
                        kwargs["help"] = kwargs.get(
                            "help", "") + (msg % {
                                "start": start_version.get_string(),
                                "end": end_version.get_string()
                            })
                    if not version.matches(start_version, end_version):
                        continue
                kw = kwargs.copy()
                kw.pop("start_version", None)
                kw.pop("end_version", None)
                subparser.add_argument(*args, **kw)
            subparser.set_defaults(func=callback)

    def setup_debugging(self, debug):
        if not debug:
            return

        streamformat = "%(levelname)s (%(module)s:%(lineno)d) %(message)s"
        # Set up the root logger to debug so that the submodules can
        # print debug messages
        logging.basicConfig(level=logging.DEBUG, format=streamformat)
        logging.getLogger('iso8601').setLevel(logging.WARNING)

        self.client_logger = logging.getLogger(client.__name__)
        ch = logging.StreamHandler()
        self.client_logger.setLevel(logging.DEBUG)
        self.client_logger.addHandler(ch)

    def main(self, argv):
        # Parse args once to find version and debug settings
        parser = self.get_base_parser(argv)
        (args, args_list) = parser.parse_known_args(argv)

        self.setup_debugging(args.debug)
        self.extensions = []
        do_help = args.help or not args_list or args_list[0] == 'help'

        # bash-completion should not require authentication
        skip_auth = do_help or ('bash-completion' in argv)

        if not args.os_compute_api_version:
            api_version = api_versions.get_api_version(
                DEFAULT_MAJOR_OS_COMPUTE_API_VERSION)
        else:
            api_version = api_versions.get_api_version(
                args.os_compute_api_version)

        auth_token = getattr(args, "os_token", None)

        os_username = getattr(args, "os_username", None)
        os_user_id = getattr(args, "os_user_id", None)
        os_password = None  # Fetched and set later as needed
        os_project_name = getattr(args, 'os_project_name',
                                  getattr(args, 'os_tenant_name', None))
        os_project_id = getattr(args, 'os_project_id',
                                getattr(args, 'os_tenant_id', None))
        os_auth_url = args.os_auth_url
        os_region_name = args.os_region_name

        if "v2.0" not in os_auth_url:
            # NOTE(andreykurilin): assume that keystone V3 is used and try to
            # be more user-friendly, i.e provide default values for domains
            if (not args.os_project_domain_id
                    and not args.os_project_domain_name):
                setattr(args, "os_project_domain_id", "default")

            # os_user_domain_id is redundant in case of Token auth type
            if not auth_token and (not args.os_user_domain_id
                                   and not args.os_user_domain_name):
                setattr(args, "os_user_domain_id", "default")

        os_project_domain_id = args.os_project_domain_id
        os_project_domain_name = args.os_project_domain_name
        os_user_domain_id = getattr(args, "os_user_domain_id", None)
        os_user_domain_name = getattr(args, "os_user_domain_name", None)

        endpoint_type = args.endpoint_type
        insecure = args.insecure
        service_type = args.service_type
        service_name = args.service_name
        endpoint_override = args.endpoint_override
        os_cache = args.os_cache
        cacert = args.os_cacert
        cert = args.os_cert
        timeout = args.timeout

        keystone_session = None
        keystone_auth = None

        if not endpoint_type:
            endpoint_type = DEFAULT_NOVA_ENDPOINT_TYPE

        # This allow users to use endpoint_type as (internal, public or admin)
        # just like other openstack clients (glance, cinder etc)
        if endpoint_type in ['internal', 'public', 'admin']:
            endpoint_type += 'URL'

        if not service_type:
            # Note(alex_xu): We need discover version first, so if there isn't
            # service type specified, we use default nova service type.
            service_type = DEFAULT_NOVA_SERVICE_TYPE

        # We should always auth unless we have a token and we're passing a
        # specific endpoint
        # Expired tokens are handled by client.py:_cs_request
        must_auth = not (auth_token and endpoint_override)

        # FIXME(usrleon): Here should be restrict for project id same as
        # for os_username or os_password but for compatibility it is not.
        if must_auth and not skip_auth:

            if not any([auth_token, os_username, os_user_id]):
                raise exc.CommandError(
                    _("You must provide a user name/id (via --os-username, "
                      "--os-user-id, env[OS_USERNAME] or env[OS_USER_ID]) or "
                      "an auth token (via --os-token)."))

            if not any([os_project_name, 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_ID]"
                      " or env[OS_PROJECT_NAME]. You may"
                      " use os-project and os-tenant"
                      " interchangeably."))

            if not os_auth_url:
                raise exc.CommandError(
                    _("You must provide an auth url "
                      "via either --os-auth-url or env[OS_AUTH_URL]."))

            # TODO(Shilpasd): need to provide support in python - novaclient
            # for required options for below default auth type plugins:
            # 1. v3oidcclientcredential
            # 2. v3oidcpassword
            # 3. v3oidcauthcode
            # 4. v3oidcaccesstoken
            # 5. v3oauth1
            # 6. v3fedkerb
            # 7. v3adfspassword
            # 8. v3samlpassword
            # 9. v3applicationcredential
            # TODO(Shilpasd): need to provide support in python - novaclient
            # for below extra keystoneauth auth type plugins:
            # We will need to add code to support discovering of versions
            # supported by the keystone service based on the auth_url similar
            # to the one supported by glanceclient.
            # 1. v3password
            # 2. v3token
            # 3. v3kerberos
            # 4. v3totp
            with utils.record_time(self.times, args.timings, 'auth_url',
                                   args.os_auth_url):
                keystone_session = (
                    loading.load_session_from_argparse_arguments(args))
                keystone_auth = (
                    loading.load_auth_from_argparse_arguments(args))

        if (not skip_auth and not any([os_project_name, 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_ID]"
                  " or env[OS_PROJECT_NAME]. You may"
                  " use os-project and os-tenant"
                  " interchangeably."))

        if not os_auth_url and not skip_auth:
            raise exc.CommandError(
                _("You must provide an auth url "
                  "via either --os-auth-url or env[OS_AUTH_URL]"))

        additional_kwargs = {}
        if osprofiler_profiler:
            additional_kwargs["profile"] = args.profile

        # This client is just used to discover api version. Version API needn't
        # microversion, so we just pass version 2 at here.
        self.cs = client.Client(api_versions.APIVersion("2.0"),
                                os_username,
                                os_password,
                                project_id=os_project_id,
                                project_name=os_project_name,
                                user_id=os_user_id,
                                auth_url=os_auth_url,
                                insecure=insecure,
                                region_name=os_region_name,
                                endpoint_type=endpoint_type,
                                extensions=self.extensions,
                                service_type=service_type,
                                service_name=service_name,
                                auth_token=auth_token,
                                timings=args.timings,
                                endpoint_override=endpoint_override,
                                os_cache=os_cache,
                                http_log_debug=args.debug,
                                cacert=cacert,
                                cert=cert,
                                timeout=timeout,
                                session=keystone_session,
                                auth=keystone_auth,
                                logger=self.client_logger,
                                project_domain_id=os_project_domain_id,
                                project_domain_name=os_project_domain_name,
                                user_domain_id=os_user_domain_id,
                                user_domain_name=os_user_domain_name,
                                **additional_kwargs)

        if not skip_auth:
            if not api_version.is_latest():
                if api_version > api_versions.APIVersion("2.0"):
                    if not api_version.matches(novaclient.API_MIN_VERSION,
                                               novaclient.API_MAX_VERSION):
                        raise exc.CommandError(
                            _("The specified version isn't supported by "
                              "client. The valid version range is '%(min)s' "
                              "to '%(max)s'") %
                            {
                                "min": novaclient.API_MIN_VERSION.get_string(),
                                "max": novaclient.API_MAX_VERSION.get_string()
                            })
            api_version = api_versions.discover_version(self.cs, api_version)

        # build available subcommands based on version
        self.extensions = client.discover_extensions(api_version)
        self._run_extension_hooks('__pre_parse_args__')

        subcommand_parser = self.get_subcommand_parser(api_version,
                                                       do_help=do_help,
                                                       argv=argv)
        self.parser = subcommand_parser

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

        args = subcommand_parser.parse_args(argv)
        self._run_extension_hooks('__post_parse_args__', args)

        # Short-circuit and deal with help right away.
        if 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

        if not args.service_type:
            service_type = (utils.get_service_type(args.func)
                            or DEFAULT_NOVA_SERVICE_TYPE)

        if utils.isunauthenticated(args.func):
            # NOTE(alex_xu): We need authentication for discover microversion.
            # But the subcommands may needn't it. If the subcommand needn't,
            # we clear the session arguments.
            keystone_session = None
            keystone_auth = None

        # Recreate client object with discovered version.
        self.cs = client.Client(api_version,
                                os_username,
                                os_password,
                                project_id=os_project_id,
                                project_name=os_project_name,
                                user_id=os_user_id,
                                auth_url=os_auth_url,
                                insecure=insecure,
                                region_name=os_region_name,
                                endpoint_type=endpoint_type,
                                extensions=self.extensions,
                                service_type=service_type,
                                service_name=service_name,
                                auth_token=auth_token,
                                timings=args.timings,
                                endpoint_override=endpoint_override,
                                os_cache=os_cache,
                                http_log_debug=args.debug,
                                cacert=cacert,
                                cert=cert,
                                timeout=timeout,
                                session=keystone_session,
                                auth=keystone_auth,
                                project_domain_id=os_project_domain_id,
                                project_domain_name=os_project_domain_name,
                                user_domain_id=os_user_domain_id,
                                user_domain_name=os_user_domain_name)

        args.func(self.cs, args)

        if osprofiler_profiler and args.profile:
            trace_id = osprofiler_profiler.get().get_base_id()
            print("To display trace use the command:\n\n"
                  "  osprofiler trace show --html %s " % trace_id)

        if args.timings:
            self._dump_timings(self.times + self.cs.get_timings())

    def _dump_timings(self, timings):
        class Tyme(object):
            def __init__(self, url, seconds):
                self.url = url
                self.seconds = seconds

        results = [Tyme(url, end - start) for url, start, end in timings]
        total = 0.0
        for tyme in results:
            total += tyme.seconds
        results.append(Tyme("Total", total))
        utils.print_list(results, ["url", "seconds"], sortby_index=None)

    def _run_extension_hooks(self, hook_type, *args, **kwargs):
        """Run hooks for all registered extensions."""
        for extension in self.extensions:
            extension.run_hooks(hook_type, *args, **kwargs)

    def do_bash_completion(self, _args):
        """
        Prints all of the commands and options to stdout so that the
        nova.bash_completion script doesn't have to hard code them.
        """
        commands = set()
        options = set()
        for sc_str, sc in self.subcommands.items():
            commands.add(sc_str)
            for option in sc._optionals._option_string_actions.keys():
                options.add(option)

        commands.remove('bash-completion')
        commands.remove('bash_completion')
        print(' '.join(commands | options))

    @utils.arg('command',
               metavar='<subcommand>',
               nargs='?',
               help=_('Display help for <subcommand>.'))
    def do_help(self, args):
        """
        Display help about this program or one of its subcommands.
        """
        if args.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()
Exemple #38
0
import novaclient
from novaclient import exceptions
from novaclient.i18n import _

LOG = logging.getLogger(__name__)
if not LOG.handlers:
    LOG.addHandler(logging.StreamHandler())

LEGACY_HEADER_NAME = "X-OpenStack-Nova-API-Version"
HEADER_NAME = "OpenStack-API-Version"
SERVICE_TYPE = "compute"

_SUBSTITUTIONS = {}

_type_error_msg = _("'%(other)s' should be an instance of '%(cls)s'")


class APIVersion(object):
    """This class represents an API Version Request.

    This class provides convenience methods for manipulation
    and comparison of version numbers that we need to do to
    implement microversions.
    """
    def __init__(self, version_str=None):
        """Create an API version object.

        :param version_str: String representation of APIVersionRequest.
                            Correct format is 'X.Y', where 'X' and 'Y'
                            are int values. None value should be used
Exemple #39
0
    def get_base_parser(self, argv):
        parser = NovaClientArgumentParser(
            prog='nova',
            description=__doc__.strip(),
            epilog='See "nova help COMMAND" '
            'for help on a specific command.',
            add_help=False,
            formatter_class=OpenStackHelpFormatter,
        )

        # Global arguments
        parser.add_argument(
            '-h',
            '--help',
            action='store_true',
            help=argparse.SUPPRESS,
        )

        parser.add_argument('--version',
                            action='version',
                            version=novaclient.__version__)

        parser.add_argument('--debug',
                            default=False,
                            action='store_true',
                            help=_("Print debugging output."))

        parser.add_argument(
            '--os-cache',
            default=strutils.bool_from_string(
                utils.env('OS_CACHE', default=False), True),
            action='store_true',
            help=_("Use the auth token cache. Defaults to False if "
                   "env[OS_CACHE] is not set."))

        parser.add_argument('--timings',
                            default=False,
                            action='store_true',
                            help=_("Print call timing info."))

        parser.add_argument('--os-region-name',
                            metavar='<region-name>',
                            default=utils.env('OS_REGION_NAME',
                                              'NOVA_REGION_NAME'),
                            help=_('Defaults to env[OS_REGION_NAME].'))

        parser.add_argument('--service-type',
                            metavar='<service-type>',
                            help=_('Defaults to compute for most actions.'))

        parser.add_argument('--service-name',
                            metavar='<service-name>',
                            default=utils.env('NOVA_SERVICE_NAME'),
                            help=_('Defaults to env[NOVA_SERVICE_NAME].'))

        parser.add_argument('--os-endpoint-type',
                            metavar='<endpoint-type>',
                            dest='endpoint_type',
                            default=utils.env(
                                'NOVA_ENDPOINT_TYPE',
                                default=utils.env(
                                    'OS_ENDPOINT_TYPE',
                                    default=DEFAULT_NOVA_ENDPOINT_TYPE)),
                            help=_('Defaults to env[NOVA_ENDPOINT_TYPE], '
                                   'env[OS_ENDPOINT_TYPE] or ') +
                            DEFAULT_NOVA_ENDPOINT_TYPE + '.')

        parser.add_argument(
            '--os-compute-api-version',
            metavar='<compute-api-ver>',
            default=utils.env('OS_COMPUTE_API_VERSION',
                              default=DEFAULT_OS_COMPUTE_API_VERSION),
            help=_('Accepts X, X.Y (where X is major and Y is minor part) or '
                   '"X.latest", defaults to env[OS_COMPUTE_API_VERSION].'))

        parser.add_argument(
            '--os-endpoint-override',
            metavar='<bypass-url>',
            dest='endpoint_override',
            default=utils.env('OS_ENDPOINT_OVERRIDE',
                              'NOVACLIENT_ENDPOINT_OVERRIDE',
                              'NOVACLIENT_BYPASS_URL'),
            help=_("Use this API endpoint instead of the Service Catalog. "
                   "Defaults to env[OS_ENDPOINT_OVERRIDE]."))

        if osprofiler_profiler:
            parser.add_argument('--profile',
                                metavar='HMAC_KEY',
                                default=utils.env('OS_PROFILE'),
                                help='HMAC key to use for encrypting context '
                                'data for performance profiling of operation. '
                                'This key should be the value of the HMAC key '
                                'configured for the OSprofiler middleware in '
                                'nova; it is specified in the Nova '
                                'configuration file at "/etc/nova/nova.conf". '
                                'Without the key, profiling will not be '
                                'triggered even if OSprofiler is enabled on '
                                'the server side.')

        self._append_global_identity_args(parser, argv)

        return parser
Exemple #40
0
    def __init__(self,
                 option_strings,
                 dest,
                 help=None,
                 real_action=None,
                 use=None,
                 **kwargs):
        """Initialize a ``DeprecatedAction`` instance.

        :param option_strings: The recognized option strings.
        :param dest: The attribute that will be set.
        :param help: Help text.  This will be updated to indicate the
                     deprecation, and if ``use`` is provided, that
                     text will be included as well.
        :param real_action: The actual action to invoke.  This is
                            interpreted the same way as the ``action``
                            parameter.
        :param use: Text explaining which option to use instead.
        """

        # Update the help text
        if not help:
            if use:
                help = _('Deprecated; %(use)s') % {'use': use}
            else:
                help = _('Deprecated')
        elif help != argparse.SUPPRESS:
            if use:
                help = _('%(help)s (Deprecated; %(use)s)') % {
                    'help': help,
                    'use': use,
                }
            else:
                help = _('%(help)s (Deprecated)') % {'help': help}

        # Initialize ourself appropriately
        super(DeprecatedAction, self).__init__(option_strings,
                                               dest,
                                               help=help,
                                               **kwargs)

        # 'emitted' tracks which warnings we've emitted
        self.emitted = set()
        self.use = use

        # Select the appropriate action
        if real_action == 'nothing':
            # NOTE(Vek): "nothing" is distinct from a real_action=None
            # argument.  When real_action=None, the argparse default
            # action of "store" is used; when real_action='nothing',
            # however, we explicitly inhibit doing anything with the
            # option
            self.real_action_args = False
            self.real_action = None
        elif real_action is None or isinstance(real_action, str):
            # Specified by string (or None); we have to have a parser
            # to look up the actual action, so defer to later
            self.real_action_args = (option_strings, dest, help, kwargs)
            self.real_action = real_action
        else:
            self.real_action_args = False
            self.real_action = real_action(option_strings,
                                           dest,
                                           help=help,
                                           **kwargs)
Exemple #41
0
    def _find_actions(self, subparsers, actions_module, version, do_help):
        msg = _(" (Supported by API versions '%(start)s' - '%(end)s')")
        for attr in (a for a in dir(actions_module) if a.startswith('do_')):
            # I prefer to be hyphen-separated instead of underscores.
            command = attr[3:].replace('_', '-')
            callback = getattr(actions_module, attr)
            desc = callback.__doc__ or ''
            if hasattr(callback, "versioned"):
                additional_msg = ""
                subs = api_versions.get_substitutions(callback)
                if do_help:
                    additional_msg = msg % {
                        'start': subs[0].start_version.get_string(),
                        'end': subs[-1].end_version.get_string()
                    }
                    if version.is_latest():
                        additional_msg += HINT_HELP_MSG
                subs = [
                    versioned_method for versioned_method in subs
                    if version.matches(versioned_method.start_version,
                                       versioned_method.end_version)
                ]
                if subs:
                    # use the "latest" substitution
                    callback = subs[-1].func
                else:
                    # there is no proper versioned method
                    continue
                desc = callback.__doc__ or desc
                desc += additional_msg

            action_help = desc.strip()
            arguments = getattr(callback, 'arguments', [])

            subparser = subparsers.add_parser(
                command,
                help=action_help,
                description=desc,
                add_help=False,
                formatter_class=OpenStackHelpFormatter)
            subparser.add_argument(
                '-h',
                '--help',
                action='help',
                help=argparse.SUPPRESS,
            )
            self.subcommands[command] = subparser
            for (args, kwargs) in arguments:
                start_version = kwargs.get("start_version", None)
                if start_version:
                    start_version = api_versions.APIVersion(start_version)
                    end_version = kwargs.get("end_version", None)
                    if end_version:
                        end_version = api_versions.APIVersion(end_version)
                    else:
                        end_version = api_versions.APIVersion(
                            "%s.latest" % start_version.ver_major)
                    if do_help:
                        kwargs["help"] = kwargs.get(
                            "help", "") + (msg % {
                                "start": start_version.get_string(),
                                "end": end_version.get_string()
                            })
                    if not version.matches(start_version, end_version):
                        continue
                kw = kwargs.copy()
                kw.pop("start_version", None)
                kw.pop("end_version", None)
                subparser.add_argument(*args, **kw)
            subparser.set_defaults(func=callback)
Exemple #42
0
    def main(self, argv):
        # Parse args once to find version and debug settings
        parser = self.get_base_parser(argv)
        (args, args_list) = parser.parse_known_args(argv)

        self.setup_debugging(args.debug)
        self.extensions = []
        do_help = args.help or not args_list or args_list[0] == 'help'

        # bash-completion should not require authentication
        skip_auth = do_help or ('bash-completion' in argv)

        if not args.os_compute_api_version:
            api_version = api_versions.get_api_version(
                DEFAULT_MAJOR_OS_COMPUTE_API_VERSION)
        else:
            api_version = api_versions.get_api_version(
                args.os_compute_api_version)

        auth_token = getattr(args, "os_token", None)

        os_username = getattr(args, "os_username", None)
        os_user_id = getattr(args, "os_user_id", None)
        os_password = None  # Fetched and set later as needed
        os_project_name = getattr(args, 'os_project_name',
                                  getattr(args, 'os_tenant_name', None))
        os_project_id = getattr(args, 'os_project_id',
                                getattr(args, 'os_tenant_id', None))
        os_auth_url = args.os_auth_url
        os_region_name = args.os_region_name

        if "v2.0" not in os_auth_url:
            # NOTE(andreykurilin): assume that keystone V3 is used and try to
            # be more user-friendly, i.e provide default values for domains
            if (not args.os_project_domain_id
                    and not args.os_project_domain_name):
                setattr(args, "os_project_domain_id", "default")

            # os_user_domain_id is redundant in case of Token auth type
            if not auth_token and (not args.os_user_domain_id
                                   and not args.os_user_domain_name):
                setattr(args, "os_user_domain_id", "default")

        os_project_domain_id = args.os_project_domain_id
        os_project_domain_name = args.os_project_domain_name
        os_user_domain_id = getattr(args, "os_user_domain_id", None)
        os_user_domain_name = getattr(args, "os_user_domain_name", None)

        endpoint_type = args.endpoint_type
        insecure = args.insecure
        service_type = args.service_type
        service_name = args.service_name
        endpoint_override = args.endpoint_override
        os_cache = args.os_cache
        cacert = args.os_cacert
        cert = args.os_cert
        timeout = args.timeout

        keystone_session = None
        keystone_auth = None

        if not endpoint_type:
            endpoint_type = DEFAULT_NOVA_ENDPOINT_TYPE

        # This allow users to use endpoint_type as (internal, public or admin)
        # just like other openstack clients (glance, cinder etc)
        if endpoint_type in ['internal', 'public', 'admin']:
            endpoint_type += 'URL'

        if not service_type:
            # Note(alex_xu): We need discover version first, so if there isn't
            # service type specified, we use default nova service type.
            service_type = DEFAULT_NOVA_SERVICE_TYPE

        # We should always auth unless we have a token and we're passing a
        # specific endpoint
        # Expired tokens are handled by client.py:_cs_request
        must_auth = not (auth_token and endpoint_override)

        # FIXME(usrleon): Here should be restrict for project id same as
        # for os_username or os_password but for compatibility it is not.
        if must_auth and not skip_auth:

            if not any([auth_token, os_username, os_user_id]):
                raise exc.CommandError(
                    _("You must provide a user name/id (via --os-username, "
                      "--os-user-id, env[OS_USERNAME] or env[OS_USER_ID]) or "
                      "an auth token (via --os-token)."))

            if not any([os_project_name, 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_ID]"
                      " or env[OS_PROJECT_NAME]. You may"
                      " use os-project and os-tenant"
                      " interchangeably."))

            if not os_auth_url:
                raise exc.CommandError(
                    _("You must provide an auth url "
                      "via either --os-auth-url or env[OS_AUTH_URL]."))

            # TODO(Shilpasd): need to provide support in python - novaclient
            # for required options for below default auth type plugins:
            # 1. v3oidcclientcredential
            # 2. v3oidcpassword
            # 3. v3oidcauthcode
            # 4. v3oidcaccesstoken
            # 5. v3oauth1
            # 6. v3fedkerb
            # 7. v3adfspassword
            # 8. v3samlpassword
            # 9. v3applicationcredential
            # TODO(Shilpasd): need to provide support in python - novaclient
            # for below extra keystoneauth auth type plugins:
            # We will need to add code to support discovering of versions
            # supported by the keystone service based on the auth_url similar
            # to the one supported by glanceclient.
            # 1. v3password
            # 2. v3token
            # 3. v3kerberos
            # 4. v3totp
            with utils.record_time(self.times, args.timings, 'auth_url',
                                   args.os_auth_url):
                keystone_session = (
                    loading.load_session_from_argparse_arguments(args))
                keystone_auth = (
                    loading.load_auth_from_argparse_arguments(args))

        if (not skip_auth and not any([os_project_name, 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_ID]"
                  " or env[OS_PROJECT_NAME]. You may"
                  " use os-project and os-tenant"
                  " interchangeably."))

        if not os_auth_url and not skip_auth:
            raise exc.CommandError(
                _("You must provide an auth url "
                  "via either --os-auth-url or env[OS_AUTH_URL]"))

        additional_kwargs = {}
        if osprofiler_profiler:
            additional_kwargs["profile"] = args.profile

        # This client is just used to discover api version. Version API needn't
        # microversion, so we just pass version 2 at here.
        self.cs = client.Client(api_versions.APIVersion("2.0"),
                                os_username,
                                os_password,
                                project_id=os_project_id,
                                project_name=os_project_name,
                                user_id=os_user_id,
                                auth_url=os_auth_url,
                                insecure=insecure,
                                region_name=os_region_name,
                                endpoint_type=endpoint_type,
                                extensions=self.extensions,
                                service_type=service_type,
                                service_name=service_name,
                                auth_token=auth_token,
                                timings=args.timings,
                                endpoint_override=endpoint_override,
                                os_cache=os_cache,
                                http_log_debug=args.debug,
                                cacert=cacert,
                                cert=cert,
                                timeout=timeout,
                                session=keystone_session,
                                auth=keystone_auth,
                                logger=self.client_logger,
                                project_domain_id=os_project_domain_id,
                                project_domain_name=os_project_domain_name,
                                user_domain_id=os_user_domain_id,
                                user_domain_name=os_user_domain_name,
                                **additional_kwargs)

        if not skip_auth:
            if not api_version.is_latest():
                if api_version > api_versions.APIVersion("2.0"):
                    if not api_version.matches(novaclient.API_MIN_VERSION,
                                               novaclient.API_MAX_VERSION):
                        raise exc.CommandError(
                            _("The specified version isn't supported by "
                              "client. The valid version range is '%(min)s' "
                              "to '%(max)s'") %
                            {
                                "min": novaclient.API_MIN_VERSION.get_string(),
                                "max": novaclient.API_MAX_VERSION.get_string()
                            })
            api_version = api_versions.discover_version(self.cs, api_version)

        # build available subcommands based on version
        self.extensions = client.discover_extensions(api_version)
        self._run_extension_hooks('__pre_parse_args__')

        subcommand_parser = self.get_subcommand_parser(api_version,
                                                       do_help=do_help,
                                                       argv=argv)
        self.parser = subcommand_parser

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

        args = subcommand_parser.parse_args(argv)
        self._run_extension_hooks('__post_parse_args__', args)

        # Short-circuit and deal with help right away.
        if 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

        if not args.service_type:
            service_type = (utils.get_service_type(args.func)
                            or DEFAULT_NOVA_SERVICE_TYPE)

        if utils.isunauthenticated(args.func):
            # NOTE(alex_xu): We need authentication for discover microversion.
            # But the subcommands may needn't it. If the subcommand needn't,
            # we clear the session arguments.
            keystone_session = None
            keystone_auth = None

        # Recreate client object with discovered version.
        self.cs = client.Client(api_version,
                                os_username,
                                os_password,
                                project_id=os_project_id,
                                project_name=os_project_name,
                                user_id=os_user_id,
                                auth_url=os_auth_url,
                                insecure=insecure,
                                region_name=os_region_name,
                                endpoint_type=endpoint_type,
                                extensions=self.extensions,
                                service_type=service_type,
                                service_name=service_name,
                                auth_token=auth_token,
                                timings=args.timings,
                                endpoint_override=endpoint_override,
                                os_cache=os_cache,
                                http_log_debug=args.debug,
                                cacert=cacert,
                                cert=cert,
                                timeout=timeout,
                                session=keystone_session,
                                auth=keystone_auth,
                                project_domain_id=os_project_domain_id,
                                project_domain_name=os_project_domain_name,
                                user_domain_id=os_user_domain_id,
                                user_domain_name=os_user_domain_name)

        args.func(self.cs, args)

        if osprofiler_profiler and args.profile:
            trace_id = osprofiler_profiler.get().get_base_id()
            print("To display trace use the command:\n\n"
                  "  osprofiler trace show --html %s " % trace_id)

        if args.timings:
            self._dump_timings(self.times + self.cs.get_timings())