monitor.py.in 4.11 KB
Newer Older
1
#!{{ python_executable }}
2

3
import datetime
4 5 6 7 8
import json
import os
import subprocess
import sys
import time
9
from optparse import OptionParser, make_option
10 11

instance_path = "{{ directory['home'] }}"
12 13 14
monitor_dir = "{{ directory['monitor'] }}"
pid_dir = "{{ directory['run'] }}"
promise_dir = "{{ directory['promise'] }}"
15

16
monitoring_file_json = "{{ monitoring_file_json }}"
17
monitoring_folder_bool = "{{ monitoring_folder_bool }}"
18 19 20 21 22 23 24 25 26 27 28 29 30

option_list = [
  make_option("-a", "--all", action="store_true", dest="all",
              help="test everything : promises, services, customs"),
  make_option("-n", "--no-write", action="store_true", dest="only_stdout",
              help="just show the json output on stdout"),
  make_option("-m", "--monitors", action="store_true", dest="monitor",
              help="add the custom monitoring file to the files to monitor"),
  make_option("-p", "--promises", action="store_true", dest="promise",
              help="add the promises\'file to the files to monitor"),
  make_option("-s", "--services", action="store_true", dest="service",
              help="add the file containing services\'pid to the files to monitor")
]
31 32


33
def getListOfScripts(directory):
34
  scripts = []
35 36 37
  if os.path.exists(directory) and os.path.isdir(directory):
    for file in os.listdir(directory):
      scripts.append(os.path.join(directory, file))
38 39 40
  else:
    exit("There is a problem in your directories" \
          "of monitoring. Please check them")
41 42 43 44 45 46 47 48
  return scripts

def runServices(directory):
  services = getListOfScripts(directory)
  result = {}
  for service in services:
    service_path = os.path.join(pid_dir, service)
    service_name = os.path.basename(service_path)
49 50 51 52 53
    try:
      pid = int(open(service_path).read())
    ### because apache (or others) can write sockets
    except IOError:
      continue
54 55 56 57 58 59
    try:
      os.kill(pid, 0)
      result[service_name] = ''
    except OSError:
      result[service_name] = "This service is not running anymore"
  return result
60

61

62 63
def runScripts(directory):
  scripts = getListOfScripts(directory)
64
  script_timeout = 3
65 66 67
  result = {}
  for script in scripts:
    command = [os.path.join(promise_dir, script)]
68
    script = os.path.basename(command[0])
69
    result[script] = ''
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    
    process_handler = subprocess.Popen(command,
                                       cwd=instance_path,
                                       env=None if sys.platform == 'cygwin' else {},
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE,
                                       stdin=subprocess.PIPE)
    process_handler.stdin.flush()
    process_handler.stdin.close()
    process_handler.stdin = None

    time.sleep(script_timeout)

    if process_handler.poll() is None:
      process_handler.terminate()
85
      result[script] = "Time Out"
86 87 88
    elif process_handler.poll() != 0:
      stderr = process_handler.communicate()[1]
      if stderr is not None:
89 90
        result[script] = stderr.strip()
  return result
91 92


93
def writeFiles(monitors):
94 95 96 97 98 99
  fail = False
  for i in monitors.values():
    if i != "" :
      fail = True
  if fail:
    message = "FAILURE : something went wrong\n"
100
  else:
101
    message = "SUCCESS : everything is ok\n"
102 103
  date = datetime.datetime.now().ctime()
  monitors['datetime'] = date
104 105
  file_bool = os.path.join(monitoring_folder_bool, str(time.time()))
  open(file_bool, "w+").write(date + "," +  message)
106
  open(monitoring_file_json, "w+").write(json.dumps(monitors))
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
if __name__ == "__main__":
  parser = OptionParser(option_list=option_list)
  monitors = {}
  (options, args) = parser.parse_args()
  
  if not (options.monitor or options.promise
         or options.service or options.all):
    exit("Please provide at list one arg in : -a, -m, -p, -s")
  
  if options.monitor or options.all:
    monitors.update(runScripts(monitor_dir))
  if options.promise or options.all:
    monitors.update(runScripts(promise_dir))
  if options.service or options.all:
    monitors.update(runServices(pid_dir))
    
  if options.only_stdout:
    print json.dumps(monitors)
  else:
    writeFiles(monitors)
  if len(monitors) == 0:
    exit(0)
  else:
    exit(1)
133