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 super(struct, self).__init__(d)
15 self.__prefix = __prefix
17 def __getattr__(self, key):
21 # XX ideally these would point a frame higher on the stack.
22 prefix = self.__prefix
23 if prefix is not None:
24 raise InvirtConfigError('missing configuration variable %s%s'
27 raise AttributeError("anonymous struct has no member '%s'"
30 def dicts2struct(x, prefix = None):
32 Given a tree of lists/dicts, perform a deep traversal to transform all the
35 if prefix is not None:
36 def newprefix(k): return prefix + str(k) + '.'
38 def newprefix(k): return prefix
40 return struct(((k, dicts2struct(v, newprefix(k)))
41 for k,v in x.iteritems()),
44 return [dicts2struct(v, newprefix(i)) for i, v in enumerate(x)]
46 return struct({}, prefix)
51 def lock_file(path, exclusive = True):
52 with clib.closing(file(path, 'w')) as f:
63 def captureOutput(popen_args, stdin_str=None, *args, **kwargs):
64 """Capture stdout from a command.
66 This method will proxy the arguments to subprocess.Popen. It
67 returns the output from the command if the call succeeded and
68 raises an exception if the process returns a non-0 value.
70 This is intended to be a variant on the subprocess.check_call
71 function that also allows you access to the output from the
74 if 'stdin' not in kwargs:
75 kwargs['stdin'] = subprocess.PIPE
76 if 'stdout' not in kwargs:
77 kwargs['stdout'] = subprocess.PIPE
78 if 'stderr' not in kwargs:
79 kwargs['stderr'] = subprocess.STDOUT
80 p = subprocess.Popen(popen_args, *args, **kwargs)
81 out, _ = p.communicate(stdin_str)
83 raise subprocess.CalledProcessError(p.returncode, popen_args, out)
90 class InvalidInput(Exception):
91 """Exception for user-provided input is invalid but maybe in good faith.
93 This would include setting memory to negative (which might be a
94 typo) but not setting an invalid boot CD (which requires bypassing
97 def __init__(self, err_field, err_value, expl=None):
98 Exception.__init__(self, expl)
99 self.err_field = err_field
100 self.err_value = err_value
102 class CodeError(Exception):
103 """Exception for internal errors or bad faith input."""
110 class common_tests(unittest.TestCase):
111 def test_dicts2structs(self):
114 'dict': { 'atom': 'atom', 'list': [1,2,3] },
115 'list': [ 'atom', {'key': 'value'} ]
117 structs = dicts2struct(dicts, '')
118 self.assertEqual(structs.atom, dicts['atom'])
119 self.assertEqual(structs.dict.atom, dicts['dict']['atom'])
120 self.assertEqual(structs.dict.list, dicts['dict']['list'])
121 self.assertEqual(structs.list[0], dicts['list'][0])
122 self.assertEqual(structs.list[1].key, dicts['list'][1]['key'])
123 self.assertEqual(set(structs), set(['atom', 'dict', 'list']))
125 if __name__ == '__main__':