-
Notifications
You must be signed in to change notification settings - Fork 517
/
Copy pathservice-runner.py
executable file
·83 lines (74 loc) · 2.47 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
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/python
## 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 sys
import redis
import subprocess
import time
import signal
def handle_sigterm(sig, frame):
print("Got Termination signal, exiting")
sys.exit(0)
# Setup the signal handler to gracefully exit
signal.signal(signal.SIGTERM, handle_sigterm)
signal.signal(signal.SIGINT, handle_sigterm)
def connect_redis():
while True:
try:
server = redis.Redis()
if server.ping():
print("Connected to redis-server")
sys.stdout.flush()
return server
except redis.exceptions.ConnectionError:
print("Unable to connect to redis-server, sleeping for 30s")
sys.stdout.flush()
time.sleep(30)
print("Starting service-runner")
sys.stdout.flush()
server = connect_redis()
while True:
try:
# Check for the existence of a redis 'service-runner' key
if server.exists('service-runner'):
# We've got one, now to turn it into a cmdline
flag = server.lpop('service-runner')
print("Got flag: %s\n" % flag)
sys.stdout.flush()
script, logfile = flag.split('>')
cmdstring = "{s} > {l} 2>&1".format(s=script, l=logfile)
print("STARTING: " + cmdstring)
sys.stdout.flush()
# Got a cmdline, now run it.
try:
subprocess.call(cmdstring, shell=True)
except SystemExit:
# If the sys.exit(0) from the interrupt handler gets caught here,
# just break from the while True: and let the script exit normally.
break
except:
# if an error occurs running the subprocess, add the error to
# the specified logfile
f = open(logfile, 'a')
f.write("Error running [%s]" % cmdstring)
f.write("Exception occurred: %s" % sys.exc_info()[0])
f.close()
raise # Now pass the exception upwards
print("COMPLETE: " + cmdstring)
sys.stdout.flush()
except redis.exceptions.ConnectionError:
print("Connection to redis-server lost, attempting to reconnect")
sys.stdout.flush()
server = connect_redis()
except SystemExit:
# If the sys.exit(0) from the interrupt handler gets caught here,
# just break from the while True: and let the script exit normally.
break
except:
print("Exception occurred", sys.exc_info()[0])
sys.exit(1)
time.sleep(0.2)