iwla/iwla.py

412 lines
12 KiB
Python
Raw Normal View History

2014-11-18 20:18:53 +01:00
#!/usr/bin/env python
import os
import re
import time
import glob
import imp
2014-11-19 19:34:16 +01:00
import pickle
import gzip
2014-11-19 19:45:41 +01:00
from display import *
2014-11-20 15:25:43 +01:00
# Default configuration
DB_ROOT = './output/'
DISPLAY_ROOT = './output/'
log_format = '$server_name:$server_port $remote_addr - $remote_user [$time_local] ' +\
'"$request" $status $body_bytes_sent ' +\
2014-11-21 10:41:29 +01:00
'"$http_referer" "$http_user_agent"'
2014-11-20 15:25:43 +01:00
time_format = '%d/%b/%Y:%H:%M:%S +0100'
2014-11-20 16:15:57 +01:00
pre_analysis_hooks = []
post_analysis_hooks = []
display_hooks = []
2014-11-20 15:25:43 +01:00
from conf import *
2014-11-18 20:18:53 +01:00
print '==> Start'
2014-11-20 09:37:54 +01:00
meta_visit = {}
2014-11-19 19:34:16 +01:00
analyse_started = False
2014-11-19 19:45:41 +01:00
current_visits = {}
2014-11-19 21:37:37 +01:00
cache_plugins = {}
2014-11-20 11:50:06 +01:00
display = {}
2014-11-18 20:18:53 +01:00
2014-11-21 10:41:29 +01:00
log_format_extracted = re.sub(r'([^\$\w])', r'\\\g<1>', log_format)
2014-11-18 20:18:53 +01:00
log_format_extracted = re.sub(r'\$(\w+)', '(?P<\g<1>>.+)', log_format_extracted)
http_request_extracted = re.compile(r'(?P<http_method>\S+) (?P<http_uri>\S+) (?P<http_version>\S+)')
log_re = re.compile(log_format_extracted)
2014-11-19 08:01:12 +01:00
uri_re = re.compile(r'(?P<extract_uri>[^\?]*)[\?(?P<extract_parameters>.*)]?')
2014-11-18 20:18:53 +01:00
pages_extensions = ['/', 'html', 'xhtml', 'py', 'pl', 'rb', 'php']
viewed_http_codes = [200]
2014-11-20 16:15:57 +01:00
HOOKS_ROOT = './plugins/'
PRE_HOOK_DIRECTORY = HOOKS_ROOT + 'pre_analysis/'
POST_HOOK_DIRECTORY = HOOKS_ROOT + 'post_analysis/'
DISPLAY_HOOK_DIRECTORY = HOOKS_ROOT + 'display/'
2014-11-19 19:34:16 +01:00
META_PATH = DB_ROOT + 'meta.db'
DB_FILENAME = 'iwla.db'
2014-11-19 08:01:12 +01:00
2014-11-20 16:15:57 +01:00
plugins = {PRE_HOOK_DIRECTORY : pre_analysis_hooks, POST_HOOK_DIRECTORY : post_analysis_hooks, DISPLAY_HOOK_DIRECTORY : display_hooks}
ANALYSIS_CLASS = 'HTTP'
API_VERSION = 1
def preloadPlugins():
2014-11-21 10:41:29 +01:00
ret = True
2014-11-20 16:15:57 +01:00
for root in plugins.keys():
for plugin_name in plugins[root]:
p = root + '/' + plugin_name
try:
2014-11-21 10:41:29 +01:00
fp, pathname, description = imp.find_module(plugin_name, [root])
cache_plugins[p] = imp.load_module(plugin_name, fp, pathname, description)
#cache_plugins[p] = imp.load_module(p,None,p,("py","r",imp.PKG_DIRECTORY))
#cache_plugins[p] = imp.load_source(p, p)
mod = cache_plugins[p]
#print dir(mod)
#print "Register %s -> %s" % (p, mod)
2014-11-20 16:15:57 +01:00
infos = mod.get_plugins_infos()
if infos['class'] != ANALYSIS_CLASS or \
API_VERSION < infos['min_version'] or\
(infos['max_version'] != -1 and (API_VERSION > infos['max_version'])):
del cache_plugins[p]
elif not mod.load():
del cache_plugins[p]
except Exception as e:
print 'Error loading \'%s\' => %s' % (p, e)
2014-11-21 10:41:29 +01:00
ret = False
return ret
2014-11-20 16:15:57 +01:00
2014-11-18 20:18:53 +01:00
2014-11-19 19:45:41 +01:00
def createEmptyVisits():
visits = {'days_stats' : {}, 'month_stats' : {}, 'visits' : {}}
return visits
2014-11-19 21:37:37 +01:00
def createEmptyMeta():
2014-11-20 11:50:06 +01:00
meta = {'last_time' : None}
2014-11-19 21:37:37 +01:00
return meta
2014-11-20 11:50:06 +01:00
def createEmptyDisplay():
display = {}
return display
2014-11-19 19:45:41 +01:00
def getDBFilename(time):
2014-11-19 19:34:16 +01:00
return (DB_ROOT + '%d/%d_%s') % (time.tm_year, time.tm_mon, DB_FILENAME)
2014-11-19 08:01:12 +01:00
2014-11-19 19:34:16 +01:00
def serialize(obj, filename):
base = os.path.dirname(filename)
if not os.path.exists(base):
os.makedirs(base)
2014-11-19 08:01:12 +01:00
2014-11-20 08:18:31 +01:00
# TODO : remove return
return
2014-11-19 19:34:16 +01:00
with open(filename + '.tmp', 'wb+') as f:
pickle.dump(obj, f)
f.seek(0)
with gzip.open(filename, 'w') as fzip:
fzip.write(f.read())
os.remove(filename + '.tmp')
2014-11-19 08:01:12 +01:00
2014-11-19 19:34:16 +01:00
def deserialize(filename):
if not os.path.exists(filename):
return None
2014-11-19 08:01:12 +01:00
2014-11-19 19:34:16 +01:00
with gzip.open(filename, 'r') as f:
return pickle.load(f)
return None
2014-11-19 08:01:12 +01:00
2014-11-21 10:41:29 +01:00
def callPlugins(root, *args):
2014-11-20 16:15:57 +01:00
print '==> Call plugins (%s)' % root
for p in plugins[root]:
2014-11-19 08:01:12 +01:00
print '\t%s' % (p)
2014-11-20 16:15:57 +01:00
mod = cache_plugins[root + '/' + p]
2014-11-21 10:41:29 +01:00
mod.hook(*args)
2014-11-19 08:01:12 +01:00
2014-11-18 20:18:53 +01:00
def isPage(request):
for e in pages_extensions:
if request.endswith(e):
return True
return False
def appendHit(hit):
2014-11-20 08:18:31 +01:00
remote_addr = hit['remote_addr']
if not remote_addr in current_visits['visits'].keys():
createUser(hit)
return
super_hit = current_visits['visits'][remote_addr]
2014-11-21 10:41:29 +01:00
super_hit['requests'].append(hit)
super_hit['bandwidth'] += int(hit['body_bytes_sent'])
2014-11-20 08:18:31 +01:00
super_hit['last_access'] = meta_visit['last_time']
2014-11-18 20:18:53 +01:00
request = hit['extract_request']
if 'extract_uri' in request.keys():
uri = request['extract_uri']
else:
uri = request['http_uri']
hit['is_page'] = isPage(uri)
2014-11-19 21:37:37 +01:00
# Don't count 3xx status
status = int(hit['status'])
if status >= 300 and status < 400: return
2014-11-18 20:18:53 +01:00
if super_hit['robot'] or\
2014-11-20 09:37:54 +01:00
not status in viewed_http_codes:
2014-11-18 20:18:53 +01:00
page_key = 'not_viewed_pages'
hit_key = 'not_viewed_hits'
else:
page_key = 'viewed_pages'
hit_key = 'viewed_hits'
if hit['is_page']:
super_hit[page_key] += 1
else:
super_hit[hit_key] += 1
2014-11-19 08:01:12 +01:00
def createUser(hit):
2014-11-19 21:37:37 +01:00
super_hit = current_visits['visits'][hit['remote_addr']] = {}
2014-11-21 10:41:29 +01:00
super_hit['remote_addr'] = hit['remote_addr']
super_hit['viewed_pages'] = 0
super_hit['viewed_hits'] = 0
super_hit['not_viewed_pages'] = 0
super_hit['not_viewed_hits'] = 0
super_hit['bandwidth'] = 0
2014-11-20 08:18:31 +01:00
super_hit['last_access'] = meta_visit['last_time']
2014-11-21 10:41:29 +01:00
super_hit['requests'] = []
2014-11-20 16:15:57 +01:00
super_hit['robot'] = False
2014-11-21 10:41:29 +01:00
super_hit['hit_only'] = 0
2014-11-18 20:18:53 +01:00
appendHit(hit)
2014-11-19 19:45:41 +01:00
def decodeHTTPRequest(hit):
2014-11-18 20:18:53 +01:00
if not 'request' in hit.keys(): return False
groups = http_request_extracted.match(hit['request'])
if groups:
hit['extract_request'] = groups.groupdict()
2014-11-21 10:41:29 +01:00
uri_groups = uri_re.match(hit['extract_request']['http_uri'])
2014-11-18 20:18:53 +01:00
if uri_groups:
2014-11-19 08:01:12 +01:00
d = uri_groups.groupdict()
hit['extract_request']['extract_uri'] = d['extract_uri']
if 'extract_parameters' in d.keys():
hit['extract_request']['extract_parameters'] = d['extract_parameters']
2014-11-18 20:18:53 +01:00
else:
print "Bad request extraction " + hit['request']
return False
2014-11-21 10:41:29 +01:00
referer_groups = uri_re.match(hit['http_referer'])
2014-11-18 20:18:53 +01:00
if referer_groups:
2014-11-19 08:01:12 +01:00
referer = hit['extract_referer'] = referer_groups.groupdict()
2014-11-18 20:18:53 +01:00
return True
2014-11-19 19:45:41 +01:00
def decodeTime(hit):
2014-11-18 20:18:53 +01:00
t = hit['time_local']
hit['time_decoded'] = time.strptime(t, time_format)
2014-11-21 10:41:29 +01:00
def getDisplayIndex():
cur_time = meta_visit['last_time']
filename = '%d/index_%d.html' % (cur_time.tm_year, cur_time.tm_mon)
return display.get(filename, None)
2014-11-20 11:50:06 +01:00
def generateDisplayDaysStat():
cur_time = meta_visit['last_time']
title = 'Stats %d/%d' % (cur_time.tm_mon, cur_time.tm_year)
filename = '%d/index_%d.html' % (cur_time.tm_year, cur_time.tm_mon)
page = createPage(display, filename, title)
2014-11-20 11:50:06 +01:00
2014-11-21 10:41:29 +01:00
days = createTable('By day', ['Day', 'Visits', 'Pages', 'Hits', 'Bandwidth', 'Robot Bandwidth'])
2014-11-20 11:50:06 +01:00
keys = current_visits['days_stats'].keys()
keys.sort()
nb_visits = 0
for k in keys:
stats = current_visits['days_stats'][k]
row = [k, stats['nb_visitors'], stats['viewed_pages'], stats['viewed_hits'], stats['viewed_bandwidth'], stats['not_viewed_bandwidth']]
row = map(lambda(v): str(v), row)
appendRowToTable(days, row)
2014-11-20 11:50:06 +01:00
nb_visits += stats['nb_visitors']
stats = current_visits['month_stats']
nb_days = len(keys)
row = [0, nb_visits, stats['viewed_pages'], stats['viewed_hits'], stats['viewed_bandwidth'], stats['not_viewed_bandwidth']]
if nb_days:
row = map(lambda(v): str(int(v/nb_days)), row)
else:
row = map(lambda(v): '0', row)
row[0] = 'Average'
appendRowToTable(days, row)
2014-11-20 11:50:06 +01:00
row = ['Total', nb_visits, stats['viewed_pages'], stats['viewed_hits'], stats['viewed_bandwidth'], stats['not_viewed_bandwidth']]
row = map(lambda(v): str(v), row)
appendRowToTable(days, row)
appendBlockToPage(page, days)
2014-11-20 11:50:06 +01:00
def generateDisplay():
generateDisplayDaysStat()
callPlugins(DISPLAY_HOOK_DIRECTORY, current_visits, display)
2014-11-21 10:41:29 +01:00
buildPages(DISPLAY_ROOT, display)
2014-11-18 20:18:53 +01:00
2014-11-19 21:37:37 +01:00
def generateStats(visits):
2014-11-19 19:34:16 +01:00
stats = {}
stats['viewed_bandwidth'] = 0
stats['not_viewed_bandwidth'] = 0
stats['viewed_pages'] = 0
stats['viewed_hits'] = 0
2014-11-21 10:41:29 +01:00
#stats['requests'] = set()
2014-11-19 21:37:37 +01:00
stats['nb_visitors'] = 0
2014-11-19 19:34:16 +01:00
2014-11-19 21:37:37 +01:00
for k in visits.keys():
super_hit = visits[k]
2014-11-19 19:34:16 +01:00
if super_hit['robot']:
2014-11-21 10:41:29 +01:00
stats['not_viewed_bandwidth'] += super_hit['bandwidth']
2014-11-19 19:34:16 +01:00
continue
2014-11-21 10:41:29 +01:00
#print "[%s] =>\t%d/%d" % (k, super_hit['viewed_pages'], super_hit['viewed_hits'])
2014-11-19 21:37:37 +01:00
2014-11-20 14:09:01 +01:00
if not super_hit['hit_only']:
stats['nb_visitors'] += 1
2014-11-21 10:41:29 +01:00
stats['viewed_bandwidth'] += super_hit['bandwidth']
2014-11-19 19:34:16 +01:00
stats['viewed_pages'] += super_hit['viewed_pages']
stats['viewed_hits'] += super_hit['viewed_hits']
2014-11-21 10:41:29 +01:00
# for p in super_hit['requests']:
2014-11-19 21:37:37 +01:00
# if not p['is_page']: continue
# req = p['extract_request']
2014-11-21 10:41:29 +01:00
# stats['requests'].add(req['extract_uri'])
2014-11-19 19:34:16 +01:00
2014-11-19 21:37:37 +01:00
return stats
def generateMonthStats():
2014-11-20 11:50:06 +01:00
display = createEmptyDisplay()
2014-11-19 21:37:37 +01:00
visits = current_visits['visits']
stats = generateStats(visits)
2014-11-19 19:34:16 +01:00
cur_time = meta_visit['last_time']
print "== Stats for %d/%d ==" % (cur_time.tm_year, cur_time.tm_mon)
print stats
2014-11-19 21:37:37 +01:00
valid_visitors = {k: v for (k,v) in visits.items() if not visits[k]['robot']}
2014-11-21 10:41:29 +01:00
callPlugins(POST_HOOK_DIRECTORY, valid_visitors, stats)
2014-11-19 21:37:37 +01:00
current_visits['month_stats'] = stats
2014-11-19 19:45:41 +01:00
path = getDBFilename(cur_time)
2014-11-19 19:34:16 +01:00
if os.path.exists(path):
os.remove(path)
print "==> Serialize to %s" % path
2014-11-19 19:45:41 +01:00
serialize(current_visits, path)
2014-11-19 19:34:16 +01:00
2014-11-20 11:50:06 +01:00
generateDisplay()
2014-11-19 21:37:37 +01:00
def generateDayStats():
visits = current_visits['visits']
callPlugins(PRE_HOOK_DIRECTORY, visits)
stats = generateStats(visits)
cur_time = meta_visit['last_time']
print "== Stats for %d/%d/%d ==" % (cur_time.tm_year, cur_time.tm_mon, cur_time.tm_mday)
if cur_time.tm_mday > 1:
last_day = cur_time.tm_mday - 1
while last_day:
if last_day in current_visits['days_stats'].keys():
break
last_day -= 1
if last_day:
for k in stats.keys():
stats[k] -= current_visits['days_stats'][last_day][k]
2014-11-20 08:18:31 +01:00
stats['nb_visitors'] = 0
for k in visits.keys():
if visits[k]['robot']: continue
if visits[k]['last_access'].tm_mday == cur_time.tm_mday:
stats['nb_visitors'] += 1
2014-11-19 21:37:37 +01:00
print stats
current_visits['days_stats'][cur_time.tm_mday] = stats
2014-11-19 19:34:16 +01:00
def newHit(hit):
2014-11-19 19:45:41 +01:00
global current_visits
2014-11-19 19:34:16 +01:00
global analyse_started
2014-11-18 20:18:53 +01:00
2014-11-19 19:45:41 +01:00
decodeTime(hit)
2014-11-18 20:18:53 +01:00
t = hit['time_decoded']
2014-11-19 19:34:16 +01:00
cur_time = meta_visit['last_time']
2014-11-18 20:18:53 +01:00
if cur_time == None:
2014-11-20 09:37:54 +01:00
current_visits = deserialize(getDBFilename(t)) or createEmptyVisits()
2014-11-19 19:34:16 +01:00
analyse_started = True
2014-11-18 20:18:53 +01:00
else:
2014-11-19 19:34:16 +01:00
if not analyse_started:
if time.mktime(cur_time) >= time.mktime(t):
return
else:
analyse_started = True
if cur_time.tm_mon != t.tm_mon:
2014-11-19 19:45:41 +01:00
generateMonthStats()
2014-11-20 09:37:54 +01:00
current_visits = deserialize(getDBFilename(t)) or createEmptyVisits()
2014-11-19 21:37:37 +01:00
elif cur_time.tm_mday != t.tm_mday:
generateDayStats()
2014-11-19 19:34:16 +01:00
meta_visit['last_time'] = t
2014-11-19 19:45:41 +01:00
if not decodeHTTPRequest(hit): return False
2014-11-19 19:34:16 +01:00
for k in hit.keys():
if hit[k] == '-': hit[k] = ''
2014-11-18 20:18:53 +01:00
2014-11-20 08:18:31 +01:00
appendHit(hit)
2014-11-18 20:18:53 +01:00
return True
2014-11-20 16:15:57 +01:00
preloadPlugins()
2014-11-18 20:18:53 +01:00
print '==> Analysing log'
2014-11-19 19:34:16 +01:00
2014-11-20 09:37:54 +01:00
meta_visit = deserialize(META_PATH) or createEmptyMeta()
2014-11-21 10:41:29 +01:00
if meta_visit['last_time']:
current_visits = deserialize(getDBFilename(meta_visit['last_time'])) or createEmptyVisits()
else:
current_visits = createEmptyVisits()
2014-11-19 19:34:16 +01:00
2014-11-20 15:25:43 +01:00
f = open(analyzed_filename)
2014-11-18 20:18:53 +01:00
for l in f:
2014-11-21 10:41:29 +01:00
# print "line " + l
2014-11-18 20:18:53 +01:00
groups = log_re.match(l)
if groups:
if not newHit(groups.groupdict()):
break
else:
print "No match " + l
2014-11-21 10:41:29 +01:00
f.close()
2014-11-18 20:18:53 +01:00
2014-11-19 19:45:41 +01:00
if analyse_started:
2014-11-20 08:18:31 +01:00
generateDayStats()
2014-11-19 19:45:41 +01:00
generateMonthStats()
serialize(meta_visit, META_PATH)
else:
print '==> Analyse not started : nothing to do'
2014-11-21 10:41:29 +01:00
generateMonthStats()