effb237c82a0973b0bb5118a8922e9a15bff2726
[invirt/packages/invirt-base.git] / python / invirt / common.py
1 import unittest
2 from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN
3 import contextlib as clib
4 import subprocess
5
6 class InvirtConfigError(AttributeError):
7     pass
8
9
10 @clib.contextmanager
11 def lock_file(path, exclusive = True):
12     with clib.closing(open(path, 'w')) as f:
13         if exclusive:
14             locktype = LOCK_EX
15         else:
16             locktype = LOCK_SH
17         flock(f, locktype)
18         try:
19             yield
20         finally:
21             flock(f, LOCK_UN)
22
23
24 #
25 # Exceptions.
26 #
27
28 class InvalidInput(Exception):
29     """Exception for user-provided input is invalid but maybe in good faith.
30
31     This would include setting memory to negative (which might be a
32     typo) but not setting an invalid boot CD (which requires bypassing
33     the select box).
34     """
35     def __init__(self, err_field, err_value, expl=None):
36         Exception.__init__(self, expl)
37         self.err_field = err_field
38         self.err_value = err_value
39
40 class CodeError(Exception):
41     """Exception for internal errors or bad faith input."""
42     pass
43
44 #
45 # Tests.
46 #
47
48