Provide wrapper for daemons.
[slapos.git] / slapos / recipe / zabbixagent / svcdaemon.py
1 import os
2 import subprocess
3 import time
4 import signal
5 import sys
6
7 pid_file = None
8 def sig_handler(s, frame):
9 print "Killing on signal %s:" % s,
10 global pid_file
11 if pid_file is not None:
12 if os.path.exists(pid_file):
13 pid = int(open(pid_file).read())
14 print 'pid %s with SIGTERM...' % pid,
15 os.kill(pid, signal.SIGTERM)
16 if os.kill(pid, 0):
17 time.sleep(5)
18 if os.kill(pid, 0):
19 print 'with SIGKILL...',
20 os.kill(pid, signal.SIGKILL)
21 else:
22 print 'no pid file %r, nothing to do...' % pid_file,
23 print 'done.'
24 sys.exit(0)
25
26 signal.signal(signal.SIGINT, sig_handler)
27 signal.signal(signal.SIGQUIT, sig_handler)
28 signal.signal(signal.SIGTERM, sig_handler)
29
30
31 def svcdaemon(args):
32 """Utility script to run daemons in supervisord"""
33 real_binary = args[0]['real_binary']
34 global pid_file
35 pid_file = args[0]['pid_file']
36 subprocess.check_call(real_binary)
37 print 'Started %r' % real_binary
38 while True:
39 time.sleep(2)