Example #1
0
 def get_parser(self, prog_name):
     parser = super(CreateShareSnapshot, self).get_parser(prog_name)
     parser.add_argument(
         "share",
         metavar="<share>",
         help=_("Name or ID of the share to create snapshot of")
     )
     parser.add_argument(
         "--force",
         action='store_true',
         default=False,
         help=_("Optional flag to indicate whether to snapshot "
                "a share even if it's busy. (Default=False)")
     )
     parser.add_argument(
         "--name",
         metavar="<name>",
         default=None,
         help=_("Add a name to the snapshot (Optional).")
     )
     parser.add_argument(
         "--description",
         metavar="<description>",
         default=None,
         help=_("Add a description to the snapshot (Optional).")
     )
     return parser
Example #2
0
 def get_parser(self, prog_name):
     parser = super(ListShareService, self).get_parser(prog_name)
     parser.add_argument("--host",
                         metavar="<host>",
                         default=None,
                         help=_("Filter services by name of the host."))
     parser.add_argument(
         "--binary",
         metavar="<binary>",
         default=None,
         help=_("Filter services by the name of the service."))
     parser.add_argument("--status",
                         metavar="<status>",
                         default=None,
                         help=_("Filter results by status."))
     parser.add_argument("--state",
                         metavar="<state>",
                         default=None,
                         choices=['up', 'down'],
                         help=_("Filter results by state."))
     parser.add_argument(
         "--zone",
         metavar="<zone>",
         default=None,
         help=_("Filter services by their availability zone."))
     return parser
Example #3
0
 def get_parser(self, prog_name):
     parser = super(SetShareSnapshot, self).get_parser(prog_name)
     parser.add_argument(
         "snapshot",
         metavar="<snapshot>",
         help=_('Name or ID of the snapshot to set a property for')
     )
     parser.add_argument(
         "--name",
         metavar="<name>",
         default=None,
         help=_("Set a name to the snapshot.")
     )
     parser.add_argument(
         "--description",
         metavar="<description>",
         default=None,
         help=_("Set a description to the snapshot.")
     )
     parser.add_argument(
         "--status",
         metavar="<status>",
         choices=['available', 'error', 'creating', 'deleting',
                  'manage_starting', 'manage_error',
                  'unmanage_starting', 'unmanage_error',
                  'error_deleting'],
         help=_("Assign a status to the snapshot (Admin only). "
                "Options include : available, error, creating, "
                "deleting, manage_starting, manage_error, "
                "unmanage_starting, unmanage_error, error_deleting.")
     )
     return parser
Example #4
0
    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share
        result = 0

        for share in parsed_args.share:
            try:
                share_obj = apiutils.find_resource(share_client.shares, share)
                share_client.shares.unmanage(share_obj)

                if parsed_args.wait:
                    # 'wait_for_delete' checks that the resource is no longer
                    # retrievable with the given 'res_id' so we can use it
                    # to check that the share has been abandoned
                    if not oscutils.wait_for_delete(
                            manager=share_client.shares, res_id=share_obj.id):
                        result += 1

            except Exception as e:
                result += 1
                LOG.error(
                    _("Failed to abandon share with "
                      "name or ID '%(share)s': %(e)s"), {
                          'share': share,
                          'e': e
                      })

        if result > 0:
            total = len(parsed_args.share)
            msg = (_("Failed to abandon %(result)s out of %(total)s shares.") %
                   {
                       'result': result,
                       'total': total
                   })
            raise exceptions.CommandError(msg)
Example #5
0
 def get_parser(self, prog_name):
     parser = super(ShareAccessAllow, self).get_parser(prog_name)
     parser.add_argument('share',
                         metavar="<share>",
                         help=_('Name or ID of the NAS share to modify.'))
     parser.add_argument(
         'access_type',
         metavar="<access_type>",
         help=_('Access rule type (only "ip", "user" (user or group), '
                '"cert" or "cephx" are supported).'))
     parser.add_argument('access_to',
                         metavar="<access_to>",
                         help=_('Value that defines access.'))
     # metadata --> properties in osc
     parser.add_argument(
         '--properties',
         type=str,
         nargs='*',
         metavar='<key=value>',
         help=_('Space separated list of key=value pairs of properties. '
                'OPTIONAL: Default=None. '
                'Available only for API microversion >= 2.45.'),
     )
     parser.add_argument(
         '--access-level',
         metavar="<access_level>",
         type=str,
         default=None,
         choices=['rw', 'ro'],
         help=_('Share access level ("rw" and "ro" access levels '
                'are supported). Defaults to rw.'))
     return parser
Example #6
0
    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share
        share = apiutils.find_resource(share_client.shares, parsed_args.share)
        share_size = share._info['size']
        new_size = parsed_args.new_size

        if share_size > new_size:
            try:
                share_client.shares.shrink(share, new_size)
            except Exception as e:
                raise exceptions.CommandError(_("Share resize failed: %s" % e))
        elif share_size < new_size:
            force = False
            if parsed_args.force:
                if share_client.api_version < api_versions.APIVersion("2.64"):
                    raise exceptions.CommandError(
                        'args force is available only for '
                        'API microversion >= 2.64')
                force = True
            try:
                if force:
                    share_client.shares.extend(share, new_size, force=force)
                else:
                    share_client.shares.extend(share, new_size)
            except Exception as e:
                raise exceptions.CommandError(_("Share resize failed: %s" % e))
        else:
            raise exceptions.CommandError(
                _("Share size is already at %s GiBs" % new_size))
        if parsed_args.wait:
            if not oscutils.wait_for_status(status_f=share_client.shares.get,
                                            res_id=share.id,
                                            success_status=['available']):
                raise exceptions.CommandError(
                    _("Share not available after resize attempt."))
Example #7
0
    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share
        result = 0

        for share in parsed_args.shares:
            try:
                share_obj = apiutils.find_resource(share_client.shares, share)
                share_group_id = (share_group_id
                                  if parsed_args.share_group else None)
                if parsed_args.force:
                    share_client.shares.force_delete(share_obj)
                else:
                    share_client.shares.delete(share_obj, share_group_id)
                if parsed_args.wait:
                    if not oscutils.wait_for_delete(
                            manager=share_client.shares, res_id=share_obj.id):
                        result += 1

            except Exception as exc:
                result += 1
                LOG.error(
                    _("Failed to delete share with "
                      "name or ID '%(share)s': %(e)s"), {
                          'share': share,
                          'e': exc
                      })

        if result > 0:
            total = len(parsed_args.shares)
            msg = (_("%(result)s of %(total)s shares failed "
                     "to delete.") % {
                         'result': result,
                         'total': total
                     })
            raise exceptions.CommandError(msg)
Example #8
0
 def get_parser(self, prog_name):
     parser = super(SetShare, self).get_parser(prog_name)
     parser.add_argument('share',
                         metavar="<share>",
                         help=_('Share to modify (name or ID)'))
     # 'metadata' --> 'properties'
     parser.add_argument(
         "--property",
         metavar="<key=value>",
         default={},
         action=parseractions.KeyValueAction,
         help=_("Set a property to this share "
                "(repeat option to set multiple properties)"),
     )
     parser.add_argument('--name',
                         metavar="<name>",
                         default=None,
                         help=_('New share name. (Default=None)'))
     parser.add_argument('--description',
                         metavar='<description>',
                         default=None,
                         help=_('New share description. (Default=None)'))
     parser.add_argument(
         '--public',
         metavar='<public>',
         help=_(
             'Level of visibility for share. '
             'Defines whether other tenants are able to see it or not. '))
     return parser
    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share
        identity_client = self.app.client_manager.identity
        result = 0

        share_group_type = apiutils.find_resource(
            share_client.share_group_types, parsed_args.share_group_type)

        for project in parsed_args.projects:
            try:
                project_obj = identity_common.find_project(
                    identity_client, project, parsed_args.project_domain)

                share_client.share_group_type_access.add_project_access(
                    share_group_type, project_obj.id)
            except Exception as e:
                result += 1
                LOG.error(_(
                    "Failed to allow access for project '%(project)s' "
                    "to share group type with name or ID "
                    "'%(share_group_type)s': %(e)s"),
                    {'project': project,
                     'share_group_type': share_group_type, 'e': e})

        if result > 0:
            total = len(parsed_args.projects)
            msg = (_("Failed to allow access to "
                     "%(result)s of %(total)s projects") % {'result': result,
                                                            'total': total})
            raise exceptions.CommandError(msg)
Example #10
0
    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share
        result = 0

        for snapshot in parsed_args.snapshot:
            try:
                snapshot_obj = utils.find_resource(
                    share_client.share_snapshots,
                    snapshot)
                if parsed_args.force:
                    share_client.share_snapshots.force_delete(
                        snapshot_obj)
                else:
                    share_client.share_snapshots.delete(
                        snapshot_obj)
            except Exception as e:
                result += 1
                LOG.error(_(
                    "Failed to delete snapshot with "
                    "name or ID '%(snapshot)s': %(e)s"),
                    {'snapshot': snapshot, 'e': e})

        if result > 0:
            total = len(parsed_args.snapshot)
            msg = (_("%(result)s of %(total)s snapshots failed "
                   "to delete.") % {'result': result, 'total': total})
            raise exceptions.CommandError(msg)
Example #11
0
def _validate_requested_version(requested_version,
                                server_start_version,
                                server_end_version):
    """Validates the requested version.

    Checks 'requested_version' is within the min/max range supported by the
    server. If 'requested_version' is not within range then attempts to
    downgrade to 'server_end_version'. Otherwise an UnsupportedVersion
    exception is thrown.

    :param requested_version: requestedversion represented by APIVersion obj
    :param server_start_version: APIVersion object representing server min
    :param server_end_version: APIVersion object representing server max
    """
    valid_version = requested_version
    if not requested_version.matches(server_start_version, server_end_version):
        if server_end_version <= requested_version:
            if (manilaclient.API_MIN_VERSION <= server_end_version and
                    server_end_version <= manilaclient.API_MAX_VERSION):
                msg = _("Requested version %(requested_version)s is "
                        "not supported. Downgrading requested version "
                        "to %(server_end_version)s.")
                LOG.debug(msg, {
                    "requested_version": requested_version,
                    "server_end_version": server_end_version})
            valid_version = server_end_version
        else:
            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 valid_version
def _validate_server_version(server_start_version, server_end_version):
    """Validates the server version.

    Checks that the 'server_end_version' is greater than the minimum version
    supported by the client. Then checks that the 'server_start_version' is
    less than the maximum version supported by the client.

    :param server_start_version:
    :param server_end_version:
    :return:
    """
    if manilaclient.API_MIN_VERSION > server_end_version:
        raise exceptions.UnsupportedVersion(
            _("Server's version is too old. The client's 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': manilaclient.API_MIN_VERSION.get_string(),
                  'client_max': manilaclient.API_MAX_VERSION.get_string(),
                  'server_min': server_start_version.get_string(),
                  'server_max': server_end_version.get_string()})
    elif manilaclient.API_MAX_VERSION < server_start_version:
        raise exceptions.UnsupportedVersion(
            _("Server's version is too new. The client's 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': manilaclient.API_MIN_VERSION.get_string(),
                  'client_max': manilaclient.API_MAX_VERSION.get_string(),
                  'server_min': server_start_version.get_string(),
                  'server_max': server_end_version.get_string()})
Example #13
0
    def take_action(self, parsed_args):
        share_client = self.app.client_manager.share
        result = 0

        for share_type in parsed_args.share_types:
            try:
                share_type_obj = apiutils.find_resource(
                    share_client.share_types, share_type)

                share_client.share_types.delete(share_type_obj)
            except Exception as e:
                result += 1
                LOG.error(
                    _("Failed to delete share type with "
                      "name or ID '%(share_type)s': %(e)s"), {
                          'share_type': share_type,
                          'e': e
                      })

        if result > 0:
            total = len(parsed_args.share_types)
            msg = (_("%(result)s of %(total)s share types failed "
                     "to delete.") % {
                         'result': result,
                         'total': total
                     })
            raise exceptions.CommandError(msg)
Example #14
0
 def get_parser(self, prog_name):
     parser = super(ListShareType, self).get_parser(prog_name)
     parser.add_argument(
         '--all',
         action='store_true',
         default=False,
         help=_('Display all share types whatever public or private. '
                'Default=False. (Admin only)'),
     )
     parser.add_argument(
         '--extra-specs',
         type=str,
         nargs='*',
         metavar='<key=value>',
         default=None,
         help=_('Filter share types with extra specs (key=value). '
                'Available only for API microversion >= 2.43. '
                'OPTIONAL: Default=None.'),
     )
     parser.add_argument(
         '--columns',
         metavar='<columns>',
         help=_('Comma separated list of columns to be displayed '
                'example --columns "id,name".'),
     )
     return parser
Example #15
0
def _validate_server_version(server_start_version, server_end_version):
    """Validates the server version.

    Checks that the 'server_end_version' is greater than the minimum version
    supported by the client. Then checks that the 'server_start_version' is
    less than the maximum version supported by the client.

    :param server_start_version:
    :param server_end_version:
    :return:
    """
    if manilaclient.API_MIN_VERSION > server_end_version:
        raise exceptions.UnsupportedVersion(
            _("Server's version is too old. The client's 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': manilaclient.API_MIN_VERSION.get_string(),
                  'client_max': manilaclient.API_MAX_VERSION.get_string(),
                  'server_min': server_start_version.get_string(),
                  'server_max': server_end_version.get_string()})
    elif manilaclient.API_MAX_VERSION < server_start_version:
        raise exceptions.UnsupportedVersion(
            _("Server's version is too new. The client's 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': manilaclient.API_MIN_VERSION.get_string(),
                  'client_max': manilaclient.API_MAX_VERSION.get_string(),
                  'server_min': server_start_version.get_string(),
                  'server_max': server_end_version.get_string()})
def _validate_requested_version(requested_version,
                                server_start_version,
                                server_end_version):
    """Validates the requested version.

    Checks 'requested_version' is within the min/max range supported by the
    server. If 'requested_version' is not within range then attempts to
    downgrade to 'server_end_version'. Otherwise an UnsupportedVersion
    exception is thrown.

    :param requested_version: requestedversion represented by APIVersion obj
    :param server_start_version: APIVersion object representing server min
    :param server_end_version: APIVersion object representing server max
    """
    valid_version = requested_version
    if not requested_version.matches(server_start_version, server_end_version):
        if server_end_version <= requested_version:
            if (manilaclient.API_MIN_VERSION <= server_end_version and
                    server_end_version <= manilaclient.API_MAX_VERSION):
                msg = _("Requested version %(requested_version)s is "
                        "not supported. Downgrading requested version "
                        "to %(server_end_version)s.")
                LOG.debug(msg, {
                    "requested_version": requested_version,
                    "server_end_version": server_end_version})
            valid_version = server_end_version
        else:
            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 valid_version
 def get_parser(self, prog_name):
     parser = super(CreateShareNetworkSubnet, self).get_parser(prog_name)
     parser.add_argument("share_network",
                         metavar="<share-network>",
                         help=_("Share network name or ID."))
     parser.add_argument(
         "--neutron-net-id",
         metavar="<neutron-net-id>",
         default=None,
         help=_("Neutron network ID. Used to set up network for share "
                "servers (optional). Should be defined together with "
                "'--neutron-subnet-id'."))
     parser.add_argument(
         "--neutron-subnet-id",
         metavar="<neutron-subnet-id>",
         default=None,
         help=_("Neutron subnet ID. Used to set up network for share "
                "servers (optional). Should be defined together with "
                "'--neutron-net-id' to which this subnet belongs to. "))
     parser.add_argument(
         "--availability-zone",
         metavar="<availability-zone>",
         default=None,
         help=_("Optional availability zone that the subnet is available "
                "within (Default=None). If None, the subnet will be "
                "considered as being available across all availability "
                "zones."))
     return parser
Example #18
0
def find_resource(manager, name_or_id, **find_args):
    """Look for resource in a given manager.

    Used as a helper for the _find_* methods.
    Example:

    .. code-block:: python

        def _find_hypervisor(cs, hypervisor):
            #Get a hypervisor by name or ID.
            return cliutils.find_resource(cs.hypervisors, hypervisor)
    """
    # first 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_decode(name_or_id)

        if uuidutils.is_uuid_like(tmp_id):
            return manager.get(tmp_id)
    except (TypeError, ValueError, exceptions.NotFound):
        pass

    # for str id which is not uuid
    if getattr(manager, 'is_alphanum_id_allowed', False):
        try:
            return manager.get(name_or_id)
        except 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 %(name)s with a name or "
                    "ID of '%(name_or_id)s' exists.") % \
                {"name": manager.resource_class.__name__.lower(),
                 "name_or_id": name_or_id}
            raise exceptions.CommandError(msg)
    except exceptions.NoUniqueMatch:
        msg = _("Multiple %(name)s matches found for "
                "'%(name_or_id)s', use an ID to be more specific.") % \
            {"name": manager.resource_class.__name__.lower(),
             "name_or_id": name_or_id}
        raise exceptions.CommandError(msg)
Example #19
0
 def get_parser(self, prog_name):
     parser = super(ShareAccessDeny, self).get_parser(prog_name)
     parser.add_argument('share',
                         metavar="<share>",
                         help=_('Name or ID of the NAS share to modify.'))
     parser.add_argument('id',
                         metavar="<id>",
                         help=_('ID of the access rule to be deleted.'))
     return parser
 def get_parser(self, prog_name):
     parser = super(ShowShareNetworkSubnet, self).get_parser(prog_name)
     parser.add_argument("share_network",
                         metavar="<share-network>",
                         help=_("Share network name or ID."))
     parser.add_argument("share_network_subnet",
                         metavar="<share-network-subnet>",
                         help=_("ID of share network subnet to show."))
     return parser
Example #21
0
 def get_parser(self, prog_name):
     parser = super(ShareTypeAccessAllow, self).get_parser(prog_name)
     parser.add_argument('share_type',
                         metavar="<share_type>",
                         help=_("Share type name or ID to add access to"))
     parser.add_argument('project_id',
                         metavar="<project_id>",
                         help=_("Project ID to add share type access for"))
     return parser
Example #22
0
 def get_parser(self, prog_name):
     parser = super(ShareExportLocationShow, self).get_parser(prog_name)
     parser.add_argument('share',
                         metavar="<share>",
                         help=_('Name or ID of share'))
     parser.add_argument('export_location',
                         metavar="<export-location>",
                         help=_('ID of the share export location'))
     return parser
Example #23
0
 def get_parser(self, prog_name):
     parser = super(AbandonShare, self).get_parser(prog_name)
     parser.add_argument('share',
                         metavar="<share>",
                         nargs="+",
                         help=_('Name or ID of the share(s)'))
     parser.add_argument("--wait",
                         action='store_true',
                         help=_("Wait until share is abandoned"))
     return parser
 def get_parser(self, prog_name):
     parser = super(ShareReplicaShowExportLocation,
                    self).get_parser(prog_name)
     parser.add_argument("replica",
                         metavar="<replica>",
                         help=_("ID of the share replica."))
     parser.add_argument("export_location",
                         metavar="<export-location>",
                         help=_("ID of the share replica export location."))
     return parser
Example #25
0
 def get_parser(self, prog_name):
     parser = super(AdoptShare, self).get_parser(prog_name)
     parser.add_argument('service_host',
                         metavar="<service-host>",
                         help=_('Service host: some.host@driver#pool.'))
     parser.add_argument(
         'protocol',
         metavar="<protocol>",
         help=_('Protocol of the share to manage, such as NFS or CIFS.'))
     parser.add_argument('export_path',
                         metavar="<export-path>",
                         help=_(
                             'Share export path, NFS share such as: '
                             '10.0.0.1:/example_path, CIFS share such as: '
                             '\\\\10.0.0.1\\example_cifs_share.'))
     parser.add_argument('--name',
                         metavar="<name>",
                         default=None,
                         help=_('Optional share name. (Default=None)'))
     parser.add_argument(
         '--description',
         metavar="<description>",
         default=None,
         help=_('Optional share description. (Default=None)'))
     parser.add_argument(
         '--share-type',
         metavar="<share-type>",
         default=None,
         help=_('Optional share type assigned to share. (Default=None)'))
     parser.add_argument(
         '--driver-options',
         type=str,
         nargs='*',
         metavar='<key=value>',
         default=None,
         help=_(
             'Optional driver options as key=value pairs (Default=None).'))
     parser.add_argument(
         '--public',
         action='store_true',
         help=_('Level of visibility for share. Defines whether other '
                'projects are able to see it or not. Available only for '
                'microversion >= 2.8. (Default=False)'))
     parser.add_argument(
         '--share-server-id',
         metavar="<share-server-id>",
         help=_('Share server associated with share when using a share '
                'type with "driver_handles_share_servers" extra_spec '
                'set to True. Available only for microversion >= 2.49. '
                '(Default=None)'))
     parser.add_argument("--wait",
                         action='store_true',
                         help=_("Wait until share is adopted"))
     return parser
 def get_parser(self, prog_name):
     parser = super(DeleteShareNetworkSubnet, self).get_parser(prog_name)
     parser.add_argument("share_network",
                         metavar="<share-network>",
                         help=_("Share network name or ID."))
     parser.add_argument(
         "share_network_subnet",
         metavar="<share-network-subnet>",
         nargs="+",
         help=_("ID(s) of share network subnet(s) to be deleted."))
     return parser
Example #27
0
 def get_parser(self, prog_name):
     parser = super(ShareInstanceShowExportLocation,
                    self).get_parser(prog_name)
     parser.add_argument("instance",
                         metavar="<instance>",
                         help=_("Name or ID of the share instance"))
     parser.add_argument(
         "export_location",
         metavar="<export_location>",
         help=_("ID of the share instance export location."))
     return parser
 def get_parser(self, prog_name):
     parser = super(ShareInstanceDelete, self).get_parser(prog_name)
     parser.add_argument('instance',
                         metavar="<instance>",
                         nargs="+",
                         help=_('ID of the share instance to delete.'))
     parser.add_argument("--wait",
                         action='store_true',
                         default=False,
                         help=_("Wait for share instance deletion."))
     return parser
Example #29
0
 def get_parser(self, prog_name):
     parser = super(AbandonShareSnapshot, self).get_parser(prog_name)
     parser.add_argument(
         "snapshot",
         metavar="<snapshot>",
         nargs='+',
         help=_("Name or ID of the snapshot(s) to be abandoned."))
     parser.add_argument("--wait",
                         action='store_true',
                         help=_("Wait until share snapshot is abandoned"))
     return parser
Example #30
0
 def get_parser(self, prog_name):
     parser = super(ShareSnapshotShowExportLocation,
                    self).get_parser(prog_name)
     parser.add_argument("snapshot",
                         metavar="<snapshot>",
                         help=_("Name or ID of the share snapshot."))
     parser.add_argument(
         "export_location",
         metavar="<export-location>",
         help=_("ID of the share snapshot export location."))
     return parser
Example #31
0
 def get_parser(self, prog_name):
     parser = super(DeleteShareSnapshot, self).get_parser(prog_name)
     parser.add_argument("snapshot",
                         metavar="<snapshot>",
                         nargs="+",
                         help=_("Name or ID of the snapshot(s) to delete"))
     parser.add_argument(
         "--force",
         action='store_true',
         default=False,
         help=_("Delete the snapshot(s) ignoring the current state."))
     return parser
Example #32
0
 def get_parser(self, prog_name):
     parser = super(ShareSnapshotAccessDeny, self).get_parser(prog_name)
     parser.add_argument(
         "snapshot",
         metavar="<snapshot>",
         help=_("Name or ID of the share snapshot to deny access to."))
     parser.add_argument(
         "id",
         metavar="<id>",
         nargs="+",
         help=_("ID(s) of the access rule(s) to be deleted."))
     return parser
Example #33
0
    def find(self, base_url=None, **kwargs):
        """Find a single item with attributes matching ``**kwargs``.

        :param base_url: if provided, the generated URL will be appended to it
        """
        kwargs = self._filter_kwargs(kwargs)

        rl = self._list(
            '%(base_url)s%(query)s' % {
                'base_url': self.build_url(base_url=base_url, **kwargs),
                'query': '?%s' % utils.safe_urlencode(kwargs) if kwargs else ''
            },
            self.collection_key)
        num = len(rl)

        if num == 0:
            msg = _("No %(name)s matching %(args)s.") % {
                'name': self.resource_class.__name__,
                'args': kwargs
            }
            raise exceptions.NotFound(404, msg)
        elif num > 1:
            raise exceptions.NoUniqueMatch
        else:
            return rl[0]
    def matches(self, min_version, max_version):
        """Determines if version is within a range.

        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 check_version_deprecated(api_version):
    """Returns True if API version is deprecated."""
    if api_version == manilaclient.API_DEPRECATED_VERSION:
        msg = _("Client version '%(version)s' is deprecated.") % {
            "version": api_version.get_string()}
        warnings.warn(msg)
        return True
    return False
        def substitution(obj, *args, **kwargs):
            methods = get_versioned_methods(name, obj.api_version)

            if not methods:
                raise exceptions.UnsupportedVersion(
                    _("API version '%(version)s' is not supported on "
                      "'%(method)s' method.") % {
                        "version": obj.api_version.get_string(),
                        "method": name,
                    })

            method = max(methods, key=lambda f: f.start_version)

            return method.func(obj, *args, **kwargs)
def check_version_matches_min_max(api_version):
    """Returns True if the API version is within the supported range."""
    if (not api_version.matches(
            manilaclient.API_MIN_VERSION,
            manilaclient.API_MAX_VERSION)):
        msg = _("Invalid client version '%(version)s'. "
                "Current version range is '%(min)s' through "
                " '%(max)s'") % {
            "version": api_version.get_string(),
            "min": manilaclient.API_MIN_VERSION.get_string(),
            "max": manilaclient.API_MAX_VERSION.get_string()}
        warnings.warn(msg)
        return False
    return True
    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)$", version_str)
            if match:
                self.ver_major = int(match.group(1))
                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)
Example #39
0
def print_list(objs, fields, formatters=None, sortby_index=0,
               mixed_case_fields=None, field_labels=None):
    """Print a list or objects as a table, one row per object.

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

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

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

    if six.PY3:
        print(encodeutils.safe_encode(pt.get_string(**kwargs)).decode())
    else:
        print(encodeutils.safe_encode(pt.get_string(**kwargs)))
Example #40
0
    def find(self, **kwargs):
        """Find a single item with attributes matching ``**kwargs``.

        This isn't very efficient: it loads the entire list then filters on
        the Python side.
        """
        matches = self.findall(**kwargs)
        num_matches = len(matches)
        if num_matches == 0:
            msg = _("No %(name)s matching %(args)s.") % {
                'name': self.resource_class.__name__,
                'args': kwargs
            }
            raise exceptions.NotFound(msg)
        elif num_matches > 1:
            raise exceptions.NoUniqueMatch()
        else:
            return matches[0]
Example #41
0
def find_resource(manager, name_or_id, **find_args):
    """Look for resource in a given manager.

    Used as a helper for the _find_* methods.
    Example:

    .. code-block:: python

        def _find_hypervisor(cs, hypervisor):
            #Get a hypervisor by name or ID.
            return cliutils.find_resource(cs.hypervisors, hypervisor)
    """
    # first 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:
        if six.PY2:
            tmp_id = encodeutils.safe_encode(name_or_id)
        else:
            tmp_id = encodeutils.safe_decode(name_or_id)

        if uuidutils.is_uuid_like(tmp_id):
            return manager.get(tmp_id)
    except (TypeError, ValueError, exceptions.NotFound):
        pass

    # for str id which is not uuid
    if getattr(manager, 'is_alphanum_id_allowed', False):
        try:
            return manager.get(name_or_id)
        except 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 %(name)s with a name or "
                    "ID of '%(name_or_id)s' exists.") % \
                {"name": manager.resource_class.__name__.lower(),
                 "name_or_id": name_or_id}
            raise exceptions.CommandError(msg)
    except exceptions.NoUniqueMatch:
        msg = _("Multiple %(name)s matches found for "
                "'%(name_or_id)s', use an ID to be more specific.") % \
            {"name": manager.resource_class.__name__.lower(),
             "name_or_id": name_or_id}
        raise exceptions.CommandError(msg)
 def __init__(self, auth_system):
     super(AuthSystemNotFound, self).__init__(
         _("AuthSystemNotFound: %r") % auth_system)
     self.auth_system = auth_system
 def __init__(self, opt_names):
     super(AuthPluginOptionsMissing, self).__init__(
         _("Authentication failed. Missing options: %s") %
         ", ".join(opt_names))
     self.opt_names = opt_names
 def __init__(self, endpoints=None):
     super(AmbiguousEndpoints, self).__init__(
         _("AmbiguousEndpoints: %r") % endpoints)
     self.endpoints = endpoints
 def get_string(self):
     """String representation of an APIVersion object."""
     if self.is_null():
         raise ValueError(
             _("Null APIVersion cannot be converted to string."))
     return "%s.%s" % (self.ver_major, self.ver_minor)
Example #46
0
 def __init__(self, missing):
     self.missing = missing
     msg = _("Missing arguments: %s") % ", ".join(missing)
     super(MissingArgs, self).__init__(msg)