#!/usr/bin/python

import urllib2, re, sys, time, getopt, socket

show_states = list("_RWCD")
states = dict(
  _ = "waiting",
  S = "starting",
  R = "reading",
  W = "sending",
  K = "keepalive",
  D = "dns_lookup",
  C = "closing",
  L = "logging",
  G = "finishing",
  I = "idle",
  # lighttpd
  E = "error"
)
states["."] = "open_slot"

apache2lighttpd = dict(
  W = "h",
  R = "r",
  S = "W",
  #h = "W",
  #r = "R",
  #q = "R",
  #Q = "R",
  #s = "W",
  #S = "W"
)

si = dict(
   B = 1,
  KB = 1024,
  MB = 1048576,
  GB = 1048576*1024,
  TB = 1048576*1048576
)

def getvalue(line, conv=str):
    return conv(line.strip().split(": ", 1)[1])

count = dict([(x, 0) for x in states.keys()])

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

htmltags = re.compile(r"<[^>]*>", re.I)
if '-l' in argv:
  lighttpd = True
else:
  lighttpd = False
if '-U' in argv:
  URL = argv['-U']
else:
  URL = "http://%s/server-status" % argv['-H']
if not '-d' in argv:
  URL += "?auto"
warn_time = float(argv.get("-w", 3.0))
crit_time = float(argv.get("-c", 5.0))
try:
  socket.setdefaulttimeout(int(argv.get('-t', 10)))
  t0 = time.time()
  f = urllib2.urlopen(URL)
  t1 = time.time()-t0
except Exception, e:
  print "HTTP CRITICAL - %s" % e
  sys.exit(2)
# search for worker table
while True:
  line = f.readline()
  if not line:
    break # EOF
  elif line.startswith("<table border="):
    break
  elif line.startswith("Total Accesses:"):
    total_accesses = getvalue(line, int)
  elif line.startswith("Total kBytes:"):
    total_traffic = 1024*getvalue(line, int)
  elif line.startswith("IdleServers:"):
    # switch to lighttpd mode
    lighttpd = True
  elif line.startswith("Scoreboard:"):
    scores = getvalue(line)
    for key in count.keys():
      if lighttpd:
        count[key] = scores.count(apache2lighttpd.get(key, key))
      else:
        count[key] = scores.count(key)
  elif "Total accesses:" in line:
    a = htmltags.sub("", line.strip()).split(' ')
    total_accesses = a[2]
    total_traffic = float(a[6])*si[a[7].upper()]

if '-d' in argv:
  # skip one next line
  f.readline()
  # read data
  buf = ""
  for line in f.readlines():
    if line.startswith("</table>"):
      f.close()
      break
    if line.strip()=="":
      if buf:
        tabrow = htmltags.sub("", buf).split("\t")
        srv,pid,acc,m,cpu,ss,req,conn,child,slot,client,vhost,request,_ = tabrow
        ss = int(ss)
        if m=="W" and ss>10:
          print "ss=%s, pid=%s, ip=%s, req=%s" % (ss,pid,client,request)
        count[m] += 1
      buf = ""
    else:
      buf += line.strip().replace("</td>", "\t")

stats = ' '.join([
  "%s=%s;;;0" % (states[key], count[key])
  for key in show_states
])

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

print "HTTP %s - %6.4f seconds, %s|time=%ss;;;0 accesses=%sc;;;0 traffic=%sc;;;0 %s" \
      % (reply, t1, stats, t1, total_accesses, total_traffic, stats)

sys.exit(exit_code)
