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, __default=None, **kwargs):
14 super(struct, self).__init__(d)
15 self.__prefix = __prefix
16 self.__default = __default
18 def __getattr__(self, key):
22 if self.__default is None:
23 # XX ideally these would point a frame higher on the stack.
24 prefix = self.__prefix
25 if prefix is not None:
26 raise InvirtConfigError('missing configuration variable '
27 '%s%s' % (prefix, key))
29 raise AttributeError("anonymous struct has no member '%s'"
32 return struct({}, '', self.__default)
34 def dicts2struct(x, prefix = None, default = 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), default))
45 for k,v in x.iteritems()),
49 return [dicts2struct(v, newprefix(i), default)
50 for i, v in enumerate(x)]
52 return struct({}, prefix, default)
57 def lock_file(path, exclusive = True):
58 with clib.closing(file(path, 'w')) as f:
69 def captureOutput(popen_args, stdin_str=None, *args, **kwargs):
70 """Capture stdout from a command.
72 This method will proxy the arguments to subprocess.Popen. It
73 returns the output from the command if the call succeeded and
74 raises an exception if the process returns a non-0 value.
76 This is intended to be a variant on the subprocess.check_call
77 function that also allows you access to the output from the
80 if 'stdin' not in kwargs:
81 kwargs['stdin'] = subprocess.PIPE
82 if 'stdout' not in kwargs:
83 kwargs['stdout'] = subprocess.PIPE
84 if 'stderr' not in kwargs:
85 kwargs['stderr'] = subprocess.STDOUT
86 p = subprocess.Popen(popen_args, *args, **kwargs)
87 out, _ = p.communicate(stdin_str)
89 raise subprocess.CalledProcessError(p.returncode, popen_args, out)
96 class InvalidInput(Exception):
97 """Exception for user-provided input is invalid but maybe in good faith.
99 This would include setting memory to negative (which might be a
100 typo) but not setting an invalid boot CD (which requires bypassing
103 def __init__(self, err_field, err_value, expl=None):
104 Exception.__init__(self, expl)
105 self.err_field = err_field
106 self.err_value = err_value
108 class CodeError(Exception):
109 """Exception for internal errors or bad faith input."""
116 class common_tests(unittest.TestCase):
117 def test_dicts2structs(self):
120 'dict': { 'atom': 'atom', 'list': [1,2,3] },
121 'list': [ 'atom', {'key': 'value'} ]
123 structs = dicts2struct(dicts, '')
124 self.assertEqual(structs.atom, dicts['atom'])
125 self.assertEqual(structs.dict.atom, dicts['dict']['atom'])
126 self.assertEqual(structs.dict.list, dicts['dict']['list'])
127 self.assertEqual(structs.list[0], dicts['list'][0])
128 self.assertEqual(structs.list[1].key, dicts['list'][1]['key'])
129 self.assertEqual(set(structs), set(['atom', 'dict', 'list']))
131 if __name__ == '__main__':