-
Notifications
You must be signed in to change notification settings - Fork 517
/
Copy pathservice-runner.py
executable file
·72 lines (60 loc) · 2.29 KB
/
service-runner.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
#!/usr/bin/env python3
## Used to run arbitrary commands from the EmonCMS web interface
# EmonCMS submits commands to redis where this service picks them up
# Used in conjunction with:
# - Admin module to run service-runner-update.sh
# - Backup module
# - Others??
import subprocess
import time
import shlex
import redis
KEYS = ["service-runner", "emoncms:service-runner"]
def connect_redis():
while True:
try:
server = redis.Redis()
if server.ping():
print("Connected to redis server", flush=True)
return server
except redis.exceptions.ConnectionError:
print("Unable to connect to redis server, sleeping for 30s", flush=True)
time.sleep(30)
def main():
print("Starting service-runner", flush=True)
server = connect_redis()
while True:
try:
# Get the next item from the 'service-runner' list, blocking until one exists
packed = server.blpop(KEYS)
if not packed:
continue
flag = packed[1].decode()
except redis.exceptions.ConnectionError:
print("Connection to redis server lost, attempting to reconnect", flush=True)
server = connect_redis()
continue
print("Got flag:", flag, flush=True)
if ">" in flag:
script, logfile = flag.split(">")
print("STARTING:", script, '&>', logfile, flush=True)
# Got a cmdline, now run it.
with open(logfile, "w") as f:
try:
subprocess.call(shlex.split(script), stdout=f, stderr=f)
except Exception as exc:
# If an error occurs running the subprocess, add the error to
# the specified logfile
f.write("Error running [%s]" % script)
f.write("Exception occurred: %s" % exc)
continue
else:
script = flag
print("STARTING:", script, flush=True)
try:
subprocess.call(shlex.split(script), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
except Exception as exc:
continue
print("COMPLETE:", script, flush=True)
if __name__ == "__main__":
main()