Buckets:
| import random, binascii, threading, os | |
| def pycc_corrupt_string(string): | |
| if string: | |
| if (random.randint(0, 1) == 0): | |
| hexstring = binascii.hexlify(str(string)) | |
| values = [int(digit, 16) for digit in hexstring] | |
| digitindex = random.randint(0, len(values)) | |
| bitindex = random.randint(0, 3) | |
| values[(digitindex - 1)] ^= (1 << bitindex) | |
| result = ''.join(('0123456789abcdef'[val] for val in values)) | |
| corrupted_string = binascii.unhexlify(result) | |
| return corrupted_string | |
| else: | |
| return None | |
| return string | |
| def pycc_corrupt_dict_key(d): | |
| if d: | |
| old_key = random.choice(d.keys()) | |
| corrupted_key = pycc_corrupt(old_key) | |
| d[corrupted_key] = d.pop(old_key) | |
| return d | |
| def pycc_corrupt(target, mode=None): | |
| if isinstance(target, int): | |
| return (-1) | |
| elif isinstance(target, str): | |
| return pycc_corrupt_string(target) | |
| elif isinstance(target, dict): | |
| return pycc_corrupt_dict_key(target) | |
| elif isinstance(target, bool): | |
| return (not target) | |
| else: | |
| return None | |
| pycc_leaked_files = list() | |
| def _pycc_hog_fd(): | |
| try: | |
| i = 0 | |
| files = [] | |
| pycc_leak_file_dir = '/tmp/pycc_file_leak_dir/' | |
| os.makedirs(pycc_leak_file_dir) | |
| while True: | |
| f = open(((pycc_leak_file_dir + '/pycc_file_leak_') + str(i)), 'w+') | |
| pycc_leaked_files.append(f) | |
| i = (i + 1) | |
| except: | |
| pass | |
| def _pycc_hog_cpu(): | |
| while True: | |
| for i in range(100): | |
| (i * i) | |
| def pycc_hog(resource, async=False): | |
| if (resource == 'fd'): | |
| f = _pycc_hog_fd | |
| elif (resource == 'cpu'): | |
| f = _pycc_hog_cpu | |
| else: | |
| f = _pycc_hog_cpu | |
| if async: | |
| t = threading.Thread(target=f) | |
| t.start() | |
| else: | |
| f() | |
| 'Utilities and helper functions.' | |
| import contextlib | |
| import copy | |
| import datetime | |
| import functools | |
| import hashlib | |
| import inspect | |
| import os | |
| import pyclbr | |
| import random | |
| import re | |
| import shutil | |
| import socket | |
| import struct | |
| import sys | |
| import tempfile | |
| import time | |
| import eventlet | |
| import netaddr | |
| from oslo_concurrency import lockutils | |
| from oslo_concurrency import processutils | |
| from oslo_context import context as common_context | |
| from oslo_log import log as logging | |
| import oslo_messaging as messaging | |
| from oslo_utils import encodeutils | |
| from oslo_utils import excutils | |
| from oslo_utils import importutils | |
| from oslo_utils import strutils | |
| from oslo_utils import timeutils | |
| from oslo_utils import units | |
| import prettytable | |
| import six | |
| from six.moves import range | |
| import nova.conf | |
| from nova import exception | |
| from nova.i18n import _, _LE, _LI, _LW | |
| import nova.network | |
| from nova import safe_utils | |
| profiler = importutils.try_import('osprofiler.profiler') | |
| CONF = nova.conf.CONF | |
| LOG = logging.getLogger(__name__) | |
| TIME_UNITS = {'SECOND': 1, 'MINUTE': 60, 'HOUR': 3600, 'DAY': 86400} | |
| _IS_NEUTRON = None | |
| synchronized = lockutils.synchronized_with_prefix('nova-') | |
| SM_IMAGE_PROP_PREFIX = 'image_' | |
| SM_INHERITABLE_KEYS = ('min_ram', 'min_disk', 'disk_format', 'container_format') | |
| SM_SKIP_KEYS = ('mappings', 'block_device_mapping', 'img_mappings', 'img_block_device_mapping') | |
| VIM_IMAGE_ATTRIBUTES = ('image_id', 'image_name', 'size', 'checksum', 'container_format', 'disk_format', 'min_ram', 'min_disk') | |
| _FILE_CACHE = {} | |
| def vpn_ping(address, port, timeout=0.05, session_id=None): | |
| 'Sends a vpn negotiation packet and returns the server session.\n\n Returns Boolean indicating whether the vpn_server is listening.\n Basic packet structure is below.\n\n Client packet (14 bytes)::\n\n 0 1 8 9 13\n +-+--------+-----+\n |x| cli_id |?????|\n +-+--------+-----+\n x = packet identifier 0x38\n cli_id = 64 bit identifier\n ? = unknown, probably flags/padding\n\n Server packet (26 bytes)::\n\n 0 1 8 9 13 14 21 2225\n +-+--------+-----+--------+----+\n |x| srv_id |?????| cli_id |????|\n +-+--------+-----+--------+----+\n x = packet identifier 0x40\n cli_id = 64 bit identifier\n ? = unknown, probably flags/padding\n bit 9 was 1 and the rest were 0 in testing\n\n ' | |
| if (session_id is None): | |
| session_id = random.randint(0, 18446744073709551615L) | |
| sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
| data = struct.pack('!BQxxxxx', 56, session_id) | |
| sock.sendto(data, (address, port)) | |
| sock.settimeout(timeout) | |
| try: | |
| received = sock.recv(2048) | |
| except socket.timeout: | |
| return False | |
| finally: | |
| sock.close() | |
| fmt = '!BQxxxxxQxxxx' | |
| if (len(received) != struct.calcsize(fmt)): | |
| LOG.warning(_LW('Expected to receive %(exp)s bytes, but actually %(act)s'), dict(exp=struct.calcsize(fmt), act=len(received))) | |
| return False | |
| (identifier, server_sess, client_sess) = struct.unpack(fmt, received) | |
| return ((identifier == 64) and (client_sess == session_id)) | |
| def get_root_helper(): | |
| if CONF.workarounds.disable_rootwrap: | |
| cmd = 'sudo' | |
| else: | |
| cmd = ('sudo nova-rootwrap %s' % CONF.rootwrap_config) | |
| return cmd | |
| class RootwrapProcessHelper(object, ): | |
| def trycmd(self, *cmd, **kwargs): | |
| kwargs['root_helper'] = get_root_helper() | |
| return processutils.trycmd(*cmd, **kwargs) | |
| def execute(self, *cmd, **kwargs): | |
| kwargs['root_helper'] = get_root_helper() | |
| return processutils.execute(*cmd, **kwargs) | |
| class RootwrapDaemonHelper(RootwrapProcessHelper, ): | |
| _clients = {} | |
| def _get_client(cls, rootwrap_config): | |
| try: | |
| return cls._clients[rootwrap_config] | |
| except KeyError: | |
| from oslo_rootwrap import client | |
| new_client = client.Client(['sudo', 'nova-rootwrap-daemon', rootwrap_config]) | |
| cls._clients[rootwrap_config] = new_client | |
| return new_client | |
| def __init__(self, rootwrap_config): | |
| self.client = self._get_client(rootwrap_config) | |
| def trycmd(self, *args, **kwargs): | |
| discard_warnings = kwargs.pop('discard_warnings', False) | |
| try: | |
| (out, err) = self.execute(*args, **kwargs) | |
| failed = False | |
| except processutils.ProcessExecutionError as exn: | |
| (out, err) = ('', six.text_type(exn)) | |
| failed = True | |
| if ((not failed) and discard_warnings and err): | |
| err = '' | |
| return (out, err) | |
| def execute(self, *cmd, **kwargs): | |
| cmd = [str(c) for c in cmd] | |
| loglevel = kwargs.pop('loglevel', logging.DEBUG) | |
| log_errors = kwargs.pop('log_errors', None) | |
| process_input = kwargs.pop('process_input', None) | |
| delay_on_retry = kwargs.pop('delay_on_retry', True) | |
| attempts = kwargs.pop('attempts', 1) | |
| check_exit_code = kwargs.pop('check_exit_code', [0]) | |
| ignore_exit_code = False | |
| if isinstance(check_exit_code, bool): | |
| ignore_exit_code = (not check_exit_code) | |
| check_exit_code = [0] | |
| elif isinstance(check_exit_code, int): | |
| check_exit_code = [check_exit_code] | |
| sanitized_cmd = strutils.mask_password(' '.join(cmd)) | |
| LOG.info(_LI('Executing RootwrapDaemonHelper.execute cmd=[%(cmd)r] kwargs=[%(kwargs)r]'), {'cmd': sanitized_cmd, 'kwargs': kwargs}) | |
| while (attempts > 0): | |
| attempts -= 1 | |
| try: | |
| start_time = time.time() | |
| LOG.log(loglevel, _('Running cmd (subprocess): %s'), sanitized_cmd) | |
| (returncode, out, err) = self.client.execute(cmd, process_input) | |
| end_time = (time.time() - start_time) | |
| LOG.log(loglevel, 'CMD "%(sanitized_cmd)s" returned: %(return_code)s in %(end_time)0.3fs', {'sanitized_cmd': sanitized_cmd, 'return_code': returncode, 'end_time': end_time}) | |
| if ((not ignore_exit_code) and (returncode not in check_exit_code)): | |
| out = strutils.mask_password(out) | |
| err = strutils.mask_password(err) | |
| raise processutils.ProcessExecutionError(exit_code=returncode, stdout=out, stderr=err, cmd=sanitized_cmd) | |
| return (out, err) | |
| except processutils.ProcessExecutionError as err: | |
| if ((log_errors == processutils.LOG_ALL_ERRORS) or ((log_errors == processutils.LOG_FINAL_ERROR) and (not attempts))): | |
| format = _('%(desc)r\ncommand: %(cmd)r\nexit code: %(code)r\nstdout: %(stdout)r\nstderr: %(stderr)r') | |
| LOG.log(loglevel, format, {'desc': err.description, 'cmd': err.cmd, 'code': err.exit_code, 'stdout': err.stdout, 'stderr': err.stderr}) | |
| if (not attempts): | |
| LOG.log(loglevel, _('%r failed. Not Retrying.'), sanitized_cmd) | |
| raise | |
| else: | |
| LOG.log(loglevel, _('%r failed. Retrying.'), sanitized_cmd) | |
| if delay_on_retry: | |
| time.sleep((random.randint(20, 200) / 100.0)) | |
| def execute(*cmd, **kwargs): | |
| "Convenience wrapper around oslo's execute() method." | |
| if (('run_as_root' in kwargs) and kwargs.get('run_as_root')): | |
| if CONF.use_rootwrap_daemon: | |
| return RootwrapDaemonHelper(CONF.rootwrap_config).execute(*cmd, **kwargs) | |
| else: | |
| return RootwrapProcessHelper().execute(*cmd, **kwargs) | |
| return processutils.execute(*cmd, **kwargs) | |
| def ssh_execute(dest, *cmd, **kwargs): | |
| 'Convenience wrapper to execute ssh command.' | |
| ssh_cmd = ['ssh', '-o', 'BatchMode=yes'] | |
| ssh_cmd.append(dest) | |
| ssh_cmd.extend(cmd) | |
| return execute(*ssh_cmd, **kwargs) | |
| def trycmd(*args, **kwargs): | |
| "Convenience wrapper around oslo's trycmd() method." | |
| if kwargs.get('run_as_root', False): | |
| if CONF.use_rootwrap_daemon: | |
| return RootwrapDaemonHelper(CONF.rootwrap_config).trycmd(*args, **kwargs) | |
| else: | |
| return RootwrapProcessHelper().trycmd(*args, **kwargs) | |
| return processutils.trycmd(*args, **kwargs) | |
| def generate_uid(topic, size=8): | |
| characters = '01234567890abcdefghijklmnopqrstuvwxyz' | |
| choices = [random.choice(characters) for _x in range(size)] | |
| return ('%s-%s' % (topic, ''.join(choices))) | |
| DEFAULT_PASSWORD_SYMBOLS = ('23456789', 'ABCDEFGHJKLMNPQRSTUVWXYZ', 'abcdefghijkmnopqrstuvwxyz') | |
| def last_completed_audit_period(unit=None, before=None): | |
| "This method gives you the most recently *completed* audit period.\n\n arguments:\n units: string, one of 'hour', 'day', 'month', 'year'\n Periods normally begin at the beginning (UTC) of the\n period unit (So a 'day' period begins at midnight UTC,\n a 'month' unit on the 1st, a 'year' on Jan, 1)\n unit string may be appended with an optional offset\n like so: 'day@18' This will begin the period at 18:00\n UTC. 'month@15' starts a monthly period on the 15th,\n and year@3 begins a yearly one on March 1st.\n before: Give the audit period most recently completed before\n <timestamp>. Defaults to now.\n\n\n returns: 2 tuple of datetimes (begin, end)\n The begin timestamp of this audit period is the same as the\n end of the previous.\n " | |
| if (not unit): | |
| unit = CONF.instance_usage_audit_period | |
| offset = 0 | |
| if ('@' in unit): | |
| (unit, offset) = unit.split('@', 1) | |
| offset = int(offset) | |
| if (before is not None): | |
| rightnow = before | |
| else: | |
| rightnow = timeutils.utcnow() | |
| if (unit not in ('month', 'day', 'year', 'hour')): | |
| raise ValueError('Time period must be hour, day, month or year') | |
| if (unit == 'month'): | |
| if (offset == 0): | |
| offset = 1 | |
| end = datetime.datetime(day=offset, month=rightnow.month, year=rightnow.year) | |
| if (end >= rightnow): | |
| year = rightnow.year | |
| if (1 >= rightnow.month): | |
| year -= 1 | |
| month = (12 + (rightnow.month - 1)) | |
| else: | |
| month = (rightnow.month - 1) | |
| end = datetime.datetime(day=offset, month=month, year=year) | |
| year = end.year | |
| if (1 >= end.month): | |
| year -= 1 | |
| month = (12 + (end.month - 1)) | |
| else: | |
| month = (end.month - 1) | |
| begin = datetime.datetime(day=offset, month=month, year=year) | |
| elif (unit == 'year'): | |
| if (offset == 0): | |
| offset = 1 | |
| end = datetime.datetime(day=1, month=offset, year=rightnow.year) | |
| if (end >= rightnow): | |
| end = datetime.datetime(day=1, month=offset, year=(rightnow.year - 1)) | |
| begin = datetime.datetime(day=1, month=offset, year=(rightnow.year - 2)) | |
| else: | |
| begin = datetime.datetime(day=1, month=offset, year=(rightnow.year - 1)) | |
| elif (unit == 'day'): | |
| end = datetime.datetime(hour=offset, day=rightnow.day, month=rightnow.month, year=rightnow.year) | |
| if (end >= rightnow): | |
| end = (end - datetime.timedelta(days=1)) | |
| begin = (end - datetime.timedelta(days=1)) | |
| elif (unit == 'hour'): | |
| end = rightnow.replace(minute=offset, second=0, microsecond=0) | |
| if (end >= rightnow): | |
| end = (end - datetime.timedelta(hours=1)) | |
| begin = (end - datetime.timedelta(hours=1)) | |
| return (begin, end) | |
| def generate_password(length=None, symbolgroups=DEFAULT_PASSWORD_SYMBOLS): | |
| 'Generate a random password from the supplied symbol groups.\n\n At least one symbol from each group will be included. Unpredictable\n results if length is less than the number of symbol groups.\n\n Believed to be reasonably secure (with a reasonable password length!)\n\n ' | |
| if (length is None): | |
| length = CONF.password_length | |
| r = random.SystemRandom() | |
| password = [r.choice(s) for s in symbolgroups] | |
| r.shuffle(password) | |
| password = password[:length] | |
| length -= len(password) | |
| symbols = ''.join(symbolgroups) | |
| password.extend([r.choice(symbols) for _i in range(length)]) | |
| r.shuffle(password) | |
| return ''.join(password) | |
| def get_my_linklocal(interface): | |
| try: | |
| if_str = execute('ip', '-f', 'inet6', '-o', 'addr', 'show', interface) | |
| condition = '\\s+inet6\\s+([0-9a-f:]+)/\\d+\\s+scope\\s+link' | |
| links = [re.search(condition, x) for x in if_str[0].split('\n')] | |
| address = [w.group(1) for w in links if (w is not None)] | |
| if (address[0] is not None): | |
| return address[0] | |
| else: | |
| msg = (_('Link Local address is not found.:%s') % if_str) | |
| raise exception.NovaException(msg) | |
| except Exception as ex: | |
| msg = (_("Couldn't get Link Local IP of %(interface)s :%(ex)s") % {'interface': interface, 'ex': ex}) | |
| raise exception.NovaException(msg) | |
| def utf8(value): | |
| 'Try to turn a string into utf-8 if possible.\n\n The original code was copied from the utf8 function in\n http://github.com/facebook/tornado/blob/master/tornado/escape.py\n\n ' | |
| if ((value is None) or isinstance(value, six.binary_type)): | |
| return value | |
| if (not isinstance(value, six.text_type)): | |
| value = six.text_type(value) | |
| return value.encode('utf-8') | |
| def parse_server_string(server_str): | |
| "Parses the given server_string and returns a tuple of host and port.\n If it's not a combination of host part and port, the port element\n is an empty string. If the input is invalid expression, return a tuple of\n two empty strings.\n " | |
| try: | |
| if netaddr.valid_ipv6(server_str): | |
| return (server_str, '') | |
| if (server_str.find(']:') != (-1)): | |
| (address, port) = server_str.replace('[', '', 1).split(']:') | |
| return (address, port) | |
| if (server_str.find(':') == (-1)): | |
| return (server_str, '') | |
| (address, port) = server_str.split(':') | |
| return (address, port) | |
| except (ValueError, netaddr.AddrFormatError): | |
| LOG.error(_LE('Invalid server_string: %s'), server_str) | |
| return ('', '') | |
| def get_shortened_ipv6(address): | |
| addr = netaddr.IPAddress(address, version=6) | |
| return str(addr.ipv6()) | |
| def get_shortened_ipv6_cidr(address): | |
| net = netaddr.IPNetwork(address, version=6) | |
| return str(net.cidr) | |
| def get_ip_version(network): | |
| 'Returns the IP version of a network (IPv4 or IPv6).\n\n Raises AddrFormatError if invalid network.\n ' | |
| if (netaddr.IPNetwork(network).version == 6): | |
| return 'IPv6' | |
| elif (netaddr.IPNetwork(network).version == 4): | |
| return 'IPv4' | |
| def safe_ip_format(ip): | |
| 'Transform ip string to "safe" format.\n\n Will return ipv4 addresses unchanged, but will nest ipv6 addresses\n inside square brackets.\n ' | |
| try: | |
| if (netaddr.IPAddress(ip).version == 6): | |
| return ('[%s]' % ip) | |
| except (TypeError, netaddr.AddrFormatError): | |
| pass | |
| return ip | |
| def format_remote_path(host, path): | |
| "Returns remote path in format acceptable for scp/rsync.\n\n If host is IPv6 address literal, return '[host]:path', otherwise\n 'host:path' is returned.\n\n If host is None, only path is returned.\n " | |
| if (host is None): | |
| return path | |
| return ('%s:%s' % (safe_ip_format(host), path)) | |
| def monkey_patch(): | |
| 'If the CONF.monkey_patch set as True,\n this function patches a decorator\n for all functions in specified modules.\n You can set decorators for each modules\n using CONF.monkey_patch_modules.\n The format is "Module path:Decorator function".\n Example:\n \'nova.api.ec2.cloud:nova.notifications.notify_decorator\'\n\n Parameters of the decorator is as follows.\n (See nova.notifications.notify_decorator)\n\n name - name of the function\n function - object of the function\n ' | |
| if (not CONF.monkey_patch): | |
| return | |
| if six.PY2: | |
| is_method = inspect.ismethod | |
| else: | |
| def is_method(obj): | |
| return (inspect.ismethod(obj) or inspect.isfunction(obj)) | |
| for module_and_decorator in CONF.monkey_patch_modules: | |
| (module, decorator_name) = module_and_decorator.split(':') | |
| decorator = importutils.import_class(decorator_name) | |
| __import__(module) | |
| module_data = pyclbr.readmodule_ex(module) | |
| for (key, value) in module_data.items(): | |
| if isinstance(value, pyclbr.Class): | |
| clz = importutils.import_class(('%s.%s' % (module, key))) | |
| for (method, func) in inspect.getmembers(clz, is_method): | |
| setattr(clz, method, decorator(('%s.%s.%s' % (module, key, method)), func)) | |
| if isinstance(value, pyclbr.Function): | |
| func = importutils.import_class(('%s.%s' % (module, key))) | |
| setattr(sys.modules[module], key, decorator(('%s.%s' % (module, key)), func)) | |
| def make_dev_path(dev, partition=None, base='/dev'): | |
| "Return a path to a particular device.\n\n >>> make_dev_path('xvdc')\n /dev/xvdc\n\n >>> make_dev_path('xvdc', 1)\n /dev/xvdc1\n " | |
| path = os.path.join(base, dev) | |
| if partition: | |
| path += str(partition) | |
| return path | |
| def sanitize_hostname(hostname, default_name=None): | |
| 'Return a hostname which conforms to RFC-952 and RFC-1123 specs except\n the length of hostname.\n\n Window, Linux, and Dnsmasq has different limitation:\n\n Windows: 255 (net_bios limits to 15, but window will truncate it)\n Linux: 64\n Dnsmasq: 63\n\n Due to nova-network will leverage dnsmasq to set hostname, so we chose\n 63.\n\n ' | |
| def truncate_hostname(name): | |
| if (len(name) > 63): | |
| LOG.warning(_LW('Hostname %(hostname)s is longer than 63, truncate it to %(truncated_name)s'), {'hostname': name, 'truncated_name': name[:63]}) | |
| return name[:63] | |
| if isinstance(hostname, six.text_type): | |
| hostname = hostname.encode('latin-1', 'ignore') | |
| if six.PY3: | |
| hostname = hostname.decode('latin-1') | |
| hostname = truncate_hostname(hostname) | |
| hostname = re.sub('[ _]', '-', hostname) | |
| hostname = re.sub('[^\\w.-]+', '', hostname) | |
| hostname = hostname.lower() | |
| hostname = hostname.strip('.-') | |
| if ((hostname == '') and (default_name is not None)): | |
| return truncate_hostname(default_name) | |
| return hostname | |
| def temporary_mutation(obj, **kwargs): | |
| 'Temporarily set the attr on a particular object to a given value then\n revert when finished.\n\n One use of this is to temporarily set the read_deleted flag on a context\n object:\n\n with temporary_mutation(context, read_deleted="yes"):\n do_something_that_needed_deleted_objects()\n ' | |
| def is_dict_like(thing): | |
| return (hasattr(thing, 'has_key') or isinstance(thing, dict)) | |
| def get(thing, attr, default): | |
| if is_dict_like(thing): | |
| return thing.get(attr, default) | |
| else: | |
| return getattr(thing, attr, default) | |
| def set_value(thing, attr, val): | |
| if is_dict_like(thing): | |
| thing[attr] = val | |
| else: | |
| setattr(thing, attr, val) | |
| def delete(thing, attr): | |
| if is_dict_like(thing): | |
| del thing[attr] | |
| else: | |
| delattr(thing, attr) | |
| NOT_PRESENT = object() | |
| old_values = {} | |
| for (attr, new_value) in kwargs.items(): | |
| old_values[attr] = get(obj, attr, NOT_PRESENT) | |
| set_value(obj, attr, new_value) | |
| try: | |
| (yield) | |
| finally: | |
| for (attr, old_value) in old_values.items(): | |
| if (old_value is NOT_PRESENT): | |
| delete(obj, attr) | |
| else: | |
| set_value(obj, attr, old_value) | |
| def generate_mac_address(): | |
| 'Generate an Ethernet MAC address.' | |
| mac = [250, 22, 62, random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)] | |
| return ':'.join(map((lambda x: ('%02x' % x)), mac)) | |
| def read_file_as_root(file_path): | |
| 'Secure helper to read file as root.' | |
| try: | |
| (out, _err) = execute('cat', file_path, run_as_root=True) | |
| return out | |
| except processutils.ProcessExecutionError: | |
| raise exception.FileNotFound(file_path=file_path) | |
| def temporary_chown(path, owner_uid=None): | |
| 'Temporarily chown a path.\n\n :param owner_uid: UID of temporary owner (defaults to current user)\n ' | |
| if (owner_uid is None): | |
| owner_uid = os.getuid() | |
| orig_uid = os.stat(path).st_uid | |
| if (orig_uid != owner_uid): | |
| execute('chown', owner_uid, path, run_as_root=True) | |
| try: | |
| (yield) | |
| finally: | |
| if (orig_uid != owner_uid): | |
| execute('chown', orig_uid, path, run_as_root=True) | |
| def tempdir(**kwargs): | |
| argdict = kwargs.copy() | |
| if ('dir' not in argdict): | |
| argdict['dir'] = CONF.tempdir | |
| tmpdir = tempfile.mkdtemp(**argdict) | |
| try: | |
| (yield tmpdir) | |
| finally: | |
| try: | |
| shutil.rmtree(tmpdir) | |
| except OSError as e: | |
| LOG.error(_LE('Could not remove tmpdir: %s'), e) | |
| def walk_class_hierarchy(clazz, encountered=None): | |
| 'Walk class hierarchy, yielding most derived classes first.' | |
| if (not encountered): | |
| encountered = [] | |
| for subclass in clazz.__subclasses__(): | |
| if (subclass not in encountered): | |
| encountered.append(subclass) | |
| for subsubclass in walk_class_hierarchy(subclass, encountered): | |
| (yield subsubclass) | |
| (yield subclass) | |
| class UndoManager(object, ): | |
| 'Provides a mechanism to facilitate rolling back a series of actions\n when an exception is raised.\n ' | |
| def __init__(self): | |
| self.undo_stack = [] | |
| def undo_with(self, undo_func): | |
| self.undo_stack.append(undo_func) | |
| def _rollback(self): | |
| for undo_func in reversed(self.undo_stack): | |
| undo_func() | |
| def rollback_and_reraise(self, msg=None, **kwargs): | |
| 'Rollback a series of actions then re-raise the exception.\n\n .. note:: (sirp) This should only be called within an\n exception handler.\n ' | |
| with excutils.save_and_reraise_exception(): | |
| if msg: | |
| LOG.exception(msg, **kwargs) | |
| self._rollback() | |
| def mkfs(fs, path, label=None, run_as_root=False): | |
| "Format a file or block device\n\n :param fs: Filesystem type (examples include 'swap', 'ext3', 'ext4'\n 'btrfs', etc.)\n :param path: Path to file or block device to format\n :param label: Volume label to use\n " | |
| if (fs == 'swap'): | |
| args = ['mkswap'] | |
| else: | |
| args = ['mkfs', '-t', fs] | |
| if (fs in ('ext3', 'ext4', 'ntfs')): | |
| args.extend(['-F']) | |
| if label: | |
| if (fs in ('msdos', 'vfat')): | |
| label_opt = '-n' | |
| else: | |
| label_opt = '-L' | |
| args.extend([label_opt, label]) | |
| args.append(path) | |
| execute(run_as_root=run_as_root, *args) | |
| def metadata_to_dict(metadata, include_deleted=False): | |
| result = {} | |
| for item in metadata: | |
| if ((not include_deleted) and item.get('deleted')): | |
| continue | |
| result[item['key']] = item['value'] | |
| return result | |
| def dict_to_metadata(metadata): | |
| result = [] | |
| for (key, value) in metadata.items(): | |
| result.append(dict(key=key, value=value)) | |
| return result | |
| def instance_meta(instance): | |
| if isinstance(instance['metadata'], dict): | |
| return instance['metadata'] | |
| else: | |
| return metadata_to_dict(instance['metadata']) | |
| def instance_sys_meta(instance): | |
| if (not instance.get('system_metadata')): | |
| return pycc_corrupt({}) | |
| if isinstance(instance['system_metadata'], dict): | |
| return instance['system_metadata'] | |
| else: | |
| return metadata_to_dict(instance['system_metadata'], include_deleted=True) | |
| def expects_func_args(*args): | |
| def _decorator_checker(dec): | |
| def _decorator(f): | |
| base_f = safe_utils.get_wrapped_function(f) | |
| (arg_names, a, kw, _default) = inspect.getargspec(base_f) | |
| if (a or kw or (set(args) <= set(arg_names))): | |
| return dec(f) | |
| else: | |
| raise TypeError(('Decorated function %(f_name)s does not have the arguments expected by the decorator %(d_name)s' % {'f_name': base_f.__name__, 'd_name': dec.__name__})) | |
| return _decorator | |
| return _decorator_checker | |
| class ExceptionHelper(object, ): | |
| 'Class to wrap another and translate the ClientExceptions raised by its\n function calls to the actual ones.\n ' | |
| def __init__(self, target): | |
| self._target = target | |
| def __getattr__(self, name): | |
| func = getattr(self._target, name) | |
| def wrapper(*args, **kwargs): | |
| try: | |
| return func(*args, **kwargs) | |
| except messaging.ExpectedException as e: | |
| six.reraise(*e.exc_info) | |
| return wrapper | |
| def check_string_length(value, name=None, min_length=0, max_length=None): | |
| 'Check the length of specified string\n :param value: the value of the string\n :param name: the name of the string\n :param min_length: the min_length of the string\n :param max_length: the max_length of the string\n ' | |
| if (not isinstance(value, six.string_types)): | |
| if (name is None): | |
| msg = _('The input is not a string or unicode') | |
| else: | |
| msg = (_('%s is not a string or unicode') % name) | |
| raise exception.InvalidInput(message=msg) | |
| if (name is None): | |
| name = value | |
| if (len(value) < min_length): | |
| msg = (_('%(name)s has a minimum character requirement of %(min_length)s.') % {'name': name, 'min_length': min_length}) | |
| raise exception.InvalidInput(message=msg) | |
| if (max_length and (len(value) > max_length)): | |
| msg = (_('%(name)s has more than %(max_length)s characters.') % {'name': name, 'max_length': max_length}) | |
| raise exception.InvalidInput(message=msg) | |
| def validate_integer(value, name, min_value=None, max_value=None): | |
| 'Make sure that value is a valid integer, potentially within range.' | |
| try: | |
| value = int(str(value)) | |
| except (ValueError, UnicodeEncodeError): | |
| msg = _('%(value_name)s must be an integer') | |
| raise exception.InvalidInput(reason=(msg % {'value_name': name})) | |
| if (min_value is not None): | |
| if (value < min_value): | |
| msg = _('%(value_name)s must be >= %(min_value)d') | |
| raise exception.InvalidInput(reason=(msg % {'value_name': name, 'min_value': min_value})) | |
| if (max_value is not None): | |
| if (value > max_value): | |
| msg = _('%(value_name)s must be <= %(max_value)d') | |
| raise exception.InvalidInput(reason=(msg % {'value_name': name, 'max_value': max_value})) | |
| return value | |
| def _serialize_profile_info(): | |
| if (not profiler): | |
| return None | |
| prof = profiler.get() | |
| trace_info = None | |
| if prof: | |
| trace_info = {'hmac_key': prof.hmac_key, 'base_id': prof.get_base_id(), 'parent_id': prof.get_id()} | |
| return trace_info | |
| def spawn(func, *args, **kwargs): | |
| 'Passthrough method for eventlet.spawn.\n\n This utility exists so that it can be stubbed for testing without\n interfering with the service spawns.\n\n It will also grab the context from the threadlocal store and add it to\n the store on the new thread. This allows for continuity in logging the\n context when using this method to spawn a new thread.\n ' | |
| _context = common_context.get_current() | |
| profiler_info = _serialize_profile_info() | |
| def context_wrapper(*args, **kwargs): | |
| if (_context is not None): | |
| _context.update_store() | |
| if (profiler_info and profiler): | |
| profiler.init(**profiler_info) | |
| return func(*args, **kwargs) | |
| return eventlet.spawn(context_wrapper, *args, **kwargs) | |
| def spawn_n(func, *args, **kwargs): | |
| 'Passthrough method for eventlet.spawn_n.\n\n This utility exists so that it can be stubbed for testing without\n interfering with the service spawns.\n\n It will also grab the context from the threadlocal store and add it to\n the store on the new thread. This allows for continuity in logging the\n context when using this method to spawn a new thread.\n ' | |
| _context = common_context.get_current() | |
| profiler_info = _serialize_profile_info() | |
| def context_wrapper(*args, **kwargs): | |
| if (_context is not None): | |
| _context.update_store() | |
| if (profiler_info and profiler): | |
| profiler.init(**profiler_info) | |
| func(*args, **kwargs) | |
| eventlet.spawn_n(context_wrapper, *args, **kwargs) | |
| def is_none_string(val): | |
| 'Check if a string represents a None value.\n ' | |
| if (not isinstance(val, six.string_types)): | |
| return False | |
| return (val.lower() == 'none') | |
| def is_neutron(): | |
| global _IS_NEUTRON | |
| if (_IS_NEUTRON is not None): | |
| return _IS_NEUTRON | |
| _IS_NEUTRON = nova.network.is_neutron() | |
| return _IS_NEUTRON | |
| def is_auto_disk_config_disabled(auto_disk_config_raw): | |
| auto_disk_config_disabled = False | |
| if (auto_disk_config_raw is not None): | |
| adc_lowered = auto_disk_config_raw.strip().lower() | |
| if (adc_lowered == 'disabled'): | |
| auto_disk_config_disabled = True | |
| return auto_disk_config_disabled | |
| def get_auto_disk_config_from_instance(instance=None, sys_meta=None): | |
| if (sys_meta is None): | |
| sys_meta = instance_sys_meta(instance) | |
| return sys_meta.get('image_auto_disk_config') | |
| def get_auto_disk_config_from_image_props(image_properties): | |
| return image_properties.get('auto_disk_config') | |
| def get_system_metadata_from_image(image_meta, flavor=None): | |
| system_meta = {} | |
| prefix_format = (SM_IMAGE_PROP_PREFIX + '%s') | |
| for (key, value) in image_meta.get('properties', {}).items(): | |
| if (key in SM_SKIP_KEYS): | |
| continue | |
| new_value = safe_truncate(six.text_type(value), 255) | |
| system_meta[(prefix_format % key)] = new_value | |
| for key in SM_INHERITABLE_KEYS: | |
| value = image_meta.get(key) | |
| if ((key == 'min_disk') and flavor): | |
| if (image_meta.get('disk_format') == 'vhd'): | |
| value = flavor['root_gb'] | |
| else: | |
| value = max((value or 0), flavor['root_gb']) | |
| if (value is None): | |
| continue | |
| system_meta[(prefix_format % key)] = value | |
| return system_meta | |
| def get_image_from_system_metadata(system_meta): | |
| image_meta = {} | |
| properties = {} | |
| if (not isinstance(system_meta, dict)): | |
| system_meta = metadata_to_dict(system_meta, include_deleted=True) | |
| for (key, value) in system_meta.items(): | |
| if (value is None): | |
| continue | |
| if key.startswith(SM_IMAGE_PROP_PREFIX): | |
| key = key[len(SM_IMAGE_PROP_PREFIX):] | |
| if (key in SM_SKIP_KEYS): | |
| continue | |
| if (key in SM_INHERITABLE_KEYS): | |
| image_meta[key] = value | |
| else: | |
| properties[key] = value | |
| image_meta['properties'] = properties | |
| return image_meta | |
| def get_image_metadata_from_volume(volume): | |
| properties = copy.copy(volume.get('volume_image_metadata', {})) | |
| image_meta = {'properties': properties} | |
| image_meta['size'] = (volume.get('size', 0) * units.Gi) | |
| for attr in VIM_IMAGE_ATTRIBUTES: | |
| val = properties.pop(attr, None) | |
| if (attr in ('min_ram', 'min_disk')): | |
| image_meta[attr] = int((val or 0)) | |
| image_meta['status'] = 'active' | |
| return image_meta | |
| def get_hash_str(base_str): | |
| 'Returns string that represents MD5 hash of base_str (in hex format).\n\n If base_str is a Unicode string, encode it to UTF-8.\n ' | |
| if isinstance(base_str, six.text_type): | |
| base_str = base_str.encode('utf-8') | |
| return hashlib.md5(base_str).hexdigest() | |
| def get_sha256_str(base_str): | |
| 'Returns string that represents sha256 hash of base_str (in hex format).\n\n sha1 and md5 are known to be breakable, so sha256 is a better option\n when the hash is being used for security purposes. If hashing passwords\n or anything else that needs to be retained for a long period a salted\n hash is better.\n ' | |
| if isinstance(base_str, six.text_type): | |
| base_str = base_str.encode('utf-8') | |
| return hashlib.sha256(base_str).hexdigest() | |
| def get_obj_repr_unicode(obj): | |
| 'Returns a string representation of an object converted to unicode.\n\n In the case of python 3, this just returns the repr() of the object,\n else it converts the repr() to unicode.\n ' | |
| obj_repr = repr(obj) | |
| if (not six.PY3): | |
| obj_repr = six.text_type(obj_repr, 'utf-8') | |
| return obj_repr | |
| def filter_and_format_resource_metadata(resource_type, resource_list, search_filts, metadata_type=None): | |
| "Get all metadata for a list of resources after filtering.\n\n Search_filts is a list of dictionaries, where the values in the dictionary\n can be string or regex string, or a list of strings/regex strings.\n\n Let's call a dict a 'filter block' and an item in the dict\n a 'filter'. A tag is returned if it matches ALL the filters in\n a filter block. If more than one values are specified for a\n filter, a tag is returned if it matches ATLEAST ONE value of the filter. If\n more than one filter blocks are specified, the tag should match ALL the\n filter blocks.\n\n For example:\n\n search_filts = [{'key': ['key1', 'key2'], 'value': 'val1'},\n {'value': 'val2'}]\n\n The filter translates to 'match any tag for which':\n ((key=key1 AND value=val1) OR (key=key2 AND value=val1)) AND\n (value=val2)\n\n This example filter will never match a tag.\n\n :param resource_type: The resource type as a string, e.g. 'instance'\n :param resource_list: List of resource objects\n :param search_filts: Filters to filter metadata to be returned. Can be\n dict (e.g. {'key': 'env', 'value': 'prod'}, or a list of dicts\n (e.g. [{'key': 'env'}, {'value': 'beta'}]. Note that the values\n of the dict can be regular expressions.\n :param metadata_type: Provided to search for a specific metadata type\n (e.g. 'system_metadata')\n\n :returns: List of dicts where each dict is of the form {'key':\n 'somekey', 'value': 'somevalue', 'instance_id':\n 'some-instance-uuid-aaa'} if resource_type is 'instance'.\n " | |
| if isinstance(search_filts, dict): | |
| search_filts = [search_filts] | |
| def _get_id(resource): | |
| if (resource_type == 'instance'): | |
| return resource.get('uuid') | |
| def _match_any(pattern_list, string): | |
| if isinstance(pattern_list, str): | |
| pattern_list = [pattern_list] | |
| return any([re.match(pattern, string) for pattern in pattern_list]) | |
| def _filter_metadata(resource, search_filt, input_metadata): | |
| ids = search_filt.get('resource_id', []) | |
| keys_filter = search_filt.get('key', []) | |
| values_filter = search_filt.get('value', []) | |
| output_metadata = {} | |
| if (ids and (_get_id(resource) not in ids)): | |
| return {} | |
| for (k, v) in input_metadata.items(): | |
| if (keys_filter and values_filter and (not _match_any(keys_filter, k)) and (not _match_any(values_filter, v))): | |
| continue | |
| elif ((keys_filter and (not _match_any(keys_filter, k))) or (values_filter and (not _match_any(values_filter, v)))): | |
| continue | |
| output_metadata[k] = v | |
| return output_metadata | |
| formatted_metadata_list = [] | |
| for res in resource_list: | |
| if (resource_type == 'instance'): | |
| if (metadata_type is None): | |
| metadata_type = 'metadata' | |
| metadata = res.get(metadata_type, {}) | |
| for filt in search_filts: | |
| metadata = _filter_metadata(res, filt, metadata) | |
| for (k, v) in metadata.items(): | |
| formatted_metadata_list.append({'key': k, 'value': v, ('%s_id' % resource_type): _get_id(res)}) | |
| return formatted_metadata_list | |
| def safe_truncate(value, length): | |
| 'Safely truncates unicode strings such that their encoded length is\n no greater than the length provided.\n ' | |
| b_value = encodeutils.safe_encode(value)[:length] | |
| decode_ok = False | |
| while (not decode_ok): | |
| try: | |
| u_value = encodeutils.safe_decode(b_value) | |
| decode_ok = True | |
| except UnicodeDecodeError: | |
| b_value = b_value[:(-1)] | |
| return u_value | |
| def read_cached_file(filename, force_reload=False): | |
| 'Read from a file if it has been modified.\n\n :param force_reload: Whether to reload the file.\n :returns: A tuple with a boolean specifying if the data is fresh\n or not.\n ' | |
| global _FILE_CACHE | |
| if force_reload: | |
| delete_cached_file(filename) | |
| reloaded = False | |
| mtime = os.path.getmtime(filename) | |
| cache_info = _FILE_CACHE.setdefault(filename, {}) | |
| if ((not cache_info) or (mtime > cache_info.get('mtime', 0))): | |
| LOG.debug('Reloading cached file %s', filename) | |
| with open(filename) as fap: | |
| cache_info['data'] = fap.read() | |
| cache_info['mtime'] = mtime | |
| reloaded = True | |
| return (reloaded, cache_info['data']) | |
| def delete_cached_file(filename): | |
| 'Delete cached file if present.\n\n :param filename: filename to delete\n ' | |
| global _FILE_CACHE | |
| if (filename in _FILE_CACHE): | |
| del _FILE_CACHE[filename] | |
| def isotime(at=None): | |
| 'Current time as ISO string,\n as timeutils.isotime() is deprecated\n\n :returns: Current time in ISO format\n ' | |
| if (not at): | |
| at = timeutils.utcnow() | |
| date_string = at.strftime('%Y-%m-%dT%H:%M:%S') | |
| tz = (at.tzinfo.tzname(None) if at.tzinfo else 'UTC') | |
| date_string += ('Z' if (tz == 'UTC') else tz) | |
| return date_string | |
| def strtime(at): | |
| return at.strftime('%Y-%m-%dT%H:%M:%S.%f') | |
| def print_dict(dct, dict_property='Property', dict_value='Value'): | |
| 'Print a `dict` as a table of two columns.\n\n :param dct: `dict` to print\n :param dict_property: name of the first column\n :param wrap: wrapping for the second column\n :param dict_value: header label for the value (second) column\n ' | |
| pt = prettytable.PrettyTable([dict_property, dict_value]) | |
| pt.align = 'l' | |
| for (k, v) in sorted(dct.items()): | |
| if isinstance(v, dict): | |
| v = six.text_type(v) | |
| if (v and isinstance(v, six.string_types) and ('\\n' in v)): | |
| lines = v.strip().split('\\n') | |
| col1 = k | |
| for line in lines: | |
| pt.add_row([col1, line]) | |
| col1 = '' | |
| else: | |
| pt.add_row([k, v]) | |
| if six.PY2: | |
| print encodeutils.safe_encode(pt.get_string()) | |
| else: | |
| print encodeutils.safe_encode(pt.get_string()).decode() | |
| def validate_args(fn, *args, **kwargs): | |
| 'Check that the supplied args are sufficient for calling a function.\n\n >>> validate_args(lambda a: None)\n Traceback (most recent call last):\n ...\n MissingArgs: Missing argument(s): a\n >>> validate_args(lambda a, b, c, d: None, 0, c=1)\n Traceback (most recent call last):\n ...\n MissingArgs: Missing argument(s): b, d\n\n :param fn: the function to check\n :param arg: the positional arguments supplied\n :param kwargs: the keyword arguments supplied\n ' | |
| argspec = inspect.getargspec(fn) | |
| num_defaults = len((argspec.defaults or [])) | |
| required_args = argspec.args[:(len(argspec.args) - num_defaults)] | |
| if (six.get_method_self(fn) is not None): | |
| required_args.pop(0) | |
| missing = [arg for arg in required_args if (arg not in kwargs)] | |
| missing = missing[len(args):] | |
| return missing | |
Xet Storage Details
- Size:
- 42.1 kB
- Xet hash:
- 37477f4fafed3f2b1afbad7c46b01ff66f90f09e465edc30a0cb201454f36b97
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.