#!/usr/bin/python

import sys
import os
import re
import urlparse
import gzip
import datetime

"""
We look for four kinds of download in the NITRC access logs:

    Using the downloader (Java app)

        GET /ir/applet/file-downloader-1.4h.jar

        followed by

        GET /ir/data/experiments/xnat_E02577/scans/anat/resources/NIfTI/files?format=zip&projectIncludedInPath=true&subjectIncludedInPath=true

    From the "download" link on a session

        GET /ir/REST/experiments/xnat_E02633/resources/15975,16153,15976/files?format=zip

    From the "manage files" link on a session (no breakdown, but byte count)

        POST /ir/app/action/DownloadImages/template/ClosePage.vm

This script does not look for direct REST downloads.

"""

download_re = re.compile('/resources/([0-9,]+)/files')

# ignore logs before this date
log_cutoff = datetime.datetime(2011, 8, 1)

log_line_re = re.compile(r"""^
                             (?P<host>[^\s]+)
                             \s
                             (?P<ident>[^\s]+)
                             \s
                             (?P<user>[^\[]+)
                             \s
                             \[(?P<time>../.../....:..:..:..\s.\d{4})\]
                             \s
                             "(?P<request>|.*[^\\])"
                             \s
                             (?P<status>[^\s]+)
                             \s
                             (?P<bytes_sent>[^\s]+)
                             \s
                             "(?P<referer>|.*[^\\])"
                             \s
                             "(?P<user_agent>|.*[^\\])"
                             $""", re.VERBOSE)

months = {'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 read_log(fname, files, bytes):
    if fname.endswith('.gz'):
        fo = gzip.GzipFile(fname)
    else:
        fo = open(fname)
    first_line_flag = True
    for (line_no, line) in enumerate(fo):
        line_no += 1
        mo = log_line_re.search(line)
        if not mo:
            # bad (or misunderstood) log line -- ignore
            continue
        hit = mo.groupdict()
        t = parse_httpd_log_time(hit['time'])
        if first_line_flag:
            if t < log_cutoff:
                print '    too old; skipping'
                return
            first_line_flag = False
        year_month = t.strftime('%Y-%m')
        files.setdefault(year_month, 0)
        bytes.setdefault(year_month, 0)
        try:
            (method, request, http_version) = hit['request'].split()
        except ValueError:
            # ignore ill-formed requests or requests with extra spaces 
            # (likely not IR hits anyway)
            continue
        if 'subjectIncludedInPath' in request:
            files[year_month] += 1
            if hit['bytes_sent'] == '-':
                bytes[year_month] += 0
            else:
                bytes[year_month] += int(hit['bytes_sent'])
        elif download_re.search(request):


            vars = parse_qs(urlparse.urlparse(request)[4])
            if 'format' in vars:
                if vars['format'][0] not in ('csv', 'json'):
                    resource_ids = download_re.search(hit['request']).groups()[0]
                    files[year_month] += len(resource_ids.split(','))
                    if hit['bytes_sent'] == '-':
                        pass
                    else:
                        bytes[year_month] += int(hit['bytes_sent'])
        elif hit['request'].startswith('POST /ir/app/action/DownloadImages/template/ClosePage.vm '):
            files[year_month] += 1
            if hit['bytes_sent'] != '-':
                bytes[year_month] += int(hit['bytes_sent'])
    fo.close()
    return

def parse_qs(qs):
    d = {}
    for pair in qs.split('&'):
        try:
            (name, value) = pair.split('=')
        except ValueError:
            continue
        d.setdefault(name, []).append(value)
    return d

def parse_httpd_log_time(s):
    day = int(s[0:2])
    month = months[s[3:6]]
    year = int(s[7:11])
    hour = int(s[12:14])
    minute = int(s[15:17])
    second = int(s[18:20])
    return datetime.datetime(year, month, day, hour, minute, second)

progname = os.path.basename(sys.argv[0])

if len(sys.argv) < 2:
    print
    print 'usage: %s <access log> [...]' % progname
    print '       %s <path to access logs>' % progname
    print
    print 'Counts the number and size of IR downlaods given access logs '
    print 'or a directory containing access logs.  Access logs may be left '
    print 'gzipped.'
    print
    print 'The report is broken down by month.'
    print
    sys.exit(2)

# each is indexed by 'YYYY-MM'
files = {}
bytes = {}

for path in sys.argv[1:]:
    if os.path.isdir(path):
        for fname in os.listdir(path):
            full_fname = '%s/%s' % (path, fname)
            if not os.path.isfile(full_fname):
                print 'skipping %s (not a regular file)' % full_fname
                continue
            print 'reading %s' % full_fname
            read_log(full_fname, files, bytes)
    else:
        print 'reading %s' % path
        read_log(path, files, bytes)

months = files.keys()
months.sort()

for month in months:
    mb = bytes[month] / 1024.0 / 1024.0
    print '%s %6d %8.f' % (month, files[month], mb)

sys.exit(0)

# eof
