comparison py/params.py @ 456:3db3665af2e2

reload config on SIGHUP
author Matt Johnston <matt@ucc.asn.au>
date Thu, 03 Jan 2013 20:12:07 +0800
parents dce9f7841696
children 256505f98c4d
comparison
equal deleted inserted replaced
455:e12d6d677320 456:3db3665af2e2
1 # -*- coding: utf-8 -*- 1 # -*- coding: utf-8 -*-
2 import collections 2 import collections
3 import json 3 import json
4 import signal
5
6 import gevent
7
4 import config 8 import config
5 from utils import W,L,E,EX 9 from utils import W,L,E,EX
6 10
7 _FIELD_DEFAULTS = { 11 _FIELD_DEFAULTS = {
8 'fridge_setpoint': 16, 12 'fridge_setpoint': 16,
15 class Error(Exception): 19 class Error(Exception):
16 pass 20 pass
17 21
18 def __init__(self): 22 def __init__(self):
19 self.update(_FIELD_DEFAULTS) 23 self.update(_FIELD_DEFAULTS)
24 gevent.signal(signal.SIGHUP, self.reload_signal)
20 25
21 def __getattr__(self, k): 26 def __getattr__(self, k):
22 return self[k] 27 return self[k]
23 28
24 def __setattr__(self, k, v): 29 def __setattr__(self, k, v):
31 try: 36 try:
32 f = file(config.PARAMS_FILE, 'r') 37 f = file(config.PARAMS_FILE, 'r')
33 except IOError, e: 38 except IOError, e:
34 W("Missing parameter file, using defaults. %s", e) 39 W("Missing parameter file, using defaults. %s", e)
35 return 40 return
36 u = json.load(f) 41 try:
42 u = json.load(f)
43 except Exception, e:
44 raise self.Error(e)
45
37 for k in u: 46 for k in u:
38 if k not in self: 47 if k not in self:
39 raise self.Error("Unknown parameter %s=%s in file '%s'" % (str(k), str(u[k]), getattr(f, 'name', '???'))) 48 raise self.Error("Unknown parameter %s=%s in file '%s'" % (str(k), str(u[k]), getattr(f, 'name', '???')))
40 self.update(u) 49 self.update(u)
41 50
43 if not f: 52 if not f:
44 f = file(config.PARAMS_FILE, 'w') 53 f = file(config.PARAMS_FILE, 'w')
45 json.dump(self, f, sort_keys=True, indent=4) 54 json.dump(self, f, sort_keys=True, indent=4)
46 f.write('\n') 55 f.write('\n')
47 f.flush() 56 f.flush()
57
58 def reload_signal(self):
59 try:
60 self.load()
61 L("Reloaded params")
62 except self.Error, e:
63 W("Problem reloading: %s" % str(e))