2013-08-15 16:56:22 -07:00
|
|
|
# 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-05-09 09:29:02 -07:00
|
|
|
import getpass
|
2012-11-12 19:40:21 +00:00
|
|
|
import hashlib
|
2014-02-28 11:22:26 +10:00
|
|
|
import logging
|
2013-05-09 09:29:02 -07:00
|
|
|
import sys
|
2011-10-25 16:50:08 -07:00
|
|
|
|
2015-01-08 17:29:47 -06:00
|
|
|
from oslo_utils import encodeutils
|
2015-06-07 11:20:44 -05:00
|
|
|
from oslo_utils import timeutils
|
2016-01-15 16:03:14 -08:00
|
|
|
from positional import positional # noqa
|
2011-10-25 16:50:08 -07:00
|
|
|
import prettytable
|
2013-10-10 13:20:37 -04:00
|
|
|
import six
|
2011-10-25 16:50:08 -07:00
|
|
|
|
|
|
|
from keystoneclient import exceptions
|
|
|
|
|
|
|
|
|
2014-02-28 11:22:26 +10:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2011-10-25 16:50:08 -07:00
|
|
|
# Decorator for cli-args
|
|
|
|
def arg(*args, **kwargs):
|
|
|
|
def _decorator(func):
|
2013-11-25 18:30:28 +08:00
|
|
|
# Because of the semantics of decorator composition if we just append
|
2011-10-25 16:50:08 -07:00
|
|
|
# to the options list positional options will appear to be backwards.
|
|
|
|
func.__dict__.setdefault('arguments', []).insert(0, (args, kwargs))
|
|
|
|
return func
|
|
|
|
return _decorator
|
|
|
|
|
|
|
|
|
|
|
|
def pretty_choice_list(l):
|
|
|
|
return ', '.join("'%s'" % i for i in l)
|
|
|
|
|
|
|
|
|
2012-12-10 19:18:02 +09:00
|
|
|
def print_list(objs, fields, formatters={}, order_by=None):
|
2013-04-29 11:22:04 +02:00
|
|
|
pt = prettytable.PrettyTable([f for f in fields],
|
|
|
|
caching=False, print_empty=False)
|
2011-10-25 16:50:08 -07:00
|
|
|
pt.aligns = ['l' for f in fields]
|
|
|
|
|
|
|
|
for o in objs:
|
|
|
|
row = []
|
|
|
|
for field in fields:
|
|
|
|
if field in formatters:
|
|
|
|
row.append(formatters[field](o))
|
|
|
|
else:
|
|
|
|
field_name = field.lower().replace(' ', '_')
|
|
|
|
data = getattr(o, field_name, '')
|
2012-06-26 11:08:24 +02:00
|
|
|
if data is None:
|
|
|
|
data = ''
|
2011-10-25 16:50:08 -07:00
|
|
|
row.append(data)
|
|
|
|
pt.add_row(row)
|
|
|
|
|
2012-12-10 19:18:02 +09:00
|
|
|
if order_by is None:
|
|
|
|
order_by = fields[0]
|
2014-10-14 17:49:17 -04:00
|
|
|
encoded = encodeutils.safe_encode(pt.get_string(sortby=order_by))
|
2014-05-05 17:39:40 -05:00
|
|
|
if six.PY3:
|
|
|
|
encoded = encoded.decode()
|
|
|
|
print(encoded)
|
2011-10-25 16:50:08 -07:00
|
|
|
|
|
|
|
|
2012-09-20 23:54:20 +00:00
|
|
|
def _word_wrap(string, max_length=0):
|
2014-05-02 16:12:20 +02:00
|
|
|
"""wrap long strings to be no longer than max_length."""
|
2012-09-20 23:54:20 +00:00
|
|
|
if max_length <= 0:
|
|
|
|
return string
|
|
|
|
return '\n'.join([string[i:i + max_length] for i in
|
2012-09-29 14:59:35 -07:00
|
|
|
range(0, len(string), max_length)])
|
2012-09-20 23:54:20 +00:00
|
|
|
|
|
|
|
|
|
|
|
def print_dict(d, wrap=0):
|
|
|
|
"""pretty table prints dictionaries.
|
|
|
|
|
|
|
|
Wrap values to max_length wrap if wrap>0
|
|
|
|
"""
|
2013-04-29 11:22:04 +02:00
|
|
|
pt = prettytable.PrettyTable(['Property', 'Value'],
|
|
|
|
caching=False, print_empty=False)
|
2011-10-25 16:50:08 -07:00
|
|
|
pt.aligns = ['l', 'l']
|
2013-10-10 13:20:37 -04:00
|
|
|
for (prop, value) in six.iteritems(d):
|
2012-06-26 11:08:24 +02:00
|
|
|
if value is None:
|
|
|
|
value = ''
|
2012-09-20 23:54:20 +00:00
|
|
|
value = _word_wrap(value, max_length=wrap)
|
2012-06-29 16:27:25 -04:00
|
|
|
pt.add_row([prop, value])
|
2014-10-14 17:49:17 -04:00
|
|
|
encoded = encodeutils.safe_encode(pt.get_string(sortby='Property'))
|
2014-05-05 17:39:40 -05:00
|
|
|
if six.PY3:
|
|
|
|
encoded = encoded.decode()
|
|
|
|
print(encoded)
|
2011-10-25 16:50:08 -07:00
|
|
|
|
|
|
|
|
|
|
|
def find_resource(manager, name_or_id):
|
|
|
|
"""Helper for the _find_* methods."""
|
|
|
|
|
2014-04-27 18:01:12 -05:00
|
|
|
# first try the entity as a string
|
2011-10-25 16:50:08 -07:00
|
|
|
try:
|
|
|
|
return manager.get(name_or_id)
|
2013-06-11 12:00:14 -04:00
|
|
|
except (exceptions.NotFound):
|
2011-10-25 16:50:08 -07:00
|
|
|
pass
|
|
|
|
|
|
|
|
# finally try to find entity by name
|
|
|
|
try:
|
2013-12-16 15:52:24 +01:00
|
|
|
if isinstance(name_or_id, six.binary_type):
|
2013-09-06 17:24:05 +08:00
|
|
|
name_or_id = name_or_id.decode('utf-8', 'strict')
|
2011-10-25 16:50:08 -07:00
|
|
|
return manager.find(name=name_or_id)
|
|
|
|
except exceptions.NotFound:
|
2012-02-29 11:31:10 +08:00
|
|
|
msg = ("No %s with a name or ID of '%s' exists." %
|
|
|
|
(manager.resource_class.__name__.lower(), name_or_id))
|
2011-10-25 16:50:08 -07:00
|
|
|
raise exceptions.CommandError(msg)
|
2013-01-17 18:11:27 +09: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))
|
2013-08-18 22:17:21 -07:00
|
|
|
raise exceptions.CommandError(msg)
|
2011-12-28 00:23:31 -06:00
|
|
|
|
|
|
|
|
|
|
|
def unauthenticated(f):
|
2012-09-29 15:28:08 -07:00
|
|
|
"""Adds 'unauthenticated' attribute to decorated function.
|
|
|
|
|
|
|
|
Usage::
|
2011-12-28 00:23:31 -06:00
|
|
|
|
|
|
|
@unauthenticated
|
|
|
|
def mymethod(f):
|
|
|
|
...
|
|
|
|
"""
|
|
|
|
f.unauthenticated = True
|
|
|
|
return f
|
|
|
|
|
|
|
|
|
|
|
|
def isunauthenticated(f):
|
2016-01-13 13:03:51 -08:00
|
|
|
"""Check if function requires authentication.
|
|
|
|
|
|
|
|
Checks to see if the function is marked as not requiring authentication
|
2013-08-04 23:10:16 +02:00
|
|
|
with the @unauthenticated decorator.
|
|
|
|
|
|
|
|
Returns True if decorator is set to True, False otherwise.
|
2011-12-28 00:23:31 -06:00
|
|
|
"""
|
|
|
|
return getattr(f, 'unauthenticated', False)
|
2012-02-21 15:02:41 -08:00
|
|
|
|
|
|
|
|
2014-04-08 19:50:09 -05:00
|
|
|
def hash_signed_token(signed_text, mode='md5'):
|
|
|
|
hash_ = hashlib.new(mode)
|
2012-11-12 19:40:21 +00:00
|
|
|
hash_.update(signed_text)
|
|
|
|
return hash_.hexdigest()
|
2013-05-09 09:29:02 -07:00
|
|
|
|
|
|
|
|
2015-04-15 09:36:10 +10:00
|
|
|
def prompt_user_password():
|
|
|
|
"""Prompt user for a password
|
|
|
|
|
|
|
|
Prompt for a password if stdin is a tty.
|
|
|
|
"""
|
|
|
|
password = None
|
|
|
|
|
|
|
|
# If stdin is a tty, try prompting for the password
|
|
|
|
if hasattr(sys.stdin, 'isatty') and sys.stdin.isatty():
|
|
|
|
# Check for Ctl-D
|
|
|
|
try:
|
|
|
|
password = getpass.getpass('Password: ')
|
|
|
|
except EOFError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
return password
|
|
|
|
|
|
|
|
|
2013-05-09 09:29:02 -07:00
|
|
|
def prompt_for_password():
|
2016-01-13 13:03:51 -08:00
|
|
|
"""Prompt user for password if not provided.
|
|
|
|
|
|
|
|
Prompt is used so the password doesn't show up in the
|
|
|
|
bash history.
|
2013-05-09 09:29:02 -07:00
|
|
|
"""
|
|
|
|
if not (hasattr(sys.stdin, 'isatty') and sys.stdin.isatty()):
|
|
|
|
# nothing to do
|
|
|
|
return
|
|
|
|
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
new_passwd = getpass.getpass('New Password: ')
|
|
|
|
rep_passwd = getpass.getpass('Repeat New Password: ')
|
|
|
|
if new_passwd == rep_passwd:
|
|
|
|
return new_passwd
|
|
|
|
except EOFError:
|
|
|
|
return
|
2014-02-28 11:22:26 +10:00
|
|
|
|
|
|
|
|
2015-06-07 11:20:44 -05:00
|
|
|
_ISO8601_TIME_FORMAT_SUBSECOND = '%Y-%m-%dT%H:%M:%S.%f'
|
|
|
|
_ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
|
|
|
|
|
|
|
|
|
|
|
|
def isotime(at=None, subsecond=False):
|
|
|
|
"""Stringify time in ISO 8601 format."""
|
|
|
|
|
|
|
|
# Python provides a similar instance method for datetime.datetime objects
|
|
|
|
# called isoformat(). The format of the strings generated by isoformat()
|
|
|
|
# have a couple of problems:
|
|
|
|
# 1) The strings generated by isotime are used in tokens and other public
|
|
|
|
# APIs that we can't change without a deprecation period. The strings
|
|
|
|
# generated by isoformat are not the same format, so we can't just
|
|
|
|
# change to it.
|
|
|
|
# 2) The strings generated by isoformat do not include the microseconds if
|
|
|
|
# the value happens to be 0. This will likely show up as random failures
|
|
|
|
# as parsers may be written to always expect microseconds, and it will
|
|
|
|
# parse correctly most of the time.
|
|
|
|
|
|
|
|
if not at:
|
|
|
|
at = timeutils.utcnow()
|
|
|
|
st = at.strftime(_ISO8601_TIME_FORMAT
|
|
|
|
if not subsecond
|
|
|
|
else _ISO8601_TIME_FORMAT_SUBSECOND)
|
|
|
|
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
|
|
|
|
st += ('Z' if tz == 'UTC' else tz)
|
|
|
|
return st
|
2015-06-29 15:46:35 -05:00
|
|
|
|
|
|
|
|
|
|
|
def strtime(at=None):
|
|
|
|
at = at or timeutils.utcnow()
|
|
|
|
return at.strftime(timeutils.PERFECT_TIME_FORMAT)
|