#!/usr/bin/python3

from __future__ import print_function

import re, sys, os, time, getopt, socket
if sys.version_info[0]>2:
  from urllib.request import urlopen, URLError
else:
  from urllib2 import urlopen, URLError

monitored_values = '''\
listen_queue
idle_processes
active_processes
total_processes
'''.split('\n')

monitored_counters = '''\
accepted_conn
slow_requests
'''.split('\n')

try:
  opts, files = getopt.gnu_getopt(sys.argv[1:], 'H:w:c:t:U:', [])
  argv = dict(opts)
except getopt.GetoptError as err:
  print("Error:", str(err))
  sys.exit(1)

if '-U' in argv:
  URL = argv['-U']
elif '-H' in argv:
  URL = "http://%s/fpm-www-status" % argv['-H']
else:
  print("Wrong arguments!")
  sys.exit(10)
warn_time = float(argv.get("-w", 3.0))
crit_time = float(argv.get("-c", 5.0))
try:
  socket.setdefaulttimeout(int(argv.get('-t', 12)))
  t0 = time.time()
  f = urlopen(URL)
  t1 = time.time()-t0
except Exception as err:
  print("PHP-FPM CRITICAL - %s, %s" % (err, URL))
  sys.exit(2)

pool = ''
stats = []
while True:
  line = f.readline().decode("utf8")
  if not line:
    break # EOF
  if line.startswith("pool:"):
    pool = line.split(":", 1)[1].strip()
    continue
  if ":" in line:
    key, value = line.split(":", 1)
    key = key.replace(" ", "_")
    value = value.strip()
    if key in monitored_values:
      stats.append("%s=%s;;;0" % (key, value))
    elif key in monitored_counters:
      stats.append("%s=%sc;;;0" % (key, value))

if t1<warn_time:
  reply = "OK"
  exit_code = 0
else:
  reply = "WARNING"
  exit_code = 1

print("PHP-FPM %s - %6.4f seconds|time=%ss;;;0 %s"
      % (reply, t1, t1, " ".join(stats)))

sys.exit(exit_code)
