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