Source

loganalyze / loganalyze.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
#!/usr/bin/env python

# vim: et sw=4 ts=4 softtabstop=4 foldmethod=expr tw=79

import os
import sys
import re
import subprocess
import shlex
import readline
import traceback
import math

from datetime import datetime, timedelta
from optparse import OptionParser, OptParseError, OptionValueError

# XXX: Debug
import pdb
from pprint import pprint as pp

# TODO: Add readline autocompletion support
#       Add ability to store time periods and switch to them quickly

# TODO: Aggregators
#       TotalHitsPerUnitTime
#       TotalHitsByTimeToRender
#       HitsPerUrlPerIP
#       same as above with per unit time
#       same as above with time to render
#       HitsPerIPPerUrl
#       same as above with per unit time
#       same as above with time to render

class NonExitingOptionParser(OptionParser):
    def exit(self, status="foo", msg="bar"):
        raise OptParseError("")

class Aggregator(object):
    def __init__(self, log_analyzer):
        self._log_analyzer = log_analyzer

    def __call__(self, **kwargs):
        """
        Call the aggregator object, getting back a dictionary.
        """
        # NOTE: *args includes 'start' and 'end'
        for arg in kwargs:
                if not hasattr(self, "_%s" % arg) or \
                   not getattr(self, "_%s" % arg) == kwargs[arg]:
                    break
        else:
            # We've already done the computation for this time period including all args, just
            # return what we've already done
            return self.aggr_data

        # Otherwise, aggregate all the data for the timeperiod and args into self.aggr_data
        self._call(**kwargs)

    def _call(self, **kwargs):
        for arg in kwargs:
            attr = "_%s" % arg
            value = kwargs[arg]
            # Special handling for ._{foo}_filter attrs, compile them ahead of time
            if re.match('^_re_.*$', attr) and value is not None:
                value = re.compile(value)
            setattr(self, attr, value)
        self.aggr_data = {}
        self._do_aggregation()

    def _do_aggregation(self):
        for datetimeobj, url, ms, ip in self._log_analyzer.log_data:
            if self._start <= datetimeobj <= self._end:
                self._aggregate(datetimeobj, url, ms, ip)

    def _total_seconds(self, timedeltaobj):
        return timedeltaobj.seconds + (timedeltaobj.days*24*3600)

class CountAggr(Aggregator):
    def _aggregate(self, datetimeobj, url, ms, ip):
        # short circuit if the re_filter does not match the given self._key
        if self._re_filter and not self._re_filter.search(self._key):
            return
        if self._re_rollup:
            m = self._re_rollup.search(self._key)
            if m:
                self._key = self._key[m.start():m.end()]
        hits = self.aggr_data.setdefault(self._key, 0)
        self.aggr_data[self._key] = hits + 1

    def display(self, display_obj, num, format_str):
        sorted_keys = sorted(self.aggr_data, lambda a,b: cmp(self.aggr_data[a], self.aggr_data[b]))
        for key in sorted_keys[-num:]:
            display_obj.write(format_str % (key, self.aggr_data[key]))

class HitsPerUrl(CountAggr):
    # __call__ requires start, end, re_filter keyword args
    def _aggregate(self, datetimeobj, url, ms, ip):
        self._key = url
        super(HitsPerUrl, self)._aggregate(datetimeobj, url, ms, ip)

    def display(self, display_obj, num):
        super(HitsPerUrl, self).display(display_obj, num, "%-100s %10d\n")

class HitsPerIP(CountAggr):
    # __call__ requires start, end, re_filter keyword args
    def _aggregate(self, datetimeobj, url, ms, ip):
        self._key = ip
        super(HitsPerIP, self)._aggregate(datetimeobj, url, ms, ip)

    def display(self, display_obj, num):
        super(HitsPerIP, self).display(display_obj, num, "%-20s %10d\n")

class PerUnitTimeAggr(Aggregator):
    def _aggregate(self, datetimeobj, url, ms, ip):
        # short circuit if the re_filter does not match the given self._key
        if self._re_filter and not self._re_filter.search(self._key):
            return
        sub_aggr = self.aggr_data.setdefault(self._key, {'hits': 0})
        sub_aggr['hits'] += 1
        # Note that we are guaranteed that datetimeobj is between start and end
        seconds_offset_into_range = datetimeobj - self._start
        seconds_offset_into_range = self._total_seconds(seconds_offset_into_range)
        multiplier = seconds_offset_into_range / self._step
        bucket_start = self._start + timedelta(seconds=( self._step * (multiplier )))
        bucket_end   = self._start + timedelta(seconds=((self._step * (multiplier+1)) - 1))
        if bucket_end > self._end:
            bucket_end = self._end
        hits_for_bucket = sub_aggr.setdefault((bucket_start, bucket_end), 0)
        sub_aggr[(bucket_start, bucket_end)] = hits_for_bucket + 1

    def display(self, display_obj):
        sorted_keys = sorted(self.aggr_data, lambda a,b: cmp(self.aggr_data[a]['hits'], self.aggr_data[b]['hits']))
        for key in sorted_keys:
            display_obj.write("%-100s %10d\n" % (key, self.aggr_data[key]['hits']))
            time_period_keys = [ x for x in self.aggr_data[key] if x != 'hits' ]
            sorted_time_period_keys = sorted(time_period_keys, lambda a,b: cmp(a[0], b[0]))
            for bucket_bottom, bucket_top in sorted_time_period_keys:
                display_obj.write("\t%s - %s %20d\n" % (bucket_bottom, bucket_top, 
                                                        self.aggr_data[key][(bucket_bottom, bucket_top)]))
            display_obj.write("\n")

class HitsPerUrlPerUnitTime(PerUnitTimeAggr):
    # __call__ requires start, end, step, re_filter keyword args
    def _aggregate(self, datetimeobj, url, ms, ip):
        self._key = url 
        super(HitsPerUrlPerUnitTime, self)._aggregate(datetimeobj, url, ms, ip)

class HitsPerIPPerUnitTime(PerUnitTimeAggr):
    # __call__ requires start, end, step, re_filter keyword args
    def _aggregate(self, datetimeobj, url, ms, ip):
        self._key = ip
        super(HitsPerIPPerUnitTime, self)._aggregate(datetimeobj, url, ms, ip)

class TimeToRenderLinearAggr(Aggregator):
    def _aggregate(self, datetimeobj, url, ms, ip):
        # short circuit if the re_filter does not match the given self._key
        if self._re_filter and not self._re_filter.search(self._key):
            return
        sub_aggr = self.aggr_data.setdefault(self._key, {'hits': 0})
        sub_aggr['hits'] += 1
        bucket_idx = ms / self._ms_step
        bucket_start = self._ms_step * bucket_idx
        bucket_end  = self._ms_step * (bucket_idx + 1)
        hits_for_bucket = sub_aggr.setdefault((bucket_start, bucket_end), 0)
        sub_aggr[(bucket_start, bucket_end)] = hits_for_bucket + 1

    def display(self, display_obj):
        sorted_keys = sorted(self.aggr_data, lambda a,b: cmp(self.aggr_data[a]['hits'], self.aggr_data[b]['hits']))
        for key in sorted_keys:
            display_obj.write("%-100s %10d\n" % (key, self.aggr_data[key]['hits']))
            ms_period_keys = [ x for x in self.aggr_data[key] if x != 'hits' ]
            sorted_ms_period_keys = sorted(ms_period_keys, lambda a,b: cmp(a[0], b[0]))
            for bucket_bottom, bucket_top in sorted_ms_period_keys:
                    display_obj.write("\t%4d ms - %4d ms %10d\n" % (bucket_bottom, bucket_top,
                                                                    self.aggr_data[key][(bucket_bottom, bucket_top)]))
            display_obj.write("\n")
 
class HitsPerUrlByTimeToRenderLinear(TimeToRenderLinearAggr):
    # __call__ requires start, end, ms_step, re_filter keyword args
    def _aggregate(self, datetimeobj, url, ms, ip):
        self._key = url
        super(HitsPerUrlByTimeToRenderLinear, self)._aggregate(datetimeobj, url, ms, ip)

class HitsPerIPByTimeToRenderLinear(TimeToRenderLinearAggr):
    # __call__ requires start, end, ms_step, re_filter keyword args
    def _aggregate(self, datetimeobj, url, ms, ip):
        self._key = ip
        super(HitsPerIPByTimeToRenderLinear, self)._aggregate(datetimeobj, url, ms, ip)

class UrlAndIPAggr(Aggregator):
    def _aggregate(self, datetimeobj, url, ms, ip):
        if self._re_filter and not self._re_filter.search(self._key1):
            return
        sub_aggr = self.aggr_data.setdefault(self._key1, {'hits': 0})
        sub_aggr['hits'] += 1
        hits_for_second_key = sub_aggr.setdefault(self._key2, 0)
        sub_aggr[self._key2] = hits_for_second_key + 1

    def display(self, display_obj):
        sorted_keys = sorted(self.aggr_data, lambda a,b: cmp(self.aggr_data[a]['hits'], self.aggr_data[b]['hits']))
        for key in sorted_keys:
            display_obj.write(self._key1_fmt % (key, self.aggr_data[key]['hits']))
            second_level_keys = [ x for x in self.aggr_data[key] if x != 'hits' ]
            sorted_second_level_keys = sorted(second_level_keys, lambda a,b: cmp(self.aggr_data[key][a], self.aggr_data[key][b]))
            for second_key in sorted_second_level_keys:
                display_obj.write(self._key2_fmt % (second_key, self.aggr_data[key][second_key]))
            display_obj.write("\n")

class HitsPerUrlPerIP(UrlAndIPAggr):
    # __call__ requires start, end, re_filter keyword args
    def _aggregate(self, datetimeobj, url, ms, ip):
        # TODO: move this stuff into __init__
        self._key1 = url
        self._key2 = ip
        self._key1_fmt = "%-100s %10d\n"
        self._key2_fmt = "\t%16s %10d\n"
        super(HitsPerUrlPerIP, self)._aggregate(datetimeobj, url, ms, ip)

class HitsPerIPPerUrl(UrlAndIPAggr):
    # __call__ requires start, end, re_filter keyword args
    def _aggregate(self, datetimeobj, url, ms, ip):
        # TODO: move this stuff into __init__
        self._key1 = ip
        self._key2 = url
        self._key1_fmt = "%16s %10d\n"
        self._key2_fmt = "\t%-100s %10d\n"
        super(HitsPerIPPerUrl, self)._aggregate(datetimeobj, url, ms, ip)

class UrlAndIPByTimeToRenderLinearAggr(Aggregator):
    def _aggregate(self, datetimeobj, url, ms, ip):
        if self._re_filter and not self._re_filter.search(self._key1):
            return
        sub_aggr = self.aggr_data.setdefault(self._key1, {'hits': 0})
        sub_aggr['hits'] += 1
        sub_aggr2 = sub_aggr.setdefault(self._key2, {'hits': 0})
        sub_aggr2['hits'] += 1
        bucket_idx = ms / self._ms_step
        bucket_start = self._ms_step * bucket_idx
        bucket_end  = self._ms_step * (bucket_idx + 1)
        hits_for_bucket = sub_aggr2.setdefault((bucket_start, bucket_end), 0)
        sub_aggr2[(bucket_start, bucket_end)] = hits_for_bucket + 1

    def display(self, display_obj):
        sorted_keys = sorted(self.aggr_data, lambda a,b: cmp(self.aggr_data[a]['hits'], self.aggr_data[b]['hits']))
        for key in sorted_keys:
            display_obj.write(self._key1_fmt % (key, self.aggr_data[key]['hits']))
            second_level_keys = [ x for x in self.aggr_data[key] if x != 'hits' ]
            sorted_second_level_keys = sorted(second_level_keys, lambda a,b: cmp(self.aggr_data[key][a]['hits'], self.aggr_data[key][b]['hits']))
            for second_key in sorted_second_level_keys:
                display_obj.write(self._key2_fmt % (second_key, self.aggr_data[key][second_key]['hits']))
                ms_period_keys = [ x for x in self.aggr_data[key][second_key] if x != 'hits' ]
                sorted_ms_period_keys = sorted(ms_period_keys, lambda a,b: cmp(a[0], b[0]))
                for bucket_bottom, bucket_top in sorted_ms_period_keys:
                    display_obj.write("\t\t%4d ms - %4d ms %10d\n" % (bucket_bottom, bucket_top,
                                                                    self.aggr_data[key][second_key][(bucket_bottom, bucket_top)]))
                display_obj.write("\n")
            display_obj.write("\n")


class HitsPerUrlPerIPByTimeToRenderLinear(UrlAndIPByTimeToRenderLinearAggr):
    # __call__ requires start, end, ms_step and re_filter keyword args
    def _aggregate(self, datetimeobj, url, ms, ip):
        # TODO: move this stuff into __init__
        self._key1 = url
        self._key2 = ip
        self._key1_fmt = "%-100s %10d\n"
        self._key2_fmt = "\t%16s %10d\n"
        super(HitsPerUrlPerIPByTimeToRenderLinear, self)._aggregate(datetimeobj, url, ms, ip)

class HitsPerIPPerUrlByTimeToRenderLinear(UrlAndIPByTimeToRenderLinearAggr):
    # __call__ requires start, end, ms_step and re_filter keyword args
    def _aggregate(self, datetimeobj, url, ms, ip):
        # TODO: move this stuff into __init__
        self._key1 = ip
        self._key2 = url
        self._key1_fmt = "%16s %10d\n"
        self._key2_fmt = "\t%-100s %10d\n"
        super(HitsPerIPPerUrlByTimeToRenderLinear, self)._aggregate(datetimeobj, url, ms, ip)

class LogAnalyzer(object):

    month_map = {
        "Jan": 1,
        "Feb": 2,
        "Mar": 3,
        "Apr": 4,
        "May": 5,
        "Jun": 6,
        "Jul": 7,
        "Aug": 8,
        "Sep": 9,
        "Oct": 10,
        "Nov": 11,
        "Dec": 12
    }

    def __init__(self, display_obj=sys.stdout):
        self.log_data = []
        self.start = None
        self.end = None

        self._saved_time_periods = {}
        self._display_obj = display_obj

        self._setup_parser_do_set()
        self._setup_parser_do_topurls()
        self._setup_parser_do_toptalkers()
        self._setup_parser_do_url_hits_per_time()
        self._setup_parser_do_url_time_to_render()
        self._setup_parser_do_url_hits_per_ip()
        self._setup_parser_do_url_hits_per_ip_time_to_render()
        self._setup_parser_do_ip_hits_per_time()
        self._setup_parser_do_ip_time_to_render()
        self._setup_parser_do_ip_hits_per_url()
        self._setup_parser_do_ip_hits_per_url_time_to_render()

        self._hpu        = HitsPerUrl(self)
        self._hpi        = HitsPerIP(self)
        self._hpuput     = HitsPerUrlPerUnitTime(self)
        self._hpiput     = HitsPerIPPerUnitTime(self)
        self._hpubttrl   = HitsPerUrlByTimeToRenderLinear(self)
        self._hpibttrl   = HitsPerIPByTimeToRenderLinear(self)
        self._hpupi      = HitsPerUrlPerIP(self)
        self._hpipu      = HitsPerIPPerUrl(self)
        self._hpupibttrl = HitsPerUrlPerIPByTimeToRenderLinear(self)
        self._hpipubttrl = HitsPerIPPerUrlByTimeToRenderLinear(self)

    def cmd_loop(self):
        while True:
            try:
                line = raw_input("\rstart:%s, end:%s >> " % (self.start, self.end))
                if not line or line.lstrip().rstrip() == '':
                    continue

                self.do_cmd(line)

            except EOFError, e:
                print ""
                break

            except KeyboardInterrupt, e:
                print ""
                continue

            except OptParseError, e:
                print e

            except StandardError, e:
                traceback.print_exc()
                continue

    def do_cmd(self, line):
        components = shlex.split(line)
        cmd = components[0]
        args = components[1:]
        for method in [ x for x in dir(self) if x.startswith('_do_')]:
            method_for_cmd = "_do_%s" % cmd.lower()
            method_for_cmd = method_for_cmd.replace('-', '_')
            if method_for_cmd == method:
                getattr(self, method)(*args)
                break
        else:
            self._display_obj.write("Unknown Command: %s\n" % cmd)

    def parse_logfile(self, path):
        cmds = []
        if path.endswith(".gz"):
            cmds.append("gzip -dc %s" % path)
            cmds.append("grep 'request end'")
        elif path.endswith(".bz2"):
            cmds.append("bzip2 -dc %s" % path)
            cmds.append("grep 'request end'")
        elif path.endswith(".xz"):
            cmds.append("xz -dc %s" % path)
            cmds.append("grep 'request end'")
        else:
            cmds.append("grep 'request end' %s" % path)

        procs = []
        stdin = None
        for cmd in cmds:
            p = subprocess.Popen(shlex.split(cmd), stdin=stdin, stdout=subprocess.PIPE)
            stdin = p.stdout
            procs.append(p)

        for line in p.stdout:
            self._process_line(line)

        for p in procs:
            p.wait()

    def _process_line(self, line):
        line   = line[:-1]
        year   = int(line[8:12])
        month  = self.month_map[line[4:7]]
        day    = int(line[1:3])
        hour   = int(line[13:15])
        minute = int(line[16:18])
        second = int(line[19:21])
        datetimeobj = datetime(year, month, day, hour, minute, second)

        line = self._fixup_urls(line)
        line_elements = line.split(' ')
        url = line_elements[8]
        ip = line_elements[11]
        # sometimes ip records have a ',' after them
        if ip.endswith(','):
            ip = ip[:-1]
        ms = int(line_elements[9])

        # Record the data for later analysis
        self.log_data.append((datetimeobj, url, ms, ip))

        # Calculate the start of the time period for the logs we're dealing with
        if self.start:
            if datetimeobj < self.start:
                self.start = datetimeobj
        else:
            self.start = datetimeobj

        # Calculate the end of the time period for the logs we're dealing with
        if self.end:
            if datetimeobj > self.end:
                self.end = datetimeobj
        else:
            self.end = datetimeobj

    def _fixup_urls(self, line):
        line = re.sub('jQuery[0-9_]+', 'uqid=jQuery-SNIPPED', line)
        line = re.sub('&ts=\d+', '&ts=SNIPPED', line)
        line = re.sub('&_=\d+', '&_=SNIPPED', line)
        return line

    def _setup_parser_do_set(self):
        self._parser_do_set = NonExitingOptionParser(usage="set [start|end] YYYY-dd-mm:HH:MM:SS")

    def _setup_parser_do_topurls(self):
        self._parser_do_topurls = NonExitingOptionParser(usage="topurls [number of urls to display]")
        self._parser_do_topurls.add_option('-f', '--filter', action='store', type='str', dest='re_filter')
        self._parser_do_topurls.add_option('-r', '--rollup', action='store', type='str', dest='re_rollup')

    def _setup_parser_do_url_hits_per_time(self):
        self._parser_do_url_hits_per_time = NonExitingOptionParser(usage="""url-hits-per-time --step STEP --filter FILTER""")
        self._parser_do_url_hits_per_time.add_option('-s', '--step', action='store', type='int', dest='step')
        self._parser_do_url_hits_per_time.add_option('-f', '--filter', action='store', type='str', dest='re_filter')

    def _setup_parser_do_url_time_to_render(self):
        self._parser_do_url_time_to_render = NonExitingOptionParser(usage="""url-time-to-render --step STEP --filter FILTER""")
        self._parser_do_url_time_to_render.add_option('-s', '--step', action='store', type='int', dest='step')
        self._parser_do_url_time_to_render.add_option('-f', '--filter', action='store', type='str', dest='re_filter')

    def _setup_parser_do_url_hits_per_ip(self):
        self._parser_do_url_hits_per_ip = NonExitingOptionParser(usage="""url-hits-per-ip --filter FILTER""")
        self._parser_do_url_hits_per_ip.add_option('-f', '--filter', action='store', type='str', dest='re_filter')

    def _setup_parser_do_url_hits_per_ip_time_to_render(self):
        self._parser_do_url_hits_per_ip_time_to_render = NonExitingOptionParser(usage="""url-hits-per-ip-time-to-render --step STEP --filter FILTER""")
        self._parser_do_url_hits_per_ip_time_to_render.add_option('-s', '--step', action='store', type='int', dest='step')
        self._parser_do_url_hits_per_ip_time_to_render.add_option('-f', '--filter', action='store', type='str', dest='re_filter')

    def _setup_parser_do_toptalkers(self):
        self._parser_do_toptalkers = NonExitingOptionParser(usage="toptalkers [number of IPs to display]")
        self._parser_do_toptalkers.add_option('-f', '--filter', action='store', type='str', dest='re_filter')
        self._parser_do_toptalkers.add_option('-r', '--rollup', action='store', type='str', dest='re_rollup')

    def _setup_parser_do_ip_hits_per_time(self):
        self._parser_do_ip_hits_per_time = NonExitingOptionParser(usage="""ip-hits-per-time --step STEP --filter FILTER""")
        self._parser_do_ip_hits_per_time.add_option('-s', '--step', action='store', type='int', dest='step')
        self._parser_do_ip_hits_per_time.add_option('-f', '--filter', action='store', type='str', dest='re_filter')

    def _setup_parser_do_ip_time_to_render(self):
        self._parser_do_ip_time_to_render = NonExitingOptionParser(usage="""ip-time-to-render --step STEP --filter FILTER""")
        self._parser_do_ip_time_to_render.add_option('-s', '--step', action='store', type='int', dest='step')
        self._parser_do_ip_time_to_render.add_option('-f', '--filter', action='store', type='str', dest='re_filter')

    def _setup_parser_do_ip_hits_per_url(self):
        self._parser_do_ip_hits_per_url = NonExitingOptionParser(usage="""ip-hits-per-url --filter FILTER""")
        self._parser_do_ip_hits_per_url.add_option('-f', '--filter', action='store', type='str', dest='re_filter')

    def _setup_parser_do_ip_hits_per_url_time_to_render(self):
        self._parser_do_ip_hits_per_url_time_to_render = NonExitingOptionParser(usage="""ip-hits-per-url-time-to-render --step STEP --filter FILTER""")
        self._parser_do_ip_hits_per_url_time_to_render.add_option('-s', '--step', action='store', type='int', dest='step')
        self._parser_do_ip_hits_per_url_time_to_render.add_option('-f', '--filter', action='store', type='str', dest='re_filter')

    def _do_set(self, *cmd_args):
        options, args = self._parser_do_set.parse_args(list(cmd_args))
        if len(args) != 2:
            raise OptionValueError("Wrong number of arguments for set command")
        what = args[0]
        method_for_what = "_do_set_%s" % what
        if method_for_what not in [ x for x in dir(self) if x.startswith("_do_set") ]:
            raise OptionValueError("Unsupported argument to 'set' command: %s" % what)
        getattr(self, method_for_what)(*args[1:])

    def _do_set_start(self, datetime_string):
        # TODO: Factor out common
        if not re.match('\d{4}-\d{2}-\d{2}:\d{2}:\d{2}:\d{2}', datetime_string):
            raise OptionValueError("Datetime must be specified as YYYY-dd-mm:HH:MM:SS")
        setattr(self, 'start', datetime(*[int(x) for x in re.split('[-:]', datetime_string)]))

    def _do_set_end(self, datetime_string):
        # TODO: Factor out common
        if not re.match('\d{4}-\d{2}-\d{2}:\d{2}:\d{2}:\d{2}', datetime_string):
            raise OptionValueError("Datetime must be specified as YYYY-dd-mm:HH:MM:SS")
        setattr(self, 'end', datetime(*[int(x) for x in re.split('[-:]', datetime_string)]))

    def _do_set_tp(self, name):
        # convenience func
        self._do_set_timeperiod(name)
    
    def _do_set_timeperiod(self, name):
        self._saved_time_periods[name] = (self.start, self.end)

    def _do_tp(self, name=None):
        # convenience func
        self._do_timeperiod(name)

    def _do_timeperiod(self, name=None):
        if name:        
            tp = self._saved_time_periods.get(name)
            if tp:
                self.start, self.end = tp
            else:
                print "No such time period has been previously saved: %s" % name
        else:
            for time_period_name in sorted(self._saved_time_periods):
                start, end = self._saved_time_periods[time_period_name]
                print "%s: %s - %s" % (time_period_name, start, end)

    def _do_single_optional_numerical_positional_arg_check(self, cmd, args, default):
        if len(args) == 0:
            return default
        if len(args) != 1:
            raise OptionValueError("First and only argument to '%s' must be a number" % cmd)
        num = args[0]
        if not re.match('\d+', num):
            raise OptionValueError("First and only argument to '%s' must be a number" % cmd)
        return int(num)

    def _do_topurls(self, *cmd_args):
        options, args = self._parser_do_topurls.parse_args(list(cmd_args))
        num_urls = self._do_single_optional_numerical_positional_arg_check('topurls', args, 10)

        self._hpu(start=self.start, end=self.end, re_filter=options.re_filter,
                  re_rollup=options.re_rollup)
        self._hpu.display(self._display_obj, num_urls)

    def _do_toptalkers(self, *cmd_args):
        options, args = self._parser_do_toptalkers.parse_args(list(cmd_args))
        num_ips = self._do_single_optional_numerical_positional_arg_check('toptalkers', args, 10)

        self._hpi(start=self.start, end=self.end, re_filter=options.re_filter,
                  re_rollup=options.re_rollup)
        self._hpi.display(self._display_obj, num_ips)

    def _do_url_hits_per_time(self, *cmd_args):
        options, args = self._parser_do_url_hits_per_time.parse_args(list(cmd_args))
        if not options.step:
            step = 3600
        else:
            step = options.step
        
        self._hpuput(start=self.start, end=self.end, step=step, re_filter=options.re_filter)
        self._hpuput.display(self._display_obj)

    def _do_ip_hits_per_time(self, *cmd_args):
        options, args = self._parser_do_ip_hits_per_time.parse_args(list(cmd_args))
        if not options.step:
            step = 3600
        else:
            step = options.step

        self._hpiput(start=self.start, end=self.end, step=step, re_filter=options.re_filter)
        self._hpiput.display(self._display_obj)

    def _do_url_time_to_render(self, *cmd_args):
        options, args = self._parser_do_url_time_to_render.parse_args(list(cmd_args))
        if not options.step:
            step = 500
        else:
            step = options.step

        self._hpubttrl(start=self.start, end=self.end, ms_step=step, re_filter=options.re_filter)
        self._hpubttrl.display(self._display_obj)

    def _do_ip_time_to_render(self, *cmd_args):
        options, args = self._parser_do_ip_time_to_render.parse_args(list(cmd_args))
        if not options.step:
            step = 500
        else:
            step = options.step

        self._hpibttrl(start=self.start, end=self.end, ms_step=step, re_filter=options.re_filter)
        self._hpibttrl.display(self._display_obj)

    def _do_url_hits_per_ip(self, *cmd_args):
        options, args = self._parser_do_url_hits_per_ip.parse_args(list(cmd_args))
        self._hpupi(start=self.start, end=self.end, re_filter=options.re_filter)
        self._hpupi.display(self._display_obj)

    def _do_ip_hits_per_url(self, *cmd_args):
        options, args = self._parser_do_ip_hits_per_url.parse_args(list(cmd_args))
        self._hpipu(start=self.start, end=self.end, re_filter=options.re_filter)
        self._hpipu.display(self._display_obj)

    def _do_url_hits_per_ip_time_to_render(self, *cmd_args):
        options, args = self._parser_do_url_hits_per_ip_time_to_render.parse_args(list(cmd_args))
        if not options.step:
            step = 500
        else:
            step = options.step
        self._hpupibttrl(start=self.start, end=self.end, ms_step=step, re_filter=options.re_filter)
        self._hpupibttrl.display(self._display_obj)

    def _do_ip_hits_per_url_time_to_render(self, *cmd_args):
        options, args = self._parser_do_ip_hits_per_url_time_to_render.parse_args(list(cmd_args))
        if not options.step:
            step = 500
        else:
            step = options.step
        self._hpipubttrl(start=self.start, end=self.end, ms_step=step, re_filter=options.re_filter)
        self._hpipubttrl.display(self._display_obj)

def main():
    log_analyzer = LogAnalyzer()
    for path in sys.argv[1:]:
        print "Parsing log file: %s  " % os.path.basename(path),
        start = datetime.now()
        log_analyzer.parse_logfile(path)    
        end = datetime.now()
        print "DONE (%s)" % (end - start)
    log_analyzer.cmd_loop()

if __name__ == "__main__":
#   import cProfile
#   cProfile.run('main()')
    main()