stack-monitor: creation of the stack.
[slapos.git] / stack / monitor / monitor.py.in
1 #!/usr/bin/python
2
3 import json
4 import os
5 import subprocess
6 import sys
7 import time
8 from optparse import OptionParser
9
10 promise_dir = "{{ directory['promise'] }}"
11 service_dir = "{{ directory['service'] }}"
12 monitor_dir = "{{ directory['monitor'] }}"
13 instance_path = "{{ directory['home'] }}"
14
15 def getListOfScripts():
16 scripts = []
17 for dir in (promise_dir, monitor_dir):
18 if os.path.exists(dir) and os.path.isdir(dir):
19 for file in os.listdir(dir):
20 scripts.append(os.path.join(dir, file))
21 if scripts:
22 return scripts
23 else:
24 exit("There is a problem in your directories" \
25 "of monitoring. Please check them")
26
27 def run():
28 scripts = getListOfScripts()
29 script_timeout = 3
30 failed_scripts = []
31 failed_bool = False
32 for script_path in scripts:
33 command = [os.path.join(promise_dir, script_path)]
34 script = os.path.basename(command[0])
35
36 process_handler = subprocess.Popen(command,
37 cwd=instance_path,
38 env=None if sys.platform == 'cygwin' else {},
39 stdout=subprocess.PIPE,
40 stderr=subprocess.PIPE,
41 stdin=subprocess.PIPE)
42 process_handler.stdin.flush()
43 process_handler.stdin.close()
44 process_handler.stdin = None
45
46 time.sleep(script_timeout)
47
48 if process_handler.poll() is None:
49 process_handler.terminate()
50 failed_bool = True
51 failed_scripts.append({script_path : "Time Out"})
52 elif process_handler.poll() != 0:
53 stderr = process_handler.communicate()[1]
54 if stderr is not None:
55 failed_bool = True
56 failed_scripts.append({script_path : stderr.strip()})
57 return failed_scripts
58
59
60 if __name__ == "__main__":
61 parser = OptionParser()
62 parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
63 help="return a json containing info for each monitored script")
64 (options, args) = parser.parse_args()
65 fails = run()
66 if options.verbose:
67 print fails
68 elif len(fails) == 0:
69 print 0
70 exit(0)
71 else:
72 print 1
73 exit(1)