All pastes #1416671 Raw Edit

ottd log analyser

public text v1 · immutable
#1416671 ·published 2009-05-08 18:45 UTC
rendered paste body
__LICENSE__ = """
Copyright (c) 2009, Leo 'hylje' Honkanen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of hylje's log analyzer nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Leo Honkanen ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Leo Honkanen BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import datetime

# --- globals

# how long a single command is active (in ottd days)
EXPIRY_TIME = datetime.timedelta(60)
# how many active commands count as playing
THRESHOLD = 1

EVENT_TYPES = READ_NEXT_COMMAND, EXPIRE_CREDIT = "read_next", "expire"

# The alternative to global LOGFILE would be passing it down many unrelated
# function contexts.
LOGFILE = None

class EverythingDone(Exception): pass

class BlastFromThePast(Exception): pass

GAMETIME_NOW = None

# --- primary event loop procedures

import heapq

next_events = []

def new_event(time, evtype, ident):
    heapq.heappush(next_events, (time, evtype, ident))

# ---

import sys

def loop():
    # TODO tell the clueless user what just happened should he forget
    # the filename argument (now just ugly traceback)
    global LOGFILE
    LOGFILE = file(sys.argv[1])

    # kick it off
    timestamp = next_command_events()

    # shouldn't need to give GAMETIME_NOW a real value yet, first credit
    # changes are in the loop
    
    # fast forward the scene

    while next_events and next_events[0][0] >= timestamp:
        timestamp, evtype, ident = heapq.heappop(next_events)

        global GAMETIME_NOW
        GAMETIME_NOW = timestamp
        
        if evtype == READ_NEXT_COMMAND:
            try:
                do_read_next_command(ident)
            except EverythingDone:
                # only expiring credit should follow now
                # we might as well break, but for now everything
                # gets processed
                continue
            except BlastFromThePast:
                print ("The logfile given is not linear. Sort it, "
                       "here's a sample command for GNU coreutils sort: ")
                print ("`sort -k 1.55,1.59n -k 1.60,1.62n "
                       "-k 1.63,1.65n FILE > TARGETFILE`")
                print "---"
                
        elif evtype == EXPIRE_CREDIT:
            expire_credit(ident)
    if next_events:
        print "Not everything was handled!"

    # collect the spoils
    print ("Active time spent by nickname "
           "(in seconds, active=%s commands "
           "in last %s game days):") % (THRESHOLD, EXPIRY_TIME.days) 
    for nick, time_spent in playtime_totals.iteritems():
        print "%s: %s" % (nick, time_spent)
    print "End date is %s" % GAMETIME_NOW
    
# --- boilerplate magic

def do_read_next_command(nick):
    add_credit(nick)
    next_command_events()
    
def next_command_events():
    next_wake, nick = find_next_command()
    
    new_event(next_wake, READ_NEXT_COMMAND, nick)
    new_event(next_wake + EXPIRY_TIME, EXPIRE_CREDIT, nick)

    return next_wake

def find_next_command():
    # TODO read lines from LOGFILE, find the next relevant command
    # and return next time to wake and the nickname relevant to it
    # if there's no such thing, raise EverythingDone
    while True:
        line = LOGFILE.readline()
        if not line:
            raise EverythingDone()
        
        info = parse_log_line(line)
              
        if info:
            if GAMETIME_NOW and not info["date"] >= GAMETIME_NOW:
                raise BlastFromThePast()
        
            return info["date"], info["nick"]

def ottd_date(date):
    return datetime.date(*[int(i) for i in date.split("-")])

def parse_log_line(line):
    cmd_name = line[0:30].strip()

    if not cmd_name.startswith("Cmd"):
        # garbage line
        return None
    
    nickname = line[31:48].strip()

    # work around variable-length text field which may have spaces
    text_index = line.find("text:")
    price_index = line.rfind("price:")

    other_fields = line[49:text_index]
    text = line[text_index:price_index].strip().lstrip("text:")
    price = line[price_index:].lstrip("price:")

    line_info = dict(entry.split(":") for entry in other_fields.split())
    line_info.update({
        "cmd": cmd_name,
        "nick": nickname,
        "text": text,
        "price": price,
    })
    line_info["date"] = ottd_date(line_info["date"])

    return line_info        
    

# --- Data structures (e.g. the info we want)

import collections

credit_pool = collections.defaultdict(list)

def add_credit(nickname):
    credit_pool[nickname].append(1)
    check_credits(nickname)

def expire_credit(nickname):
    credit_pool[nickname].pop(0)
    check_credits(nickname)

def check_credits(nickname):
    credits_ = credit_pool[nickname]
    if (len(credits_) >= THRESHOLD
        and not active_playtime(nickname)):
        start_playtime(nickname)
    elif (len(credits_) < THRESHOLD
          and active_playtime(nickname)):
        stop_playtime(nickname)

# --- this is important
        
playtime_started = {}
playtime_totals = collections.defaultdict(int)

def start_playtime(nickname):
    playtime_started[nickname] = GAMETIME_NOW

def active_playtime(nickname):
    return nickname in playtime_started

def stop_playtime(nickname):
    days_spent = (GAMETIME_NOW - playtime_started[nickname]).days
    playtime_totals[nickname] += days_spent
    del playtime_started[nickname]

# --- 

if __name__ == "__main__":
    loop()