[209] | 1 | """Exceptions for the web interface.""" |
---|
| 2 | |
---|
[261] | 3 | from sipb_xen_database import Machine, MachineAccess |
---|
[209] | 4 | |
---|
| 5 | class MyException(Exception): |
---|
| 6 | """Base class for my exceptions""" |
---|
| 7 | pass |
---|
| 8 | |
---|
| 9 | class InvalidInput(MyException): |
---|
| 10 | """Exception for user-provided input is invalid but maybe in good faith. |
---|
| 11 | |
---|
| 12 | This would include setting memory to negative (which might be a |
---|
| 13 | typo) but not setting an invalid boot CD (which requires bypassing |
---|
| 14 | the select box). |
---|
| 15 | """ |
---|
| 16 | def __init__(self, err_field, err_value, expl=None): |
---|
| 17 | MyException.__init__(self, expl) |
---|
| 18 | self.err_field = err_field |
---|
| 19 | self.err_value = err_value |
---|
| 20 | |
---|
| 21 | class CodeError(MyException): |
---|
| 22 | """Exception for internal errors or bad faith input.""" |
---|
| 23 | pass |
---|
| 24 | |
---|
| 25 | import controls |
---|
| 26 | |
---|
[261] | 27 | def cachedproperty(func): |
---|
| 28 | name = '__cache_' + func.__name__ + '_' + str(id(func)) |
---|
| 29 | def getter(self): |
---|
| 30 | try: |
---|
| 31 | return getattr(self, name) |
---|
| 32 | except AttributeError: |
---|
| 33 | value = func(self) |
---|
| 34 | setattr(self, name, value) |
---|
| 35 | return value |
---|
| 36 | return property(getter) |
---|
| 37 | |
---|
[209] | 38 | class Global(object): |
---|
| 39 | """Global state of the system, to avoid duplicate remctls to get state""" |
---|
| 40 | def __init__(self, user): |
---|
| 41 | self.user = user |
---|
[261] | 42 | |
---|
| 43 | machines = cachedproperty(lambda self: |
---|
| 44 | [ma.machine for ma in |
---|
| 45 | MachineAccess.select_by(user=self.user)]) |
---|
| 46 | uptimes = cachedproperty(lambda self: |
---|
| 47 | controls.getUptimes(self.machines)) |
---|
[209] | 48 | |
---|
| 49 | def clear(self): |
---|
| 50 | """Clear the state so future accesses reload it.""" |
---|
[261] | 51 | for attr in self.__dict__: |
---|
| 52 | if attr.startswith('__cache_'): |
---|
[209] | 53 | delattr(self, attr) |
---|
| 54 | |
---|
| 55 | g = Global(None) |
---|