-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgdata.py
executable file
·139 lines (128 loc) · 3.37 KB
/
gdata.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#!/usr/bin/env python3
import sys
import os
import json
import time
import argparse
import psutil
def is_running(pid_file):
'''
determine if the daemon is running.
check for an exisiting pid file, check the pid.
if the pid is running return true, otherwise false.
'''
debug("Checking for running process")
if os.path.exists(pid_file):
debug("pid_file exists")
with open(pid_file) as f:
old_pid = int(f.read().strip())
try:
debug(f"Checking for pid {old_pid}")
p = psutil.Process(old_pid)
return True
except psutil.NoSuchProcess:
pass
return False
def startup(pid_file):
'''
Check if daemon is running if not gork and exit else just exit
'''
if not get_debug():
if is_running(pid_file):
log(f'daemon already running')
sys.exit(0)
pid = os.fork()
if pid > 0:
sys.exit(0)
with open(pid_file,"w") as f:
print(os.getpid(),file=f)
log(f'Daemon started, pid: {os.getpid()}')
else:
debug("Debug mode no daemon")
def log(*args):
'''
Write to logfile also debug if debug is enabled
'''
tfmt = '%m-%d-%Y %H:%M'
with open("/tmp/get-data.log","a") as f:
now = time.time()
lt = time.localtime(now)
tstr = time.strftime(tfmt,lt)
print(f'{tstr}:',*args,file=f)
debug(*args)
def get_config():
'''
read common config file
'''
try:
with open('sensors.json') as f:
return json.load(f)
except:
return None
def main(base_dir,pid_file):
'''
loop through defined sensors and write data to {base_dir}/{host}-{sensor}.json
sleep for poll interval miliseconds
'''
config = None
while not config:
config = get_config()
if not config:
time.sleep(1)
poll_interval = config['poll_interval']/1000
while True:
time.sleep(poll_interval)
config = get_config()
if not config:
continue
poll_interval = config['poll_interval']/1000
for name,sensor in config['sensors'].items():
if '::' in name:
continue
#if not sensor['active']:
# continue
host = sensor['host']
sen = sensor['sensor']
server = config['server']
debug(server,host,sensor)
data_file = f'{base_dir}/{host}-{sen}.json'
client = rest.RestClient(
server=server,
host=host,
sensor=sen)
try:
sensor_data = client.read()
if not 'error' in sensor_data:
with open(data_file,'w') as f:
debug("Writing",data_file)
json.dump(sensor_data,f,indent=2)
except Exception as e:
with open('/tmp/get-data.log','a') as f:
log(f'Exception getting data for {host}-{sen}: {e}')
if __name__ == "__main__":
parser = argparse.ArgumentParser(
prog=f"get-data",
description="daemon to collect data via sensorfs",
epilog="A SensorFS RestAPI Example. See https://github.com/nicciniamh/sensorfs"
)
parser.add_argument('-d','--debug',action='store_true',default=False,help='turn on copious debugging messages')
parser.add_argument('-rp','--run-path',type=str,default=None,help='run program in path',metavar="path")
args = parser.parse_args()
prog_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
if args.run_path:
prog_dir = args.run_path
os.chdir(prog_dir)
sys.path.append(os.path.expanduser('~/lib'))
sys.path.append(prog_dir)
from dflib import rest
from dflib.debug import *
pid_file = '/tmp/get-data.pid'
data_path = '/Volumes/RamDisk/sensordata'
set_debug(args.debug)
try:
startup(pid_file)
main(data_path,pid_file)
except KeyboardInterrupt:
pass
except Exception as e:
log(f'Exception: {e}')