923d672d892678deb26c7556618c25f69f0829a1
[invirt/packages/invirt-base.git] / python / invirt / common.py
1 from __future__ import with_statement
2
3 from __future__ import absolute_import
4 import unittest
5 from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN
6 import contextlib as clib
7 import subprocess
8
9 class InvirtConfigError(AttributeError):
10     pass
11
12 class struct(dict):
13     'A simple namespace object.'
14     def __init__(self, d = {}, __prefix = None, __default=None, **kwargs):
15         super(struct, self).__init__(d)
16         self.__prefix = __prefix
17         self.__default = __default
18         self.update(kwargs)
19     def __getattr__(self, key):
20         try:
21             return self[key]
22         except KeyError:
23             if self.__default is None:
24                 # XX ideally these would point a frame higher on the stack.
25                 prefix = self.__prefix
26                 if prefix is not None:
27                     raise InvirtConfigError('missing configuration variable '
28                                             '%s%s' % (prefix, key))
29                 else:
30                     raise AttributeError("anonymous struct has no member '%s'"
31                                          % (key,))
32             else:
33                 return struct({}, '', self.__default)
34
35 def dicts2struct(x, prefix = None, default = None):
36     """
37     Given a tree of lists/dicts, perform a deep traversal to transform all the
38     dicts to structs.
39     """
40     if prefix is not None:
41         def newprefix(k): return prefix + str(k) + '.'
42     else:
43         def newprefix(k): return prefix
44     if type(x) == dict:
45         return struct(((k, dicts2struct(v, newprefix(k), default))
46                        for k,v in x.iteritems()),
47                       prefix,
48                       default)
49     elif type(x) == list:
50         return [dicts2struct(v, newprefix(i), default)
51                 for i, v in enumerate(x)]
52     elif x is None:
53         return struct({}, prefix, default)
54     else:
55         return x
56
57 @clib.contextmanager
58 def lock_file(path, exclusive = True):
59     with clib.closing(open(path, 'w')) as f:
60         if exclusive:
61             locktype = LOCK_EX
62         else:
63             locktype = LOCK_SH
64         flock(f, locktype)
65         try:
66             yield
67         finally:
68             flock(f, LOCK_UN)
69
70 def captureOutput(popen_args, stdin_str=None, *args, **kwargs):
71     """Capture stdout from a command.
72
73     This method will proxy the arguments to subprocess.Popen. It
74     returns the output from the command if the call succeeded and
75     raises an exception if the process returns a non-0 value.
76
77     This is intended to be a variant on the subprocess.check_call
78     function that also allows you access to the output from the
79     command.
80     """
81     if 'stdin' not in kwargs:
82         kwargs['stdin'] = subprocess.PIPE
83     if 'stdout' not in kwargs:
84         kwargs['stdout'] = subprocess.PIPE
85     if 'stderr' not in kwargs:
86         kwargs['stderr'] = subprocess.PIPE
87     p = subprocess.Popen(popen_args, *args, **kwargs)
88     out, err = p.communicate(stdin_str)
89     if p.returncode:
90         raise subprocess.CalledProcessError(p.returncode, '%s, stdout: %s, stderr: %s' %
91                                             (popen_args, out, err))
92     return out
93
94 #
95 # Exceptions.
96 #
97
98 class InvalidInput(Exception):
99     """Exception for user-provided input is invalid but maybe in good faith.
100
101     This would include setting memory to negative (which might be a
102     typo) but not setting an invalid boot CD (which requires bypassing
103     the select box).
104     """
105     def __init__(self, err_field, err_value, expl=None):
106         Exception.__init__(self, expl)
107         self.err_field = err_field
108         self.err_value = err_value
109
110 class CodeError(Exception):
111     """Exception for internal errors or bad faith input."""
112     pass
113
114 #
115 # Tests.
116 #
117
118 class common_tests(unittest.TestCase):
119     def test_dicts2structs(self):
120         dicts = {
121                 'atom': 0,
122                 'dict': { 'atom': 'atom', 'list': [1,2,3] },
123                 'list': [ 'atom', {'key': 'value'} ]
124                 }
125         structs = dicts2struct(dicts, '')
126         self.assertEqual(structs.atom,        dicts['atom'])
127         self.assertEqual(structs.dict.atom,   dicts['dict']['atom'])
128         self.assertEqual(structs.dict.list,   dicts['dict']['list'])
129         self.assertEqual(structs.list[0],     dicts['list'][0])
130         self.assertEqual(structs.list[1].key, dicts['list'][1]['key'])
131         self.assertEqual(set(structs), set(['atom', 'dict', 'list']))
132
133 if __name__ == '__main__':
134     unittest.main()