blob: 07a1dce739c01024f07d2793d8965af753db5ceb [file] [log] [blame]
koder aka kdanilovdda86d32015-03-16 11:20:04 +02001import os
2import sys
3import time
4import json
5import signal
6import os.path
7import argparse
8
9import io_sensors
10import net_sensors
11
12from utils import SensorInfo
13from daemonize import Daemonize
14from discover import all_sensors
15from protocol import create_protocol
16
17
18def get_values(required_sensors):
19 result = {}
20 for sensor_name, params in required_sensors:
21 if sensor_name in all_sensors:
22 result.update(all_sensors[sensor_name](**params))
23 else:
24 msg = "Sensor {0!r} isn't available".format(sensor_name)
25 raise ValueError(msg)
26 return time.time(), result
27
28
29def parse_args(args):
30 parser = argparse.ArgumentParser()
31 parser.add_argument('-d', '--daemon',
32 choices=('start', 'stop', 'status'),
33 default=None)
34
35 parser.add_argument('-u', '--url', default='stdout://')
36 parser.add_argument('-t', '--timeout', type=float, default=1)
37 parser.add_argument('sensors_config', type=argparse.FileType('r'),
38 default=None, nargs='?')
39 return parser.parse_args(args[1:])
40
41
42def daemon_main(required_sensors, opts):
43 sender = create_protocol(opts.url)
44 prev = {}
45
46 while True:
47 gtime, data = get_values(required_sensors.items())
48 curr = {'time': SensorInfo(gtime, True)}
49 for name, val in data.items():
50 if val.is_accumulated:
51 if name in prev:
52 curr[name] = SensorInfo(val.value - prev[name], True)
53 prev[name] = val.value
54 else:
55 curr[name] = SensorInfo(val.value, False)
56 sender.send(curr)
57 time.sleep(opts.timeout)
58
59
60def main(argv):
61 opts = parse_args(argv)
62
63 if opts.daemon is not None:
64 pid_file = "/tmp/sensors.pid"
65 if opts.daemon == 'start':
66 required_sensors = json.loads(opts.sensors_config.read())
67
68 def root_func():
69 daemon_main(required_sensors, opts)
70
71 daemon = Daemonize(app="perfcollect_app",
72 pid=pid_file,
73 action=root_func)
74 daemon.start()
75 elif opts.daemon == 'stop':
76 if os.path.isfile(pid_file):
77 pid = int(open(pid_file).read())
78 if os.path.exists("/proc/" + str(pid)):
79 os.kill(pid, signal.SIGTERM)
80
81 time.sleep(0.1)
82
83 if os.path.exists("/proc/" + str(pid)):
84 os.kill(pid, signal.SIGKILL)
85
86 if os.path.isfile(pid_file):
87 os.unlink(pid_file)
88 elif opts.daemon == 'status':
89 if os.path.isfile(pid_file):
90 pid = int(open(pid_file).read())
91 if os.path.exists("/proc/" + str(pid)):
92 print "running"
93 return
94 print "stopped"
95 else:
96 raise ValueError("Unknown daemon operation {}".format(opts.daemon))
97 else:
98 required_sensors = json.loads(opts.sensors_config.read())
99 daemon_main(required_sensors, opts)
100 return 0
101
102if __name__ == "__main__":
103 exit(main(sys.argv))