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