Newer
Older
attend-cgi / call.cgi
#!/usr/bin/env python
import os
import sys
import cgi
import re
import json
import pickle
from datetime import datetime
from datetime import timedelta

form = cgi.FieldStorage()

print "Content-Type: application/json"
print ""

class Data(object):
    def __init__(self, value = ""): self._value = value
    @property
    def value(self): return self._value
    @value.setter
    def value(self, value): self._value = value


def machine_name(ip_str):
    ip = [int(v) for v in ip_str.split(".")]
    if ip_str.startswith("172.29.11"):
        if   ip[2] == 116:  prefix = "GRL"
        elif ip[2] == 117:  prefix = "ML1"
        elif ip[2] == 118:  prefix = "ML2"
        elif ip[2] == 119:  prefix = "HSJ"
        else: return ip_str
        if prefix != "HSJ" and 151 <= ip[3] <= 150 + 49 or\
           prefix == "HSJ" and 151 <= ip[3] <= 150 + 63:  
            return "%s-%02d"  % (prefix, ip[3]-150)
        if 220 <= ip[3] <= 220 + 5:  
            return "%s-K%02d" % (prefix, ip[3]-220)
        else: return ip_str

form = {
        "date": Data(sys.argv[1]),
        "from": Data(sys.argv[2]),
          "to": Data(sys.argv[3]),
}

fr =  datetime.strptime(form["date"].value + " " + form["from"].value, "%Y %m %d %H:%M")
to =  datetime.strptime(form["date"].value + " " + form["to"].value, "%Y %m %d %H:%M")

#logdir = "/var/log/httpd/"
logdir = "./"

l = fr + timedelta(7) # a week after
higher = "access_log-%04d%02d%02d"%(l.year, l.month, l.day)
lower  = "access_log-%04d%02d%02d"%(fr.year, fr.month, fr.day)
logfiles = [fname for fname in os.listdir(logdir) 
                if fname.startswith("access_log-") and lower <= fname and fname <=higher]
if not logfiles: logfiles.append('access_log')

maildb = pickle.load(open("name.pickle"))
db = {}
lines = []
for fname in logfiles[-2:]:
    with open(logdir + fname) as f:
        line = [l for l in f.readlines() if "logonoff" in l]
        line = [re.match(r'^([0-9.]*).*\[(\d+/\w+/\d+:\d+:\d+:\d+).*logonoff\?(.*) HTTP', l) for l in line]
        line = [l.groups() for l in line if l]
        line = [(machine_name(ip), datetime.strptime(date, '%d/%b/%Y:%H:%M:%S'), action) 
                for ip, date, action in line]
        for host, date, action in line:
            if host in db:
                db[host].append([date,action])
            else:
                db[host] = [[date,action]]
for mac in db.keys():
    candidate = []
    for date, action in db[mac]:
        if action.startswith("on:"):
            if date < to:
                _, id_ = action.split(":")
                if id_ in maildb:
                    date = date.strftime("%Y/%m/%d %H:%M")
                    candidate.append([mac, date, action, id_, 
                        maildb[id_]["no"], maildb[id_]["name"],
                        maildb[id_]["reading"], maildb[id_]["dep"]])
        if action.startswith("off:") or action.startswith("shutdown"):
            if not fr < date and candidate:
                candidate.pop()
    lines.extend(candidate)

json.dump(lines, sys.stdout)