2013-09-20 03:31:42 +08:00
|
|
|
# Copyright (c) 2013 OpenStack Foundation
|
2013-05-06 18:25:26 -05:00
|
|
|
# All Rights Reserved.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
|
|
|
# not use this file except in compliance with the License. You may obtain
|
|
|
|
# a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
|
|
|
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
|
|
|
# License for the specific language governing permissions and limitations
|
|
|
|
# under the License.
|
|
|
|
|
2013-06-09 21:24:10 -05:00
|
|
|
from __future__ import print_function
|
2016-10-17 14:39:33 +02:00
|
|
|
import collections
|
2013-06-09 21:24:10 -05:00
|
|
|
|
2012-05-21 16:32:35 -04:00
|
|
|
import os
|
2014-02-14 13:42:58 -06:00
|
|
|
import pkg_resources
|
2012-05-21 16:32:35 -04:00
|
|
|
import sys
|
|
|
|
import uuid
|
|
|
|
|
2017-08-01 15:16:22 -04:00
|
|
|
import prettytable
|
2013-06-11 13:22:56 -05:00
|
|
|
import six
|
2016-09-29 16:00:10 +08:00
|
|
|
from six.moves.urllib import parse
|
2012-05-21 16:32:35 -04:00
|
|
|
|
2013-07-15 16:25:40 +00:00
|
|
|
from cinderclient import exceptions
|
2015-11-23 10:40:05 -05:00
|
|
|
from oslo_utils import encodeutils
|
2012-05-21 16:32:35 -04:00
|
|
|
|
|
|
|
|
|
|
|
def arg(*args, **kwargs):
|
|
|
|
"""Decorator for CLI args."""
|
|
|
|
def _decorator(func):
|
|
|
|
add_arg(func, *args, **kwargs)
|
|
|
|
return func
|
|
|
|
return _decorator
|
|
|
|
|
|
|
|
|
2016-10-17 14:39:33 +02:00
|
|
|
def exclusive_arg(group_name, *args, **kwargs):
|
|
|
|
"""Decorator for CLI mutually exclusive args."""
|
|
|
|
def _decorator(func):
|
|
|
|
required = kwargs.pop('required', None)
|
|
|
|
add_exclusive_arg(func, group_name, required, *args, **kwargs)
|
|
|
|
return func
|
|
|
|
return _decorator
|
|
|
|
|
|
|
|
|
2012-05-21 16:32:35 -04:00
|
|
|
def env(*vars, **kwargs):
|
|
|
|
"""
|
|
|
|
returns the first environment variable set
|
|
|
|
if none are non-empty, defaults to '' or keyword arg default
|
|
|
|
"""
|
|
|
|
for v in vars:
|
|
|
|
value = os.environ.get(v, None)
|
|
|
|
if value:
|
|
|
|
return value
|
|
|
|
return kwargs.get('default', '')
|
|
|
|
|
|
|
|
|
|
|
|
def add_arg(f, *args, **kwargs):
|
|
|
|
"""Bind CLI arguments to a shell.py `do_foo` function."""
|
|
|
|
|
|
|
|
if not hasattr(f, 'arguments'):
|
|
|
|
f.arguments = []
|
|
|
|
|
|
|
|
# NOTE(sirp): avoid dups that can occur when the module is shared across
|
|
|
|
# tests.
|
|
|
|
if (args, kwargs) not in f.arguments:
|
2013-11-25 18:08:01 +08:00
|
|
|
# Because of the semantics of decorator composition if we just append
|
2012-05-21 16:32:35 -04:00
|
|
|
# to the options list positional options will appear to be backwards.
|
|
|
|
f.arguments.insert(0, (args, kwargs))
|
|
|
|
|
|
|
|
|
2016-10-17 14:39:33 +02:00
|
|
|
def add_exclusive_arg(f, group_name, required, *args, **kwargs):
|
|
|
|
"""Bind CLI mutally exclusive arguments to a shell.py `do_foo` function."""
|
|
|
|
|
|
|
|
if not hasattr(f, 'exclusive_args'):
|
|
|
|
f.exclusive_args = collections.defaultdict(list)
|
|
|
|
# Default required to False
|
|
|
|
f.exclusive_args['__required__'] = collections.defaultdict(bool)
|
|
|
|
|
|
|
|
# NOTE(sirp): avoid dups that can occur when the module is shared across
|
|
|
|
# tests.
|
|
|
|
if (args, kwargs) not in f.exclusive_args[group_name]:
|
|
|
|
# Because of the semantics of decorator composition if we just append
|
|
|
|
# to the options list positional options will appear to be backwards.
|
|
|
|
f.exclusive_args[group_name].insert(0, (args, kwargs))
|
|
|
|
if required is not None:
|
|
|
|
f.exclusive_args['__required__'][group_name] = required
|
|
|
|
|
|
|
|
|
2012-05-21 16:32:35 -04:00
|
|
|
def unauthenticated(f):
|
|
|
|
"""
|
|
|
|
Adds 'unauthenticated' attribute to decorated function.
|
|
|
|
Usage:
|
|
|
|
@unauthenticated
|
|
|
|
def mymethod(f):
|
|
|
|
...
|
|
|
|
"""
|
|
|
|
f.unauthenticated = True
|
|
|
|
return f
|
|
|
|
|
|
|
|
|
|
|
|
def isunauthenticated(f):
|
|
|
|
"""
|
|
|
|
Checks to see if the function is marked as not requiring authentication
|
|
|
|
with the @unauthenticated decorator. Returns True if decorator is
|
|
|
|
set to True, False otherwise.
|
|
|
|
"""
|
|
|
|
return getattr(f, 'unauthenticated', False)
|
|
|
|
|
|
|
|
|
2013-06-21 07:15:11 -05:00
|
|
|
def _print(pt, order):
|
|
|
|
if sys.version_info >= (3, 0):
|
|
|
|
print(pt.get_string(sortby=order))
|
|
|
|
else:
|
2015-11-23 10:40:05 -05:00
|
|
|
print(encodeutils.safe_encode(pt.get_string(sortby=order)))
|
2013-06-21 07:15:11 -05:00
|
|
|
|
|
|
|
|
2015-06-09 11:37:54 +08:00
|
|
|
def print_list(objs, fields, exclude_unavailable=False, formatters=None,
|
|
|
|
sortby_index=0):
|
2014-12-15 22:52:18 +00:00
|
|
|
'''Prints a list of objects.
|
|
|
|
|
|
|
|
@param objs: Objects to print
|
|
|
|
@param fields: Fields on each object to be printed
|
2015-06-09 11:37:54 +08:00
|
|
|
@param exclude_unavailable: Boolean to decide if unavailable fields are
|
|
|
|
removed
|
2014-12-15 22:52:18 +00:00
|
|
|
@param formatters: Custom field formatters
|
|
|
|
@param sortby_index: Results sorted against the key in the fields list at
|
|
|
|
this index; if None then the object order is not
|
|
|
|
altered
|
|
|
|
'''
|
2014-07-01 16:16:49 +08:00
|
|
|
formatters = formatters or {}
|
2012-05-21 16:32:35 -04:00
|
|
|
mixed_case_fields = ['serverId']
|
2015-06-09 11:37:54 +08:00
|
|
|
removed_fields = []
|
|
|
|
rows = []
|
2012-05-21 16:32:35 -04:00
|
|
|
|
|
|
|
for o in objs:
|
|
|
|
row = []
|
|
|
|
for field in fields:
|
2015-06-09 11:37:54 +08:00
|
|
|
if field in removed_fields:
|
|
|
|
continue
|
2012-05-21 16:32:35 -04:00
|
|
|
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(' ', '_')
|
2016-02-24 13:46:39 -06:00
|
|
|
if isinstance(o, dict) and field in o:
|
2013-09-26 21:48:17 +00:00
|
|
|
data = o[field]
|
|
|
|
else:
|
2015-06-09 11:37:54 +08:00
|
|
|
if not hasattr(o, field_name) and exclude_unavailable:
|
|
|
|
removed_fields.append(field)
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
data = getattr(o, field_name, '')
|
2015-03-16 23:26:12 +05:30
|
|
|
if data is None:
|
|
|
|
data = '-'
|
2015-07-21 12:50:14 +08:00
|
|
|
if isinstance(data, six.string_types) and "\r" in data:
|
|
|
|
data = data.replace("\r", " ")
|
2012-05-21 16:32:35 -04:00
|
|
|
row.append(data)
|
2015-06-09 11:37:54 +08:00
|
|
|
rows.append(row)
|
|
|
|
|
|
|
|
for f in removed_fields:
|
|
|
|
fields.remove(f)
|
|
|
|
|
|
|
|
pt = prettytable.PrettyTable((f for f in fields), caching=False)
|
2016-05-19 22:59:26 -04:00
|
|
|
pt.align = 'l'
|
2015-06-09 11:37:54 +08:00
|
|
|
for row in rows:
|
2016-02-18 00:45:10 +05:30
|
|
|
count = 0
|
|
|
|
# Converts unicode values in dictionary to string
|
|
|
|
for part in row:
|
|
|
|
count = count + 1
|
|
|
|
if isinstance(part, dict):
|
|
|
|
part = unicode_key_value_to_string(part)
|
|
|
|
row[count - 1] = part
|
2012-05-21 16:32:35 -04:00
|
|
|
pt.add_row(row)
|
|
|
|
|
2014-12-15 22:52:18 +00:00
|
|
|
if sortby_index is None:
|
|
|
|
order_by = None
|
|
|
|
else:
|
|
|
|
order_by = fields[sortby_index]
|
2013-06-21 07:15:11 -05:00
|
|
|
_print(pt, order_by)
|
2012-05-21 16:32:35 -04:00
|
|
|
|
|
|
|
|
2016-07-27 10:13:36 -04:00
|
|
|
def _encode(src):
|
|
|
|
"""remove extra 'u' in PY2."""
|
2018-06-09 20:49:05 +08:00
|
|
|
if six.PY2 and isinstance(src, six.text_type):
|
2016-07-27 10:13:36 -04:00
|
|
|
return src.encode('utf-8')
|
|
|
|
return src
|
|
|
|
|
|
|
|
|
|
|
|
def unicode_key_value_to_string(src):
|
2016-02-18 00:45:10 +05:30
|
|
|
"""Recursively converts dictionary keys to strings."""
|
2016-07-27 10:13:36 -04:00
|
|
|
if isinstance(src, dict):
|
|
|
|
return dict((_encode(k),
|
|
|
|
_encode(unicode_key_value_to_string(v)))
|
|
|
|
for k, v in src.items())
|
|
|
|
if isinstance(src, list):
|
|
|
|
return [unicode_key_value_to_string(l) for l in src]
|
|
|
|
return _encode(src)
|
2016-02-18 00:45:10 +05:30
|
|
|
|
|
|
|
|
2016-09-29 16:00:10 +08:00
|
|
|
def build_query_param(params, sort=False):
|
|
|
|
"""parse list to url query parameters"""
|
|
|
|
|
2018-09-13 16:45:45 -06:00
|
|
|
if not params:
|
|
|
|
return ""
|
|
|
|
|
2016-09-29 16:00:10 +08:00
|
|
|
if not sort:
|
|
|
|
param_list = list(params.items())
|
|
|
|
else:
|
|
|
|
param_list = list(sorted(params.items()))
|
|
|
|
|
|
|
|
query_string = parse.urlencode(
|
2018-09-13 16:45:45 -06:00
|
|
|
[(k, v) for (k, v) in param_list if v not in (None, '')])
|
|
|
|
|
|
|
|
# urllib's parse library used to adhere to RFC 2396 until
|
|
|
|
# python 3.7. The library moved from RFC 2396 to RFC 3986
|
|
|
|
# for quoting URL strings in python 3.7 and '~' is now
|
|
|
|
# included in the set of reserved characters. [1]
|
|
|
|
#
|
|
|
|
# Below ensures "~" is never encoded. See LP 1784728 [2] for more details.
|
|
|
|
# [1] https://docs.python.org/3/library/urllib.parse.html#url-quoting
|
|
|
|
# [2] https://bugs.launchpad.net/python-cinderclient/+bug/1784728
|
|
|
|
query_string = query_string.replace("%7E=", "~=")
|
|
|
|
|
2016-09-29 16:00:10 +08:00
|
|
|
if query_string:
|
|
|
|
query_string = "?%s" % (query_string,)
|
|
|
|
|
|
|
|
return query_string
|
|
|
|
|
|
|
|
|
2017-05-12 15:35:20 +08:00
|
|
|
def _pretty_format_dict(data_dict):
|
|
|
|
formatted_data = []
|
|
|
|
|
|
|
|
for k in sorted(data_dict):
|
|
|
|
formatted_data.append("%s : %s" % (k, data_dict[k]))
|
|
|
|
|
|
|
|
return "\n".join(formatted_data)
|
|
|
|
|
|
|
|
|
2016-02-18 00:45:10 +05:30
|
|
|
def print_dict(d, property="Property", formatters=None):
|
2012-05-21 16:32:35 -04:00
|
|
|
pt = prettytable.PrettyTable([property, 'Value'], caching=False)
|
2016-05-19 22:59:26 -04:00
|
|
|
pt.align = 'l'
|
2016-02-18 00:45:10 +05:30
|
|
|
formatters = formatters or {}
|
|
|
|
|
2016-12-01 20:18:26 +08:00
|
|
|
for r in d.items():
|
2015-07-21 12:50:14 +08:00
|
|
|
r = list(r)
|
2016-02-18 00:45:10 +05:30
|
|
|
|
|
|
|
if r[0] in formatters:
|
|
|
|
r[1] = unicode_key_value_to_string(r[1])
|
2017-05-12 15:35:20 +08:00
|
|
|
if isinstance(r[1], dict):
|
|
|
|
r[1] = _pretty_format_dict(r[1])
|
2015-07-21 12:50:14 +08:00
|
|
|
if isinstance(r[1], six.string_types) and "\r" in r[1]:
|
|
|
|
r[1] = r[1].replace("\r", " ")
|
|
|
|
pt.add_row(r)
|
2013-06-21 07:15:11 -05:00
|
|
|
_print(pt, property)
|
2012-05-21 16:32:35 -04:00
|
|
|
|
|
|
|
|
2017-02-10 16:39:33 +08:00
|
|
|
def find_resource(manager, name_or_id, **kwargs):
|
2012-05-21 16:32:35 -04:00
|
|
|
"""Helper for the _find_* methods."""
|
2017-02-10 16:39:33 +08:00
|
|
|
is_group = kwargs.pop('is_group', False)
|
2012-05-21 16:32:35 -04:00
|
|
|
# first try to get entity as integer id
|
|
|
|
try:
|
|
|
|
if isinstance(name_or_id, int) or name_or_id.isdigit():
|
2017-02-10 16:39:33 +08:00
|
|
|
if is_group:
|
|
|
|
return manager.get(int(name_or_id), **kwargs)
|
2012-05-21 16:32:35 -04:00
|
|
|
return manager.get(int(name_or_id))
|
|
|
|
except exceptions.NotFound:
|
|
|
|
pass
|
2015-03-06 13:13:05 +01:00
|
|
|
else:
|
|
|
|
# now try to get entity as uuid
|
|
|
|
try:
|
|
|
|
uuid.UUID(name_or_id)
|
2017-02-10 16:39:33 +08:00
|
|
|
if is_group:
|
|
|
|
return manager.get(name_or_id, **kwargs)
|
2015-03-06 13:13:05 +01:00
|
|
|
return manager.get(name_or_id)
|
|
|
|
except (ValueError, exceptions.NotFound):
|
|
|
|
pass
|
2012-05-21 16:32:35 -04:00
|
|
|
|
2013-06-21 07:15:11 -05:00
|
|
|
if sys.version_info <= (3, 0):
|
2015-11-23 10:40:05 -05:00
|
|
|
name_or_id = encodeutils.safe_decode(name_or_id)
|
2013-06-21 07:15:11 -05:00
|
|
|
|
2012-05-21 16:32:35 -04:00
|
|
|
try:
|
|
|
|
try:
|
2015-04-28 13:12:48 +03:00
|
|
|
resource = getattr(manager, 'resource_class', None)
|
|
|
|
name_attr = resource.NAME_ATTR if resource else 'name'
|
2017-02-10 16:39:33 +08:00
|
|
|
if is_group:
|
|
|
|
kwargs[name_attr] = name_or_id
|
|
|
|
return manager.find(**kwargs)
|
2015-04-28 13:12:48 +03:00
|
|
|
return manager.find(**{name_attr: name_or_id})
|
2012-05-21 16:32:35 -04:00
|
|
|
except exceptions.NotFound:
|
|
|
|
pass
|
|
|
|
|
2015-04-28 13:12:48 +03:00
|
|
|
# finally try to find entity by human_id
|
2012-05-21 16:32:35 -04:00
|
|
|
try:
|
2017-02-10 16:39:33 +08:00
|
|
|
if is_group:
|
|
|
|
kwargs['human_id'] = name_or_id
|
|
|
|
return manager.find(**kwargs)
|
2015-04-28 13:12:48 +03:00
|
|
|
return manager.find(human_id=name_or_id)
|
2012-05-21 16:32:35 -04:00
|
|
|
except exceptions.NotFound:
|
2015-03-06 13:13:05 +01:00
|
|
|
msg = "No %s with a name or ID of '%s' exists." % \
|
|
|
|
(manager.resource_class.__name__.lower(), name_or_id)
|
|
|
|
raise exceptions.CommandError(msg)
|
2015-04-28 13:12:48 +03:00
|
|
|
|
2012-05-21 16:32:35 -04:00
|
|
|
except exceptions.NoUniqueMatch:
|
|
|
|
msg = ("Multiple %s matches found for '%s', use an ID to be more"
|
|
|
|
" specific." % (manager.resource_class.__name__.lower(),
|
|
|
|
name_or_id))
|
|
|
|
raise exceptions.CommandError(msg)
|
|
|
|
|
|
|
|
|
2013-09-18 16:44:51 +09:00
|
|
|
def find_volume(cs, volume):
|
|
|
|
"""Get a volume by name or ID."""
|
|
|
|
return find_resource(cs.volumes, volume)
|
|
|
|
|
|
|
|
|
2012-05-21 16:32:35 -04:00
|
|
|
def safe_issubclass(*args):
|
|
|
|
"""Like issubclass, but will just return False if not a class."""
|
|
|
|
|
|
|
|
try:
|
|
|
|
if issubclass(*args):
|
|
|
|
return True
|
|
|
|
except TypeError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2014-02-14 13:42:58 -06:00
|
|
|
def _load_entry_point(ep_name, name=None):
|
|
|
|
"""Try to load the entry point ep_name that matches name."""
|
|
|
|
for ep in pkg_resources.iter_entry_points(ep_name, name=name):
|
|
|
|
try:
|
|
|
|
return ep.load()
|
|
|
|
except (ImportError, pkg_resources.UnknownExtra, AttributeError):
|
|
|
|
continue
|
2016-03-31 09:20:29 -06:00
|
|
|
|
|
|
|
|
2016-04-05 15:45:28 -06:00
|
|
|
def get_function_name(func):
|
|
|
|
if six.PY2:
|
|
|
|
if hasattr(func, "im_class"):
|
|
|
|
return "%s.%s" % (func.im_class, func.__name__)
|
|
|
|
else:
|
|
|
|
return "%s.%s" % (func.__module__, func.__name__)
|
|
|
|
else:
|
|
|
|
return "%s.%s" % (func.__module__, func.__qualname__)
|