Debian Codegraph @

glanceclient/common/utils.py

raw symbols SCIP
1 # Copyright 2012 OpenStack Foundation
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import datetime
17 import errno
18 import functools
19 import hashlib
20 import json
21 import os
22 import re
23 import sys
24 import threading
25 import urllib.parse
26 import uuid
27
28
29 if os.name == 'nt': # noqa
30 import msvcrt # noqa
31 else: # noqa
32 msvcrt = None # noqa
33
34 from oslo_utils import encodeutils
35 from oslo_utils import strutils
36 import prettytable
37 import wrapt
38
39 from glanceclient._i18n import _
40 from glanceclient import exc
41
42
43 _memoized_property_lock = threading.Lock()
44
45 # NOTE(cyril): Sensitive headers must be bytes, not strings, because when we
46 # compare them to actual headers in safe_header, headers have already been
47 # encoded.
48 SENSITIVE_HEADERS = (b'X-Auth-Token', )
49 REQUIRED_FIELDS_ON_DATA = ('disk_format', 'container_format')
50
51
52 # Decorator for cli-args
53 def arg(*args, **kwargs):
54 def _decorator(func):
55 # Because of the semantics of decorator composition if we just append
56 # to the options list positional options will appear to be backwards.
57 func.__dict__.setdefault('arguments', []).insert(0, (args, kwargs))
58 return func
59 return _decorator
60
61
62 def on_data_require_fields(data_fields, required=REQUIRED_FIELDS_ON_DATA):
63 """Decorator to check commands' validity
64
65 This decorator checks that required fields are present when image
66 data has been supplied via command line arguments or via stdin
67
68 On error throws CommandError exception with meaningful message.
69
70 :param data_fields: Which fields' presence imply image data
71 :type data_fields: iter
72 :param required: Required fields
73 :type required: iter
74 :return: function decorator
75 """
76
77 def args_decorator(func):
78 def prepare_fields(fields):
79 args = ('--' + x.replace('_', '-') for x in fields)
80 return ', '.join(args)
81
82 @functools.wraps(func)
83 def func_wrapper(gc, args):
84 # Set of arguments with data
85 fields = set(a[0] for a in vars(args).items() if a[1])
86
87 # Fields the conditional requirements depend on
88 present = fields.intersection(data_fields)
89
90 # How many conditional requirements are missing
91 missing = set(required) - fields
92
93 # We use get_data_file to check if data is provided in stdin
94 if (present or get_data_file(args)) and missing:
95 msg = (_("error: Must provide %(req)s when using %(opt)s.") %
96 {'req': prepare_fields(missing),
97 'opt': prepare_fields(present) or 'stdin'})
98 raise exc.CommandError(msg)
99 return func(gc, args)
100 return func_wrapper
101 return args_decorator
102
103
104 def schema_args(schema_getter, omit=None):
105 omit = omit or []
106 typemap = {
107 'string': encodeutils.safe_decode,
108 'integer': int,
109 'boolean': lambda x: strutils.bool_from_string(x, strict=True),
110 'array': list
111 }
112
113 def _decorator(func):
114 schema = schema_getter()
115 if schema is None:
116 param = '<unavailable>'
117 kwargs = {
118 'help': ("Please run with connection parameters set to "
119 "retrieve the schema for generating help for this "
120 "command")
121 }
122 func.__dict__.setdefault('arguments', []).insert(0, ((param, ),
123 kwargs))
124 else:
125 properties = schema.get('properties', {})
126 for name, property in properties.items():
127 if name in omit:
128 continue
129 if property.get('readOnly', False):
130 continue
131 param = '--' + name.replace('_', '-')
132 kwargs = {}
133
134 type_str = property.get('type', 'string')
135
136 if isinstance(type_str, list):
137 # NOTE(flaper87): This means the server has
138 # returned something like `['null', 'string']`,
139 # therefore we use the first non-`null` type as
140 # the valid type.
141 for t in type_str:
142 if t != 'null':
143 type_str = t
144 break
145
146 if type_str == 'array':
147 items = property.get('items')
148 kwargs['type'] = typemap.get(items.get('type'))
149 kwargs['nargs'] = '+'
150 else:
151 kwargs['type'] = typemap.get(type_str)
152
153 if type_str == 'boolean':
154 kwargs['metavar'] = '[True|False]'
155 else:
156 kwargs['metavar'] = '<%s>' % name.upper()
157
158 description = property.get('description', "")
159 if 'enum' in property:
160 if len(description):
161 description += " "
162
163 # NOTE(flaper87): Make sure all values are `str/unicode`
164 # for the `join` to succeed. Enum types can also be `None`
165 # therefore, join's call would fail without the following
166 # list comprehension
167 vals = [str(val) for val in property.get('enum')]
168 description += ('Valid values: ' + ', '.join(vals))
169 kwargs['help'] = description
170
171 func.__dict__.setdefault('arguments',
172 []).insert(0, ((param, ), kwargs))
173 return func
174
175 return _decorator
176
177
178 def pretty_choice_list(choices):
179 return ', '.join("'%s'" % choice for choice in choices)
180
181
182 def has_version(client, version):
183 versions = client.get('/versions')[1].get('versions')
184 supported = ['SUPPORTED', 'CURRENT', 'EXPERIMENTAL']
185 for version_struct in versions:
186 if version_struct['id'] == version:
187 return version_struct['status'] in supported
188 return False
189
190
191 def print_cached_images(cached_images):
192 cache_pt = prettytable.PrettyTable(("ID",
193 "State",
194 "Last Accessed (UTC)",
195 "Last Modified (UTC)",
196 "Size",
197 "Hits"))
198 for item in cached_images:
199 state = "queued"
200 last_accessed = "N/A"
201 last_modified = "N/A"
202 size = "N/A"
203 hits = "N/A"
204 if item == 'cached_images':
205 state = "cached"
206 for image in cached_images[item]:
207 last_accessed = image['last_accessed']
208 if last_accessed == 0:
209 last_accessed = "N/A"
210 else:
211 last_accessed = datetime.datetime.utcfromtimestamp(
212 last_accessed).isoformat()
213
214 cache_pt.add_row((image['image_id'], state,
215 last_accessed,
216 datetime.datetime.utcfromtimestamp(
217 image['last_modified']).isoformat(),
218 image['size'],
219 image['hits']))
220 else:
221 for image in cached_images[item]:
222 cache_pt.add_row((image,
223 state,
224 last_accessed,
225 last_modified,
226 size,
227 hits))
228
229 print(cache_pt.get_string())
230
231
232 def print_dict_list(objects, fields):
233 pt = prettytable.PrettyTable([f for f in fields], caching=False)
234 pt.align = 'l'
235 for o in objects:
236 row = []
237 for field in fields:
238 field_name = field.lower().replace(' ', '_')
239 # NOTE (abhishekk) mapping field to actual name in the
240 # structure.
241 if field_name == 'task_id':
242 field_name = 'id'
243 data = o.get(field_name, '')
244 row.append(data)
245
246 pt.add_row(row)
247
248 print(encodeutils.safe_decode(pt.get_string()))
249
250
251 def print_list(objs, fields, formatters=None, field_settings=None):
252 '''Prints a list of objects.
253
254 @param objs: Objects to print
255 @param fields: Fields on each object to be printed
256 @param formatters: Custom field formatters
257 '''
258 formatters = formatters or {}
259 field_settings = field_settings or {}
260 pt = prettytable.PrettyTable([f for f in fields], caching=False)
261 pt.align = 'l'
262
263 for o in objs:
264 row = []
265 for field in fields:
266 if field in field_settings:
267 for setting, value in field_settings[field].items():
268 setting_dict = getattr(pt, setting)
269 setting_dict[field] = value
270
271 if field in formatters:
272 row.append(formatters[field](o))
273 else:
274 field_name = field.lower().replace(' ', '_')
275 data = getattr(o, field_name, None) or ''
276 row.append(data)
277 pt.add_row(row)
278
279 print(encodeutils.safe_decode(pt.get_string()))
280
281
282 def print_dict(d, max_column_width=80):
283 pt = prettytable.PrettyTable(['Property', 'Value'], caching=False)
284 pt.align = 'l'
285 pt.max_width = max_column_width
286 for k, v in d.items():
287 if isinstance(v, (dict, list)):
288 v = json.dumps(v)
289 pt.add_row([k, v])
290 print(encodeutils.safe_decode(pt.get_string(sortby='Property')))
291
292
293 def find_resource(manager, name_or_id):
294 """Helper for the _find_* methods."""
295 # first try to get entity as integer id
296 try:
297 if isinstance(name_or_id, int) or name_or_id.isdigit():
298 return manager.get(int(name_or_id))
299 except exc.NotFound:
300 pass
301
302 # now try to get entity as uuid
303 try:
304 # This must be unicode for Python 3 compatibility.
305 # If you pass a bytestring to uuid.UUID, you will get a TypeError
306 uuid.UUID(encodeutils.safe_decode(name_or_id))
307 return manager.get(name_or_id)
308 except (ValueError, exc.NotFound):
309 pass
310
311 # finally try to find entity by name
312 matches = list(manager.list(filters={'name': name_or_id}))
313 num_matches = len(matches)
314 if num_matches == 0:
315 msg = "No %s with a name or ID of '%s' exists." % \
316 (manager.resource_class.__name__.lower(), name_or_id)
317 raise exc.CommandError(msg)
318 elif num_matches > 1:
319 msg = ("Multiple %s matches found for '%s', use an ID to be more"
320 " specific." % (manager.resource_class.__name__.lower(),
321 name_or_id))
322 raise exc.CommandError(msg)
323 else:
324 return matches[0]
325
326
327 def env(*vars, **kwargs):
328 """Search for the first defined of possibly many env vars.
329
330 Returns the first environment variable defined in vars, or
331 returns the default defined in kwargs.
332 """
333 for v in vars:
334 value = os.environ.get(v, None)
335 if value:
336 return value
337 return kwargs.get('default', '')
338
339
340 def exit(msg='', exit_code=1):
341 if msg:
342 print_err(msg)
343 sys.exit(exit_code)
344
345
346 def print_err(msg):
347 print(encodeutils.safe_decode(msg), file=sys.stderr)
348
349
350 def save_image(data, path):
351 """Save an image to the specified path.
352
353 :param data: binary data of the image
354 :param path: path to save the image to
355 """
356 if path is None:
357 # NOTE(kragniz): for py3 compatibility: sys.stdout.buffer is only
358 # present on py3, otherwise fall back to sys.stdout
359 image = getattr(sys.stdout, 'buffer',
360 sys.stdout)
361 else:
362 image = open(path, 'wb')
363 try:
364 for chunk in data:
365 image.write(chunk)
366 finally:
367 if path is not None:
368 image.close()
369
370
371 def make_size_human_readable(size):
372 suffix = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB']
373 base = 1024.0
374 index = 0
375
376 if size is None:
377 size = 0
378 while size >= base:
379 index = index + 1
380 size = size / base
381
382 padded = '%.1f' % size
383 stripped = padded.rstrip('0').rstrip('.')
384
385 return '%s%s' % (stripped, suffix[index])
386
387
388 def get_file_size(file_obj):
389 """Analyze file-like object and attempt to determine its size.
390
391 :param file_obj: file-like object.
392 :retval: The file's size or None if it cannot be determined.
393 """
394 if (hasattr(file_obj, 'seek') and hasattr(file_obj, 'tell') and
395 file_obj.seekable()):
396 try:
397 curr = file_obj.tell()
398 file_obj.seek(0, os.SEEK_END)
399 size = file_obj.tell()
400 file_obj.seek(curr)
401 return size
402 except IOError as e:
403 if e.errno == errno.ESPIPE:
404 # Illegal seek. This means the file object
405 # is a pipe (e.g. the user is trying
406 # to pipe image data to the client,
407 # echo testdata | bin/glance add blah...), or
408 # that file object is empty, or that a file-like
409 # object which doesn't support 'seek/tell' has
410 # been supplied.
411 return
412 else:
413 raise
414
415
416 def get_data_file(args):
417 if args.file:
418 return open(args.file, 'rb')
419 else:
420 # distinguish cases where:
421 # (1) stdin is not valid (as in cron jobs):
422 # glance ... <&-
423 # (2) image data is provided through standard input:
424 # glance ... < /tmp/file or cat /tmp/file | glance ...
425 # (3) no image data provided:
426 # glance ...
427 try:
428 os.fstat(0)
429 except OSError:
430 # (1) stdin is not valid (closed...)
431 return None
432 if hasattr(sys.stdin, 'isatty') and not sys.stdin.isatty():
433 # (2) image data is provided through standard input
434 image = sys.stdin
435 if hasattr(sys.stdin, 'buffer'):
436 image = sys.stdin.buffer
437 if msvcrt:
438 msvcrt.setmode(image.fileno(), os.O_BINARY)
439 return image
440 else:
441 # (3) no image data provided
442 return None
443
444
445 def strip_version(endpoint):
446 """Strip version from the last component of endpoint if present."""
447 # NOTE(flaper87): This shouldn't be necessary if
448 # we make endpoint the first argument. However, we
449 # can't do that just yet because we need to keep
450 # backwards compatibility.
451 if not isinstance(endpoint, str):
452 raise ValueError("Expected endpoint")
453
454 version = None
455 # Get rid of trailing '/' if present
456 endpoint = endpoint.rstrip('/')
457 url_parts = urllib.parse.urlparse(endpoint)
458 (scheme, netloc, path, __, __, __) = url_parts
459 path = path.lstrip('/')
460 # regex to match 'v1' or 'v2.0' etc
461 if re.match(r'v\d+\.?\d*', path):
462 version = float(path.lstrip('v'))
463 endpoint = scheme + '://' + netloc
464 return endpoint, version
465
466
467 def print_image(image_obj, human_readable=False, max_col_width=None):
468 ignore = ['self', 'access', 'file', 'schema']
469 image = dict([item for item in image_obj.items()
470 if item[0] not in ignore])
471 if 'virtual_size' in image:
472 image['virtual_size'] = image.get('virtual_size') or 'Not available'
473 if human_readable:
474 image['size'] = make_size_human_readable(image['size'])
475 if str(max_col_width).isdigit():
476 print_dict(image, max_column_width=max_col_width)
477 else:
478 print_dict(image)
479
480
481 def integrity_iter(iter, checksum):
482 """Check image data integrity.
483
484 :raises: IOError
485 """
486 try:
487 md5sum = hashlib.new('md5')
488 except ValueError:
489 raise IOError(errno.EPIPE,
490 'Corrupt image download. Expected checksum is %s '
491 'but md5 algorithm is not available on the client' %
492 checksum)
493
494 for chunk in iter:
495 yield chunk
496 if isinstance(chunk, str):
497 chunk = bytes(chunk, 'latin-1')
498 md5sum.update(chunk)
499 md5sum = md5sum.hexdigest()
500 if md5sum != checksum:
501 raise IOError(errno.EPIPE,
502 'Corrupt image download. Checksum was %s expected %s' %
503 (md5sum, checksum))
504
505
506 def serious_integrity_iter(iter, hasher, hash_value):
507 """Check image data integrity using the Glance "multihash".
508
509 :param iter: iterable containing the image data
510 :param hasher: a hashlib object
511 :param hash_value: hexdigest of the image data
512 :raises: IOError if the hashdigest of the data is not hash_value
513 """
514 for chunk in iter:
515 yield chunk
516 if isinstance(chunk, str):
517 chunk = bytes(chunk, 'latin-1')
518 hasher.update(chunk)
519 computed = hasher.hexdigest()
520 if computed != hash_value:
521 raise IOError(errno.EPIPE,
522 'Corrupt image download. Hash was %s expected %s' %
523 (computed, hash_value))
524
525
526 def memoized_property(fn):
527 attr_name = '_lazy_once_' + fn.__name__
528
529 @property
530 def _memoized_property(self):
531 if hasattr(self, attr_name):
532 return getattr(self, attr_name)
533 else:
534 with _memoized_property_lock:
535 if not hasattr(self, attr_name):
536 setattr(self, attr_name, fn(self))
537 return getattr(self, attr_name)
538 return _memoized_property
539
540
541 def safe_header(name, value):
542 if value is not None and name in SENSITIVE_HEADERS:
543 h = hashlib.sha1(value)
544 d = h.hexdigest()
545 return name, "{SHA1}%s" % d
546 else:
547 return name, value
548
549
550 def endpoint_version_from_url(endpoint, default_version=None):
551 if endpoint:
552 endpoint, version = strip_version(endpoint)
553 return endpoint, version or default_version
554 else:
555 return None, default_version
556
557
558 def debug_enabled(argv):
559 if bool(env('GLANCECLIENT_DEBUG')) is True:
560 return True
561 if '--debug' in argv or '-d' in argv:
562 return True
563 return False
564
565
566 class IterableWithLength(object):
567 def __init__(self, iterable, length):
568 self.iterable = iterable
569 self.length = length
570
571 def __iter__(self):
572 try:
573 for chunk in self.iterable:
574 yield chunk
575 finally:
576 self.iterable.close()
577
578 def next(self):
579 return next(self.iterable)
580
581 # In Python 3, __next__() has replaced next().
582 __next__ = next
583
584 def __len__(self):
585 return self.length
586
587
588 class RequestIdProxy(wrapt.ObjectProxy):
589 def __init__(self, wrapped):
590 # `wrapped` is a tuple: (original_obj, response_obj)
591 super(RequestIdProxy, self).__init__(wrapped[0])
592 self._self_wrapped = wrapped[0]
593 req_id = _extract_request_id(wrapped[1])
594 self._self_request_ids = [req_id]
595
596 @property
597 def request_ids(self):
598 return self._self_request_ids
599
600 @property
601 def wrapped(self):
602 return self._self_wrapped
603
604 # Overriden next method to act as iterator
605 def next(self):
606 return next(self._self_wrapped)
607
608 # In Python 3, __next__() has replaced next().
609 __next__ = next
610
611
612 class GeneratorProxy(wrapt.ObjectProxy):
613 def __init__(self, wrapped):
614 super(GeneratorProxy, self).__init__(wrapped)
615 self._self_wrapped = wrapped
616 self._self_request_ids = []
617
618 def _set_request_ids(self, resp):
619 if self._self_request_ids == []:
620 req_id = _extract_request_id(resp)
621 self._self_request_ids = [req_id]
622
623 def _next(self):
624 obj, resp = next(self._self_wrapped)
625 self._set_request_ids(resp)
626 return obj
627
628 # Override generator's next method to add
629 # request id on each iteration
630 def next(self):
631 return self._next()
632
633 # For Python 3 compatibility
634 def __next__(self):
635 return self._next()
636
637 def __iter__(self):
638 return self
639
640 @property
641 def request_ids(self):
642 return self._self_request_ids
643
644 @property
645 def wrapped(self):
646 return self._self_wrapped
647
648
649 def add_req_id_to_object():
650 @wrapt.decorator
651 def inner(wrapped, instance, args, kwargs):
652 return RequestIdProxy(wrapped(*args, **kwargs))
653 return inner
654
655
656 def add_req_id_to_generator():
657 @wrapt.decorator
658 def inner(wrapped, instance, args, kwargs):
659 return GeneratorProxy(wrapped(*args, **kwargs))
660 return inner
661
662
663 def _extract_request_id(resp):
664 # TODO(rsjethani): Do we need more checks here?
665 return resp.headers.get('x-openstack-request-id')