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.'
15 self.__dict__.update(d)
16 self.__dict__.update(kwargs)
17 self.__prefix = __prefix
18 def __getattr__(self, key):
19 # XX ideally these would point a frame higher on the stack.
20 prefix = self.__prefix
21 if prefix is not None:
22 raise InvirtConfigError('missing configuration variable %s%s'
25 raise AttributeError("anonymous struct has no member '%s'"
28 def dicts2struct(x, prefix = None):
30 Given a tree of lists/dicts, perform a deep traversal to transform all the
33 if prefix is not None:
34 def newprefix(k): return prefix + str(k) + '.'
36 def newprefix(k): return prefix
38 return struct(((k, dicts2struct(v, newprefix(k)))
39 for k,v in x.iteritems()),
42 return [dicts2struct(v, newprefix(i)) for i, v in enumerate(x)]
44 return struct({}, prefix)
49 def lock_file(path, exclusive = True):
50 with clib.closing(file(path, 'w')) as f:
61 def captureOutput(popen_args, stdin_str=None, *args, **kwargs):
62 """Capture stdout from a command.
64 This method will proxy the arguments to subprocess.Popen. It
65 returns the output from the command if the call succeeded and
66 raises an exception if the process returns a non-0 value.
68 This is intended to be a variant on the subprocess.check_call
69 function that also allows you access to the output from the
72 if 'stdin' not in kwargs:
73 kwargs['stdin'] = subprocess.PIPE
74 if 'stdout' not in kwargs:
75 kwargs['stdout'] = subprocess.PIPE
76 if 'stderr' not in kwargs:
77 kwargs['stderr'] = subprocess.STDOUT
78 p = subprocess.Popen(popen_args, *args, **kwargs)
79 out, _ = p.communicate(stdin_str)
81 raise subprocess.CalledProcessError(p.returncode, popen_args, out)
88 class InvalidInput(Exception):
89 """Exception for user-provided input is invalid but maybe in good faith.
91 This would include setting memory to negative (which might be a
92 typo) but not setting an invalid boot CD (which requires bypassing
95 def __init__(self, err_field, err_value, expl=None):
96 Exception.__init__(self, expl)
97 self.err_field = err_field
98 self.err_value = err_value
100 class CodeError(Exception):
101 """Exception for internal errors or bad faith input."""
108 class common_tests(unittest.TestCase):
109 def test_dicts2structs(self):
112 'dict': { 'atom': 'atom', 'list': [1,2,3] },
113 'list': [ 'atom', {'key': 'value'} ]
115 structs = dicts2struct(dicts, '')
116 self.assertEqual(structs.atom, dicts['atom'])
117 self.assertEqual(structs.dict.atom, dicts['dict']['atom'])
118 self.assertEqual(structs.dict.list, dicts['dict']['list'])
119 self.assertEqual(structs.list[0], dicts['list'][0])
120 self.assertEqual(structs.list[1].key, dicts['list'][1]['key'])
122 if __name__ == '__main__':