1 from __future__ import with_statement
4 from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN
5 import contextlib as clib
8 class InvirtConfigError(AttributeError):
12 'A simple namespace object.'
13 def __init__(self, d = {}, __prefix = None, **kwargs):
14 'd is the dictionary or the items-iterable to update my __dict__ with.'
18 self.__dict__.update(dct)
19 self.__keys = set(dct)
20 self.__prefix = __prefix
21 def __getattr__(self, key):
22 # XX ideally these would point a frame higher on the stack.
23 prefix = self.__prefix
24 if prefix is not None:
25 raise InvirtConfigError('missing configuration variable %s%s'
28 raise AttributeError("anonymous struct has no member '%s'"
34 def dicts2struct(x, prefix = None):
36 Given a tree of lists/dicts, perform a deep traversal to transform all the
39 if prefix is not None:
40 def newprefix(k): return prefix + str(k) + '.'
42 def newprefix(k): return prefix
44 return struct(((k, dicts2struct(v, newprefix(k)))
45 for k,v in x.iteritems()),
48 return [dicts2struct(v, newprefix(i)) for i, v in enumerate(x)]
50 return struct({}, prefix)
55 def lock_file(path, exclusive = True):
56 with clib.closing(file(path, 'w')) as f:
67 def captureOutput(popen_args, stdin_str=None, *args, **kwargs):
68 """Capture stdout from a command.
70 This method will proxy the arguments to subprocess.Popen. It
71 returns the output from the command if the call succeeded and
72 raises an exception if the process returns a non-0 value.
74 This is intended to be a variant on the subprocess.check_call
75 function that also allows you access to the output from the
78 if 'stdin' not in kwargs:
79 kwargs['stdin'] = subprocess.PIPE
80 if 'stdout' not in kwargs:
81 kwargs['stdout'] = subprocess.PIPE
82 if 'stderr' not in kwargs:
83 kwargs['stderr'] = subprocess.STDOUT
84 p = subprocess.Popen(popen_args, *args, **kwargs)
85 out, _ = p.communicate(stdin_str)
87 raise subprocess.CalledProcessError(p.returncode, popen_args, out)
94 class InvalidInput(Exception):
95 """Exception for user-provided input is invalid but maybe in good faith.
97 This would include setting memory to negative (which might be a
98 typo) but not setting an invalid boot CD (which requires bypassing
101 def __init__(self, err_field, err_value, expl=None):
102 Exception.__init__(self, expl)
103 self.err_field = err_field
104 self.err_value = err_value
106 class CodeError(Exception):
107 """Exception for internal errors or bad faith input."""
114 class common_tests(unittest.TestCase):
115 def test_dicts2structs(self):
118 'dict': { 'atom': 'atom', 'list': [1,2,3] },
119 'list': [ 'atom', {'key': 'value'} ]
121 structs = dicts2struct(dicts, '')
122 self.assertEqual(structs.atom, dicts['atom'])
123 self.assertEqual(structs.dict.atom, dicts['dict']['atom'])
124 self.assertEqual(structs.dict.list, dicts['dict']['list'])
125 self.assertEqual(structs.list[0], dicts['list'][0])
126 self.assertEqual(structs.list[1].key, dicts['list'][1]['key'])
127 self.assertEqual(set(structs), set(['atom', 'dict', 'list']))
129 if __name__ == '__main__':