~sandy-walsh/nova/zones2

« back to all changes in this revision

Viewing changes to nova/utils.py

  • Committer: Sandy Walsh
  • Date: 2011-02-25 09:12:28 UTC
  • mfrom: (635.1.117 nova)
  • Revision ID: sandy.walsh@rackspace.com-20110225091228-o7ircyj18yp8po8z
merged with trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
2
2
 
3
3
# Copyright 2010 United States Government as represented by the
4
4
# Administrator of the National Aeronautics and Space Administration.
 
5
# Copyright 2011 Justin Santa Barbara
5
6
# All Rights Reserved.
6
7
#
7
8
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
20
21
System-level utilities and helper functions.
21
22
"""
22
23
 
 
24
import base64
23
25
import datetime
24
26
import inspect
25
27
import json
26
28
import os
27
29
import random
28
30
import socket
 
31
import string
29
32
import struct
30
33
import sys
31
34
import time
 
35
import types
32
36
from xml.sax import saxutils
33
37
import re
34
38
import netaddr
53
57
        __import__(mod_str)
54
58
        return getattr(sys.modules[mod_str], class_str)
55
59
    except (ImportError, ValueError, AttributeError), exc:
56
 
        logging.debug(_('Inner Exception: %s'), exc)
 
60
        LOG.debug(_('Inner Exception: %s'), exc)
57
61
        raise exception.NotFound(_('Class %s cannot be found') % class_str)
58
62
 
59
63
 
235
239
    return ':'.join(map(lambda x: "%02x" % x, mac))
236
240
 
237
241
 
 
242
def generate_password(length=20):
 
243
    """Generate a random sequence of letters and digits
 
244
    to be used as a password. Note that this is not intended
 
245
    to represent the ultimate in security.
 
246
    """
 
247
    chrs = string.letters + string.digits
 
248
    return "".join([random.choice(chrs) for i in xrange(length)])
 
249
 
 
250
 
238
251
def last_octet(address):
239
252
    return int(address.split(".")[-1])
240
253
 
476
489
 
477
490
def loads(s):
478
491
    return json.loads(s)
 
492
 
 
493
 
 
494
def ensure_b64_encoding(val):
 
495
    """Safety method to ensure that values expected to be base64-encoded
 
496
    actually are. If they are, the value is returned unchanged. Otherwise,
 
497
    the encoded value is returned.
 
498
    """
 
499
    try:
 
500
        dummy = base64.decode(val)
 
501
        return val
 
502
    except TypeError:
 
503
        return base64.b64encode(val)
 
504
 
 
505
 
 
506
def get_from_path(items, path):
 
507
    """ Returns a list of items matching the specified path.  Takes an
 
508
    XPath-like expression e.g. prop1/prop2/prop3, and for each item in items,
 
509
    looks up items[prop1][prop2][prop3].  Like XPath, if any of the
 
510
    intermediate results are lists it will treat each list item individually.
 
511
    A 'None' in items or any child expressions will be ignored, this function
 
512
    will not throw because of None (anywhere) in items.  The returned list
 
513
    will contain no None values."""
 
514
 
 
515
    if path is None:
 
516
        raise exception.Error("Invalid mini_xpath")
 
517
 
 
518
    (first_token, sep, remainder) = path.partition("/")
 
519
 
 
520
    if first_token == "":
 
521
        raise exception.Error("Invalid mini_xpath")
 
522
 
 
523
    results = []
 
524
 
 
525
    if items is None:
 
526
        return results
 
527
 
 
528
    if not isinstance(items, types.ListType):
 
529
        # Wrap single objects in a list
 
530
        items = [items]
 
531
 
 
532
    for item in items:
 
533
        if item is None:
 
534
            continue
 
535
        get_method = getattr(item, "get", None)
 
536
        if get_method is None:
 
537
            continue
 
538
        child = get_method(first_token)
 
539
        if child is None:
 
540
            continue
 
541
        if isinstance(child, types.ListType):
 
542
            # Flatten intermediate lists
 
543
            for x in child:
 
544
                results.append(x)
 
545
        else:
 
546
            results.append(child)
 
547
 
 
548
    if not sep:
 
549
        # No more tokens
 
550
        return results
 
551
    else:
 
552
        return get_from_path(results, remainder)