2010-05-27 23:05:26 -07:00
|
|
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
|
2010-06-23 22:04:16 -07:00
|
|
|
|
|
|
|
# Copyright 2010 United States Government as represented by the
|
2010-06-23 23:15:06 -07:00
|
|
|
# Administrator of the National Aeronautics and Space Administration.
|
2011-02-23 12:05:49 -08:00
|
|
|
# Copyright 2011 Justin Santa Barbara
|
2010-06-23 22:04:16 -07: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
|
|
|
|
#
|
2010-05-27 23:05:26 -07:00
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
2010-06-23 22:04:16 -07:00
|
|
|
# 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.
|
2010-05-27 23:05:26 -07:00
|
|
|
|
|
|
|
"""
|
|
|
|
System-level utilities and helper functions.
|
|
|
|
"""
|
|
|
|
|
2011-02-17 22:09:26 +00:00
|
|
|
import base64
|
2010-08-16 14:16:21 +02:00
|
|
|
import datetime
|
2011-03-01 20:49:46 +01:00
|
|
|
import functools
|
2010-07-08 10:53:27 -07:00
|
|
|
import inspect
|
2010-12-22 17:53:42 -08:00
|
|
|
import json
|
2011-02-28 12:37:02 +01:00
|
|
|
import lockfile
|
2011-03-01 20:49:46 +01:00
|
|
|
import netaddr
|
2010-07-07 12:24:24 -07:00
|
|
|
import os
|
2010-05-27 23:05:26 -07:00
|
|
|
import random
|
2011-03-01 20:49:46 +01:00
|
|
|
import re
|
2010-07-14 16:27:18 -05:00
|
|
|
import socket
|
2011-02-17 22:09:26 +00:00
|
|
|
import string
|
2010-11-23 21:48:32 +00:00
|
|
|
import struct
|
2010-07-08 10:53:27 -07:00
|
|
|
import sys
|
2010-12-15 11:23:33 -08:00
|
|
|
import time
|
2011-02-23 14:07:08 -08:00
|
|
|
import types
|
2010-10-25 19:21:09 +09:00
|
|
|
from xml.sax import saxutils
|
2010-05-27 23:05:26 -07:00
|
|
|
|
2010-10-25 03:45:19 +09:00
|
|
|
from eventlet import event
|
|
|
|
from eventlet import greenthread
|
2011-03-22 10:35:43 +01:00
|
|
|
from eventlet import semaphore
|
2011-02-14 21:06:16 +01:00
|
|
|
from eventlet.green import subprocess
|
2011-03-09 15:33:20 -05:00
|
|
|
None
|
2010-07-28 12:53:27 -07:00
|
|
|
from nova import exception
|
2010-09-07 21:53:40 -07:00
|
|
|
from nova.exception import ProcessExecutionError
|
2011-02-28 23:31:09 +01:00
|
|
|
from nova import flags
|
2011-01-04 00:23:35 -05:00
|
|
|
from nova import log as logging
|
2010-06-10 18:39:07 +01:00
|
|
|
|
2010-08-16 14:16:21 +02:00
|
|
|
|
2011-01-04 00:23:35 -05:00
|
|
|
LOG = logging.getLogger("nova.utils")
|
2010-07-26 17:00:50 -04:00
|
|
|
TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
|
2011-02-28 23:31:09 +01:00
|
|
|
FLAGS = flags.FLAGS
|
2010-06-10 18:39:07 +01:00
|
|
|
|
2010-10-21 11:49:51 -07:00
|
|
|
|
2010-07-28 12:53:27 -07:00
|
|
|
def import_class(import_str):
|
|
|
|
"""Returns a class from a string including module and class"""
|
|
|
|
mod_str, _sep, class_str = import_str.rpartition('.')
|
|
|
|
try:
|
|
|
|
__import__(mod_str)
|
|
|
|
return getattr(sys.modules[mod_str], class_str)
|
2010-12-26 14:08:38 +00:00
|
|
|
except (ImportError, ValueError, AttributeError), exc:
|
2011-02-21 13:46:41 -08:00
|
|
|
LOG.debug(_('Inner Exception: %s'), exc)
|
2010-12-11 15:23:40 -05:00
|
|
|
raise exception.NotFound(_('Class %s cannot be found') % class_str)
|
2010-06-10 18:39:07 +01:00
|
|
|
|
2010-10-21 11:49:51 -07:00
|
|
|
|
2010-08-27 23:10:57 -07:00
|
|
|
def import_object(import_str):
|
|
|
|
"""Returns an object including a module or module and class"""
|
|
|
|
try:
|
2010-08-30 00:55:19 -07:00
|
|
|
__import__(import_str)
|
|
|
|
return sys.modules[import_str]
|
|
|
|
except ImportError:
|
|
|
|
cls = import_class(import_str)
|
2010-08-27 23:10:57 -07:00
|
|
|
return cls()
|
2010-08-16 14:16:21 +02:00
|
|
|
|
2010-10-21 11:49:51 -07:00
|
|
|
|
2010-11-23 21:48:32 +00:00
|
|
|
def vpn_ping(address, port, timeout=0.05, session_id=None):
|
|
|
|
"""Sends a vpn negotiation packet and returns the server session.
|
|
|
|
|
|
|
|
Returns False on a failure. Basic packet structure is below.
|
|
|
|
|
|
|
|
Client packet (14 bytes)::
|
|
|
|
0 1 8 9 13
|
|
|
|
+-+--------+-----+
|
|
|
|
|x| cli_id |?????|
|
|
|
|
+-+--------+-----+
|
|
|
|
x = packet identifier 0x38
|
|
|
|
cli_id = 64 bit identifier
|
|
|
|
? = unknown, probably flags/padding
|
|
|
|
|
|
|
|
Server packet (26 bytes)::
|
|
|
|
0 1 8 9 13 14 21 2225
|
|
|
|
+-+--------+-----+--------+----+
|
|
|
|
|x| srv_id |?????| cli_id |????|
|
|
|
|
+-+--------+-----+--------+----+
|
|
|
|
x = packet identifier 0x40
|
|
|
|
cli_id = 64 bit identifier
|
|
|
|
? = unknown, probably flags/padding
|
|
|
|
bit 9 was 1 and the rest were 0 in testing
|
|
|
|
"""
|
|
|
|
if session_id is None:
|
|
|
|
session_id = random.randint(0, 0xffffffffffffffff)
|
|
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
|
|
data = struct.pack("!BQxxxxxx", 0x38, 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):
|
|
|
|
print struct.calcsize(fmt)
|
|
|
|
return False
|
|
|
|
(identifier, server_sess, client_sess) = struct.unpack(fmt, received)
|
|
|
|
if identifier == 0x40 and client_sess == session_id:
|
|
|
|
return server_sess
|
|
|
|
|
|
|
|
|
2010-05-27 23:05:26 -07:00
|
|
|
def fetchfile(url, target):
|
2011-01-04 00:23:35 -05:00
|
|
|
LOG.debug(_("Fetching %s") % url)
|
2010-05-27 23:05:26 -07:00
|
|
|
# c = pycurl.Curl()
|
|
|
|
# fp = open(target, "wb")
|
|
|
|
# c.setopt(c.URL, url)
|
|
|
|
# c.setopt(c.WRITEDATA, fp)
|
|
|
|
# c.perform()
|
|
|
|
# c.close()
|
|
|
|
# fp.close()
|
2011-03-08 01:01:41 -05:00
|
|
|
execute("curl", "--fail", url, "-o", target)
|
2010-05-27 23:05:26 -07:00
|
|
|
|
|
|
|
|
2011-03-09 00:30:05 -05:00
|
|
|
def execute(*cmd, **kwargs):
|
2011-03-14 10:46:26 +01:00
|
|
|
process_input = kwargs.pop('process_input', None)
|
|
|
|
addl_env = kwargs.pop('addl_env', None)
|
|
|
|
check_exit_code = kwargs.pop('check_exit_code', 0)
|
|
|
|
delay_on_retry = kwargs.pop('delay_on_retry', True)
|
|
|
|
attempts = kwargs.pop('attempts', 1)
|
|
|
|
if len(kwargs):
|
|
|
|
raise exception.Error(_('Got unknown keyword args '
|
|
|
|
'to utils.execute: %r') % kwargs)
|
2011-03-09 15:33:20 -05:00
|
|
|
cmd = map(str, cmd)
|
2010-10-21 11:49:51 -07:00
|
|
|
|
2011-02-18 22:10:06 +01:00
|
|
|
while attempts > 0:
|
|
|
|
attempts -= 1
|
|
|
|
try:
|
2011-03-09 23:39:12 +01:00
|
|
|
LOG.debug(_("Running cmd (subprocess): %s"), ' '.join(cmd))
|
2011-02-18 22:10:06 +01:00
|
|
|
env = os.environ.copy()
|
|
|
|
if addl_env:
|
|
|
|
env.update(addl_env)
|
2011-03-14 10:46:26 +01:00
|
|
|
obj = subprocess.Popen(cmd,
|
|
|
|
stdin=subprocess.PIPE,
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.PIPE,
|
|
|
|
env=env)
|
2011-02-18 22:10:06 +01:00
|
|
|
result = None
|
2011-04-18 15:53:09 -05:00
|
|
|
if process_input is not None:
|
2011-02-18 22:10:06 +01:00
|
|
|
result = obj.communicate(process_input)
|
|
|
|
else:
|
|
|
|
result = obj.communicate()
|
|
|
|
obj.stdin.close()
|
|
|
|
if obj.returncode:
|
|
|
|
LOG.debug(_("Result was %s") % obj.returncode)
|
2011-03-09 23:39:12 +01:00
|
|
|
if type(check_exit_code) == types.IntType \
|
|
|
|
and obj.returncode != check_exit_code:
|
2011-02-18 22:10:06 +01:00
|
|
|
(stdout, stderr) = result
|
|
|
|
raise ProcessExecutionError(exit_code=obj.returncode,
|
|
|
|
stdout=stdout,
|
|
|
|
stderr=stderr,
|
2011-03-09 23:39:12 +01:00
|
|
|
cmd=' '.join(cmd))
|
2011-02-18 22:10:06 +01:00
|
|
|
return result
|
|
|
|
except ProcessExecutionError:
|
|
|
|
if not attempts:
|
|
|
|
raise
|
|
|
|
else:
|
2011-03-07 21:54:25 +01:00
|
|
|
LOG.debug(_("%r failed. Retrying."), cmd)
|
2011-03-14 10:46:26 +01:00
|
|
|
if delay_on_retry:
|
|
|
|
greenthread.sleep(random.randint(20, 200) / 100.0)
|
2011-03-23 13:39:01 -07:00
|
|
|
finally:
|
|
|
|
# NOTE(termie): this appears to be necessary to let the subprocess
|
|
|
|
# call clean something up in between calls, without
|
|
|
|
# it two execute calls in a row hangs the second one
|
|
|
|
greenthread.sleep(0)
|
2010-05-27 23:05:26 -07:00
|
|
|
|
2010-06-10 18:39:07 +01:00
|
|
|
|
2011-02-04 13:07:17 -06:00
|
|
|
def ssh_execute(ssh, cmd, process_input=None,
|
|
|
|
addl_env=None, check_exit_code=True):
|
2011-03-08 01:01:41 -05:00
|
|
|
LOG.debug(_("Running cmd (SSH): %s"), ' '.join(cmd))
|
2011-02-04 13:07:17 -06:00
|
|
|
if addl_env:
|
|
|
|
raise exception.Error("Environment not supported over SSH")
|
|
|
|
|
|
|
|
if process_input:
|
|
|
|
# This is (probably) fixable if we need it...
|
|
|
|
raise exception.Error("process_input not supported over SSH")
|
|
|
|
|
|
|
|
stdin_stream, stdout_stream, stderr_stream = ssh.exec_command(cmd)
|
|
|
|
channel = stdout_stream.channel
|
|
|
|
|
|
|
|
#stdin.write('process_input would go here')
|
|
|
|
#stdin.flush()
|
|
|
|
|
|
|
|
# NOTE(justinsb): This seems suspicious...
|
|
|
|
# ...other SSH clients have buffering issues with this approach
|
|
|
|
stdout = stdout_stream.read()
|
|
|
|
stderr = stderr_stream.read()
|
|
|
|
stdin_stream.close()
|
|
|
|
|
|
|
|
exit_status = channel.recv_exit_status()
|
|
|
|
|
|
|
|
# exit_status == -1 if no exit code was returned
|
|
|
|
if exit_status != -1:
|
|
|
|
LOG.debug(_("Result was %s") % exit_status)
|
|
|
|
if check_exit_code and exit_status != 0:
|
|
|
|
raise exception.ProcessExecutionError(exit_code=exit_status,
|
|
|
|
stdout=stdout,
|
|
|
|
stderr=stderr,
|
2011-03-08 01:01:41 -05:00
|
|
|
cmd=' '.join(cmd))
|
2011-02-04 13:07:17 -06:00
|
|
|
|
|
|
|
return (stdout, stderr)
|
|
|
|
|
2011-02-09 11:18:48 -08:00
|
|
|
|
2010-05-27 23:05:26 -07:00
|
|
|
def abspath(s):
|
|
|
|
return os.path.join(os.path.dirname(__file__), s)
|
|
|
|
|
2010-06-10 18:39:07 +01:00
|
|
|
|
2010-11-01 16:25:56 -07:00
|
|
|
def novadir():
|
|
|
|
import nova
|
2010-09-17 19:28:10 -07:00
|
|
|
return os.path.abspath(nova.__file__).split('nova/__init__.pyc')[0]
|
|
|
|
|
|
|
|
|
2010-05-27 23:05:26 -07:00
|
|
|
def default_flagfile(filename='nova.conf'):
|
|
|
|
for arg in sys.argv:
|
|
|
|
if arg.find('flagfile') != -1:
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
if not os.path.isabs(filename):
|
|
|
|
# turn relative filename into an absolute path
|
|
|
|
script_dir = os.path.dirname(inspect.stack()[-1][1])
|
|
|
|
filename = os.path.abspath(os.path.join(script_dir, filename))
|
|
|
|
if os.path.exists(filename):
|
2010-10-21 11:49:51 -07:00
|
|
|
flagfile = ['--flagfile=%s' % filename]
|
|
|
|
sys.argv = sys.argv[:1] + flagfile + sys.argv[1:]
|
2010-05-27 23:05:26 -07:00
|
|
|
|
2010-06-10 18:39:07 +01:00
|
|
|
|
2010-05-27 23:05:26 -07:00
|
|
|
def debug(arg):
|
2011-01-04 00:23:35 -05:00
|
|
|
LOG.debug(_('debug in callback: %s'), arg)
|
2010-05-27 23:05:26 -07:00
|
|
|
return arg
|
|
|
|
|
2010-06-10 18:39:07 +01:00
|
|
|
|
2011-03-09 00:30:05 -05:00
|
|
|
def runthis(prompt, *cmd, **kwargs):
|
|
|
|
LOG.debug(_("Running %s"), (" ".join(cmd)))
|
|
|
|
rv, err = execute(*cmd, **kwargs)
|
2010-05-27 23:05:26 -07:00
|
|
|
|
|
|
|
|
|
|
|
def generate_uid(topic, size=8):
|
2010-10-25 17:20:10 -07:00
|
|
|
characters = '01234567890abcdefghijklmnopqrstuvwxyz'
|
|
|
|
choices = [random.choice(characters) for x in xrange(size)]
|
|
|
|
return '%s-%s' % (topic, ''.join(choices))
|
2010-05-27 23:05:26 -07:00
|
|
|
|
2010-06-10 18:39:07 +01:00
|
|
|
|
2010-05-27 23:05:26 -07:00
|
|
|
def generate_mac():
|
2010-10-21 11:49:51 -07:00
|
|
|
mac = [0x02, 0x16, 0x3e,
|
|
|
|
random.randint(0x00, 0x7f),
|
|
|
|
random.randint(0x00, 0xff),
|
|
|
|
random.randint(0x00, 0xff)]
|
2010-05-27 23:05:26 -07:00
|
|
|
return ':'.join(map(lambda x: "%02x" % x, mac))
|
|
|
|
|
2010-06-10 18:39:07 +01:00
|
|
|
|
2011-03-15 11:24:07 -07:00
|
|
|
# Default symbols to use for passwords. Avoids visually confusing characters.
|
|
|
|
# ~6 bits per symbol
|
|
|
|
DEFAULT_PASSWORD_SYMBOLS = ("23456789" # Removed: 0,1
|
|
|
|
"ABCDEFGHJKLMNPQRSTUVWXYZ" # Removed: I, O
|
|
|
|
"abcdefghijkmnopqrstuvwxyz") # Removed: l
|
|
|
|
|
|
|
|
|
|
|
|
# ~5 bits per symbol
|
|
|
|
EASIER_PASSWORD_SYMBOLS = ("23456789" # Removed: 0, 1
|
|
|
|
"ABCDEFGHJKLMNPQRSTUVWXYZ") # Removed: I, O
|
|
|
|
|
|
|
|
|
|
|
|
def generate_password(length=20, symbols=DEFAULT_PASSWORD_SYMBOLS):
|
|
|
|
"""Generate a random password from the supplied symbols.
|
2011-03-14 20:48:33 -07:00
|
|
|
|
|
|
|
Believed to be reasonably secure (with a reasonable password length!)
|
2011-02-17 22:09:26 +00:00
|
|
|
"""
|
2011-03-15 11:24:07 -07:00
|
|
|
r = random.SystemRandom()
|
|
|
|
return "".join([r.choice(symbols) for _i in xrange(length)])
|
2011-02-17 22:09:26 +00:00
|
|
|
|
|
|
|
|
2010-05-27 23:05:26 -07:00
|
|
|
def last_octet(address):
|
|
|
|
return int(address.split(".")[-1])
|
|
|
|
|
2010-06-10 18:39:07 +01:00
|
|
|
|
2010-12-24 20:38:49 +09:00
|
|
|
def get_my_linklocal(interface):
|
|
|
|
try:
|
2011-03-08 01:01:41 -05:00
|
|
|
if_str = execute("ip", "-f", "inet6", "-o", "addr", "show", interface)
|
2011-01-19 11:13:33 +09:00
|
|
|
condition = "\s+inet6\s+([0-9a-f:]+)/\d+\s+scope\s+link"
|
2010-12-24 20:38:49 +09:00
|
|
|
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:
|
2011-01-19 11:13:33 +09:00
|
|
|
raise exception.Error(_("Link Local address is not found.:%s")
|
|
|
|
% if_str)
|
2011-01-18 11:41:05 +09:00
|
|
|
except Exception as ex:
|
2011-01-27 13:52:10 -06:00
|
|
|
raise exception.Error(_("Couldn't get Link Local IP of %(interface)s"
|
|
|
|
" :%(ex)s") % locals())
|
2010-12-24 20:38:49 +09:00
|
|
|
|
|
|
|
|
|
|
|
def to_global_ipv6(prefix, mac):
|
2011-03-24 00:36:07 +03:00
|
|
|
try:
|
|
|
|
mac64 = netaddr.EUI(mac).eui64().words
|
|
|
|
int_addr = int(''.join(['%02x' % i for i in mac64]), 16)
|
|
|
|
mac64_addr = netaddr.IPAddress(int_addr)
|
|
|
|
maskIP = netaddr.IPNetwork(prefix).ip
|
|
|
|
return (mac64_addr ^ netaddr.IPAddress('::0200:0:0:0') | maskIP).\
|
2011-03-24 23:00:16 +03:00
|
|
|
format()
|
2011-03-24 00:36:07 +03:00
|
|
|
except TypeError:
|
2011-03-24 00:56:56 +03:00
|
|
|
raise TypeError(_("Bad mac for to_global_ipv6: %s") % mac)
|
2010-12-24 20:38:49 +09:00
|
|
|
|
|
|
|
|
|
|
|
def to_mac(ipv6_address):
|
|
|
|
address = netaddr.IPAddress(ipv6_address)
|
|
|
|
mask1 = netaddr.IPAddress("::ffff:ffff:ffff:ffff")
|
|
|
|
mask2 = netaddr.IPAddress("::0200:0:0:0")
|
|
|
|
mac64 = netaddr.EUI(int(address & mask1 ^ mask2)).words
|
|
|
|
return ":".join(["%02x" % i for i in mac64[0:3] + mac64[5:8]])
|
|
|
|
|
|
|
|
|
2010-12-15 11:23:33 -08:00
|
|
|
def utcnow():
|
|
|
|
"""Overridable version of datetime.datetime.utcnow."""
|
|
|
|
if utcnow.override_time:
|
|
|
|
return utcnow.override_time
|
|
|
|
return datetime.datetime.utcnow()
|
|
|
|
|
|
|
|
|
|
|
|
utcnow.override_time = None
|
|
|
|
|
|
|
|
|
2011-03-23 17:15:41 -05:00
|
|
|
def is_older_than(before, seconds):
|
2011-03-24 10:30:09 -05:00
|
|
|
"""Return True if before is older than seconds"""
|
|
|
|
return utcnow() - before > datetime.timedelta(seconds=seconds)
|
2011-03-23 14:41:35 -05:00
|
|
|
|
|
|
|
|
2010-12-15 11:23:33 -08:00
|
|
|
def utcnow_ts():
|
|
|
|
"""Timestamp version of our utcnow function."""
|
|
|
|
return time.mktime(utcnow().timetuple())
|
|
|
|
|
|
|
|
|
|
|
|
def set_time_override(override_time=datetime.datetime.utcnow()):
|
|
|
|
"""Override utils.utcnow to return a constant time."""
|
|
|
|
utcnow.override_time = override_time
|
|
|
|
|
|
|
|
|
|
|
|
def advance_time_delta(timedelta):
|
|
|
|
"""Advance overriden time using a datetime.timedelta."""
|
|
|
|
assert(not utcnow.override_time is None)
|
|
|
|
utcnow.override_time += timedelta
|
|
|
|
|
|
|
|
|
|
|
|
def advance_time_seconds(seconds):
|
|
|
|
"""Advance overriden time by seconds."""
|
|
|
|
advance_time_delta(datetime.timedelta(0, seconds))
|
|
|
|
|
|
|
|
|
|
|
|
def clear_time_override():
|
|
|
|
"""Remove the overridden time."""
|
|
|
|
utcnow.override_time = None
|
|
|
|
|
|
|
|
|
2010-07-08 10:53:27 -07:00
|
|
|
def isotime(at=None):
|
2010-12-15 11:23:33 -08:00
|
|
|
"""Returns iso formatted utcnow."""
|
2010-07-08 10:53:27 -07:00
|
|
|
if not at:
|
2010-12-15 11:23:33 -08:00
|
|
|
at = utcnow()
|
2010-07-26 17:00:50 -04:00
|
|
|
return at.strftime(TIME_FORMAT)
|
|
|
|
|
2010-08-16 14:16:21 +02:00
|
|
|
|
2010-07-26 17:00:50 -04:00
|
|
|
def parse_isotime(timestr):
|
2010-12-15 11:23:33 -08:00
|
|
|
"""Turn an iso formatted time back into a datetime"""
|
2010-08-16 14:16:21 +02:00
|
|
|
return datetime.datetime.strptime(timestr, TIME_FORMAT)
|
2010-08-19 12:28:45 +02:00
|
|
|
|
|
|
|
|
2010-11-11 19:52:36 -06:00
|
|
|
def parse_mailmap(mailmap='.mailmap'):
|
|
|
|
mapping = {}
|
|
|
|
if os.path.exists(mailmap):
|
|
|
|
fp = open(mailmap, 'r')
|
|
|
|
for l in fp:
|
|
|
|
l = l.strip()
|
|
|
|
if not l.startswith('#') and ' ' in l:
|
|
|
|
canonical_email, alias = l.split(' ')
|
|
|
|
mapping[alias] = canonical_email
|
|
|
|
return mapping
|
|
|
|
|
2010-11-23 21:58:46 +01:00
|
|
|
|
2010-11-11 19:52:36 -06:00
|
|
|
def str_dict_replace(s, mapping):
|
|
|
|
for s1, s2 in mapping.iteritems():
|
|
|
|
s = s.replace(s1, s2)
|
|
|
|
return s
|
|
|
|
|
2010-08-19 12:28:45 +02:00
|
|
|
|
|
|
|
class LazyPluggable(object):
|
|
|
|
"""A pluggable backend loaded lazily based on some value."""
|
2010-08-27 23:10:57 -07:00
|
|
|
|
2010-08-19 12:28:45 +02:00
|
|
|
def __init__(self, pivot, **backends):
|
|
|
|
self.__backends = backends
|
|
|
|
self.__pivot = pivot
|
|
|
|
self.__backend = None
|
2010-08-27 23:10:57 -07:00
|
|
|
|
2010-08-19 12:28:45 +02:00
|
|
|
def __get_backend(self):
|
|
|
|
if not self.__backend:
|
|
|
|
backend_name = self.__pivot.value
|
|
|
|
if backend_name not in self.__backends:
|
2010-12-11 15:23:40 -05:00
|
|
|
raise exception.Error(_('Invalid backend: %s') % backend_name)
|
2010-08-27 23:10:57 -07:00
|
|
|
|
2010-08-19 12:28:45 +02:00
|
|
|
backend = self.__backends[backend_name]
|
|
|
|
if type(backend) == type(tuple()):
|
|
|
|
name = backend[0]
|
|
|
|
fromlist = backend[1]
|
|
|
|
else:
|
|
|
|
name = backend
|
|
|
|
fromlist = backend
|
2010-08-27 23:10:57 -07:00
|
|
|
|
2010-08-19 12:28:45 +02:00
|
|
|
self.__backend = __import__(name, None, None, fromlist)
|
2011-01-04 00:23:35 -05:00
|
|
|
LOG.debug(_('backend %s'), self.__backend)
|
2010-08-19 12:28:45 +02:00
|
|
|
return self.__backend
|
2010-08-27 23:10:57 -07:00
|
|
|
|
2010-08-19 12:28:45 +02:00
|
|
|
def __getattr__(self, key):
|
|
|
|
backend = self.__get_backend()
|
|
|
|
return getattr(backend, key)
|
|
|
|
|
2010-10-21 11:49:51 -07:00
|
|
|
|
2011-01-06 21:37:33 -06:00
|
|
|
class LoopingCallDone(Exception):
|
|
|
|
"""The poll-function passed to LoopingCall can raise this exception to
|
2011-01-06 23:38:01 -06:00
|
|
|
break out of the loop normally. This is somewhat analogous to
|
|
|
|
StopIteration.
|
2011-01-06 21:37:33 -06:00
|
|
|
|
|
|
|
An optional return-value can be included as the argument to the exception;
|
|
|
|
this return-value will be returned by LoopingCall.wait()
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, retvalue=True):
|
|
|
|
""":param retvalue: Value that LoopingCall.wait() should return"""
|
|
|
|
self.retvalue = retvalue
|
|
|
|
|
|
|
|
|
2010-10-25 03:45:19 +09:00
|
|
|
class LoopingCall(object):
|
|
|
|
def __init__(self, f=None, *args, **kw):
|
|
|
|
self.args = args
|
|
|
|
self.kw = kw
|
|
|
|
self.f = f
|
|
|
|
self._running = False
|
|
|
|
|
|
|
|
def start(self, interval, now=True):
|
|
|
|
self._running = True
|
|
|
|
done = event.Event()
|
2010-12-16 10:52:30 -08:00
|
|
|
|
2010-10-25 03:45:19 +09:00
|
|
|
def _inner():
|
|
|
|
if not now:
|
|
|
|
greenthread.sleep(interval)
|
|
|
|
try:
|
|
|
|
while self._running:
|
|
|
|
self.f(*self.args, **self.kw)
|
|
|
|
greenthread.sleep(interval)
|
2011-01-06 21:37:33 -06:00
|
|
|
except LoopingCallDone, e:
|
|
|
|
self.stop()
|
|
|
|
done.send(e.retvalue)
|
2010-10-25 03:45:19 +09:00
|
|
|
except Exception:
|
2010-12-14 16:05:39 -08:00
|
|
|
logging.exception('in looping call')
|
2010-10-25 03:45:19 +09:00
|
|
|
done.send_exception(*sys.exc_info())
|
|
|
|
return
|
2011-01-06 21:37:33 -06:00
|
|
|
else:
|
|
|
|
done.send(True)
|
2010-12-09 15:19:56 -08:00
|
|
|
|
|
|
|
self.done = done
|
2010-12-16 10:52:30 -08:00
|
|
|
|
2010-10-25 03:45:19 +09:00
|
|
|
greenthread.spawn(_inner)
|
2010-12-09 15:19:56 -08:00
|
|
|
return self.done
|
2010-12-16 10:52:30 -08:00
|
|
|
|
2010-10-25 03:45:19 +09:00
|
|
|
def stop(self):
|
|
|
|
self._running = False
|
|
|
|
|
2010-12-09 15:19:56 -08:00
|
|
|
def wait(self):
|
|
|
|
return self.done.wait()
|
2010-10-25 19:21:09 +09:00
|
|
|
|
|
|
|
|
|
|
|
def xhtml_escape(value):
|
|
|
|
"""Escapes a string so it is valid within XML or XHTML.
|
2010-10-26 15:37:32 -07:00
|
|
|
|
2010-10-25 19:21:09 +09:00
|
|
|
Code is directly from the utf8 function in
|
|
|
|
http://github.com/facebook/tornado/blob/master/tornado/escape.py
|
2010-10-26 15:37:32 -07:00
|
|
|
|
2010-10-25 19:21:09 +09:00
|
|
|
"""
|
|
|
|
return saxutils.escape(value, {'"': """})
|
|
|
|
|
|
|
|
|
|
|
|
def utf8(value):
|
|
|
|
"""Try to turn a string into utf-8 if possible.
|
|
|
|
|
|
|
|
Code is directly from the utf8 function in
|
|
|
|
http://github.com/facebook/tornado/blob/master/tornado/escape.py
|
|
|
|
|
|
|
|
"""
|
|
|
|
if isinstance(value, unicode):
|
|
|
|
return value.encode("utf-8")
|
|
|
|
assert isinstance(value, str)
|
|
|
|
return value
|
2010-12-22 17:53:42 -08:00
|
|
|
|
|
|
|
|
|
|
|
def to_primitive(value):
|
|
|
|
if type(value) is type([]) or type(value) is type((None,)):
|
|
|
|
o = []
|
|
|
|
for v in value:
|
|
|
|
o.append(to_primitive(v))
|
|
|
|
return o
|
|
|
|
elif type(value) is type({}):
|
|
|
|
o = {}
|
|
|
|
for k, v in value.iteritems():
|
|
|
|
o[k] = to_primitive(v)
|
|
|
|
return o
|
|
|
|
elif isinstance(value, datetime.datetime):
|
|
|
|
return str(value)
|
2011-01-07 16:03:53 -08:00
|
|
|
elif hasattr(value, 'iteritems'):
|
|
|
|
return to_primitive(dict(value.iteritems()))
|
|
|
|
elif hasattr(value, '__iter__'):
|
|
|
|
return to_primitive(list(value))
|
2010-12-22 17:53:42 -08:00
|
|
|
else:
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
def dumps(value):
|
|
|
|
try:
|
|
|
|
return json.dumps(value)
|
|
|
|
except TypeError:
|
|
|
|
pass
|
|
|
|
return json.dumps(to_primitive(value))
|
|
|
|
|
|
|
|
|
|
|
|
def loads(s):
|
|
|
|
return json.loads(s)
|
2011-02-17 22:09:26 +00:00
|
|
|
|
|
|
|
|
2011-03-22 10:35:43 +01:00
|
|
|
_semaphores = {}
|
|
|
|
|
|
|
|
|
|
|
|
class _NoopContextManager(object):
|
|
|
|
def __enter__(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def synchronized(name, external=False):
|
|
|
|
"""Synchronization decorator
|
|
|
|
|
|
|
|
Decorating a method like so:
|
|
|
|
@synchronized('mylock')
|
|
|
|
def foo(self, *args):
|
|
|
|
...
|
|
|
|
|
|
|
|
ensures that only one thread will execute the bar method at a time.
|
|
|
|
|
|
|
|
Different methods can share the same lock:
|
|
|
|
@synchronized('mylock')
|
|
|
|
def foo(self, *args):
|
|
|
|
...
|
|
|
|
|
|
|
|
@synchronized('mylock')
|
|
|
|
def bar(self, *args):
|
|
|
|
...
|
|
|
|
|
|
|
|
This way only one of either foo or bar can be executing at a time.
|
|
|
|
|
|
|
|
The external keyword argument denotes whether this lock should work across
|
|
|
|
multiple processes. This means that if two different workers both run a
|
|
|
|
a method decorated with @synchronized('mylock', external=True), only one
|
|
|
|
of them will execute at a time.
|
|
|
|
"""
|
|
|
|
|
2011-02-28 12:37:02 +01:00
|
|
|
def wrap(f):
|
2011-03-01 20:49:46 +01:00
|
|
|
@functools.wraps(f)
|
2011-02-28 12:37:02 +01:00
|
|
|
def inner(*args, **kwargs):
|
2011-03-22 14:14:47 +01:00
|
|
|
# NOTE(soren): If we ever go natively threaded, this will be racy.
|
|
|
|
# See http://stackoverflow.com/questions/5390569/dyn\
|
|
|
|
# amically-allocating-and-destroying-mutexes
|
|
|
|
if name not in _semaphores:
|
|
|
|
_semaphores[name] = semaphore.Semaphore()
|
|
|
|
sem = _semaphores[name]
|
2011-03-22 10:35:43 +01:00
|
|
|
LOG.debug(_('Attempting to grab semaphore "%(lock)s" for method '
|
|
|
|
'"%(method)s"...' % {"lock": name,
|
2011-03-15 16:21:22 -05:00
|
|
|
"method": f.__name__}))
|
2011-03-22 10:35:43 +01:00
|
|
|
with sem:
|
|
|
|
if external:
|
|
|
|
LOG.debug(_('Attempting to grab file lock "%(lock)s" for '
|
|
|
|
'method "%(method)s"...' %
|
|
|
|
{"lock": name, "method": f.__name__}))
|
|
|
|
lock_file_path = os.path.join(FLAGS.lock_path,
|
|
|
|
'nova-%s.lock' % name)
|
|
|
|
lock = lockfile.FileLock(lock_file_path)
|
|
|
|
else:
|
|
|
|
lock = _NoopContextManager()
|
|
|
|
|
|
|
|
with lock:
|
2011-03-22 14:14:47 +01:00
|
|
|
retval = f(*args, **kwargs)
|
2011-03-22 10:35:43 +01:00
|
|
|
|
2011-03-22 14:14:47 +01:00
|
|
|
# If no-one else is waiting for it, delete it.
|
|
|
|
# See note about possible raciness above.
|
|
|
|
if not sem.balance < 1:
|
|
|
|
del _semaphores[name]
|
|
|
|
|
|
|
|
return retval
|
2011-02-28 12:37:02 +01:00
|
|
|
return inner
|
|
|
|
return wrap
|
|
|
|
|
|
|
|
|
2011-02-23 14:07:08 -08:00
|
|
|
def get_from_path(items, path):
|
|
|
|
""" Returns a list of items matching the specified path. Takes an
|
|
|
|
XPath-like expression e.g. prop1/prop2/prop3, and for each item in items,
|
|
|
|
looks up items[prop1][prop2][prop3]. Like XPath, if any of the
|
|
|
|
intermediate results are lists it will treat each list item individually.
|
|
|
|
A 'None' in items or any child expressions will be ignored, this function
|
|
|
|
will not throw because of None (anywhere) in items. The returned list
|
|
|
|
will contain no None values."""
|
2011-02-23 12:05:49 -08:00
|
|
|
|
2011-02-23 14:07:08 -08:00
|
|
|
if path is None:
|
2011-02-23 12:05:49 -08:00
|
|
|
raise exception.Error("Invalid mini_xpath")
|
|
|
|
|
2011-02-23 14:07:08 -08:00
|
|
|
(first_token, sep, remainder) = path.partition("/")
|
2011-02-23 12:05:49 -08:00
|
|
|
|
|
|
|
if first_token == "":
|
|
|
|
raise exception.Error("Invalid mini_xpath")
|
|
|
|
|
|
|
|
results = []
|
|
|
|
|
|
|
|
if items is None:
|
|
|
|
return results
|
|
|
|
|
2011-02-23 12:36:09 -08:00
|
|
|
if not isinstance(items, types.ListType):
|
|
|
|
# Wrap single objects in a list
|
|
|
|
items = [items]
|
|
|
|
|
2011-02-23 12:05:49 -08:00
|
|
|
for item in items:
|
|
|
|
if item is None:
|
|
|
|
continue
|
|
|
|
get_method = getattr(item, "get", None)
|
|
|
|
if get_method is None:
|
|
|
|
continue
|
|
|
|
child = get_method(first_token)
|
|
|
|
if child is None:
|
|
|
|
continue
|
|
|
|
if isinstance(child, types.ListType):
|
|
|
|
# Flatten intermediate lists
|
|
|
|
for x in child:
|
|
|
|
results.append(x)
|
|
|
|
else:
|
|
|
|
results.append(child)
|
|
|
|
|
|
|
|
if not sep:
|
|
|
|
# No more tokens
|
|
|
|
return results
|
|
|
|
else:
|
2011-02-23 14:07:08 -08:00
|
|
|
return get_from_path(results, remainder)
|
2011-03-22 20:26:45 +00:00
|
|
|
|
|
|
|
|
|
|
|
def flatten_dict(dict_, flattened=None):
|
|
|
|
"""Recursively flatten a nested dictionary"""
|
|
|
|
flattened = flattened or {}
|
|
|
|
for key, value in dict_.iteritems():
|
|
|
|
if hasattr(value, 'iteritems'):
|
|
|
|
flatten_dict(value, flattened)
|
|
|
|
else:
|
|
|
|
flattened[key] = value
|
|
|
|
return flattened
|
|
|
|
|
|
|
|
|
|
|
|
def partition_dict(dict_, keys):
|
|
|
|
"""Return two dicts, one containing only `keys` the other containing
|
|
|
|
everything but `keys`
|
|
|
|
"""
|
|
|
|
intersection = {}
|
|
|
|
difference = {}
|
|
|
|
for key, value in dict_.iteritems():
|
|
|
|
if key in keys:
|
|
|
|
intersection[key] = value
|
|
|
|
else:
|
|
|
|
difference[key] = value
|
|
|
|
return intersection, difference
|
|
|
|
|
|
|
|
|
|
|
|
def map_dict_keys(dict_, key_map):
|
2011-03-22 20:34:00 +00:00
|
|
|
"""Return a dictionary in which the dictionaries keys are mapped to
|
2011-03-22 20:26:45 +00:00
|
|
|
new keys.
|
|
|
|
"""
|
|
|
|
mapped = {}
|
|
|
|
for key, value in dict_.iteritems():
|
|
|
|
mapped_key = key_map[key] if key in key_map else key
|
|
|
|
mapped[mapped_key] = value
|
|
|
|
return mapped
|
2011-03-23 05:50:53 +00:00
|
|
|
|
|
|
|
|
|
|
|
def subset_dict(dict_, keys):
|
|
|
|
"""Return a dict that only contains a subset of keys"""
|
|
|
|
subset = partition_dict(dict_, keys)[0]
|
|
|
|
return subset
|
2011-03-24 21:13:55 +00:00
|
|
|
|
|
|
|
|
2011-03-22 21:42:17 -07:00
|
|
|
def check_isinstance(obj, cls):
|
2011-03-14 14:17:58 -07:00
|
|
|
"""Checks that obj is of type cls, and lets PyLint infer types"""
|
|
|
|
if isinstance(obj, cls):
|
|
|
|
return obj
|
|
|
|
raise Exception(_("Expected object of type: %s") % (str(cls)))
|
2011-03-22 22:45:15 -07:00
|
|
|
# TODO(justinsb): Can we make this better??
|
2011-03-14 14:17:58 -07:00
|
|
|
return cls() # Ugly PyLint hack
|