2 from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN
3 import contextlib as clib
6 class InvirtConfigError(AttributeError):
10 'A simple namespace object.'
11 def __init__(self, d = {}, __prefix = None, __default=None, **kwargs):
12 super(struct, self).__init__(d)
13 self.__prefix = __prefix
14 self.__default = __default
16 def __getattr__(self, key):
20 if self.__default is None:
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 '
25 '%s%s' % (prefix, key))
27 raise AttributeError("anonymous struct has no member '%s'"
30 return struct({}, '', self.__default)
32 def dicts2struct(x, prefix = None, default = None):
34 Given a tree of lists/dicts, perform a deep traversal to transform all the
37 if prefix is not None:
38 def newprefix(k): return prefix + str(k) + '.'
40 def newprefix(k): return prefix
42 return struct(((k, dicts2struct(v, newprefix(k), default))
43 for k,v in x.iteritems()),
47 return [dicts2struct(v, newprefix(i), default)
48 for i, v in enumerate(x)]
50 return struct({}, prefix, default)
55 def lock_file(path, exclusive = True):
56 with clib.closing(open(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.PIPE
84 p = subprocess.Popen(popen_args, *args, **kwargs)
85 out, err = p.communicate(stdin_str)
87 raise subprocess.CalledProcessError(p.returncode, '%s, stdout: %s, stderr: %s' %
88 (popen_args, out, err))
95 class InvalidInput(Exception):
96 """Exception for user-provided input is invalid but maybe in good faith.
98 This would include setting memory to negative (which might be a
99 typo) but not setting an invalid boot CD (which requires bypassing
102 def __init__(self, err_field, err_value, expl=None):
103 Exception.__init__(self, expl)
104 self.err_field = err_field
105 self.err_value = err_value
107 class CodeError(Exception):
108 """Exception for internal errors or bad faith input."""
115 class common_tests(unittest.TestCase):
116 def test_dicts2structs(self):
119 'dict': { 'atom': 'atom', 'list': [1,2,3] },
120 'list': [ 'atom', {'key': 'value'} ]
122 structs = dicts2struct(dicts, '')
123 self.assertEqual(structs.atom, dicts['atom'])
124 self.assertEqual(structs.dict.atom, dicts['dict']['atom'])
125 self.assertEqual(structs.dict.list, dicts['dict']['list'])
126 self.assertEqual(structs.list[0], dicts['list'][0])
127 self.assertEqual(structs.list[1].key, dicts['list'][1]['key'])
128 self.assertEqual(set(structs), set(['atom', 'dict', 'list']))
130 if __name__ == '__main__':