#!/usr/bin/env python2.6

"""
Author: Joshua Holmes <jholmes@hostgator.com>
"""

import os
import sys
if os.name != 'posix':
    sys.exit('platform not supported')
import time
import curses
import atexit
from datetime import datetime, timedelta
import psutil
import multiprocessing
import socket
import sqlite3
import fcntl
import termios
import struct
from optparse import OptionParser


SQLITE_DATABASE_FILE = "/dev/shm/PHPSUM_SQLITE.db"


def parse_options():
    usage = """
    usage: %prog [options] --display=\"<initial display style>\"
    hotkeys: 
        '/' - switches views
        'q' or 'Q' quits
    """
    version = "PHPTop 0.2 by Joshua Holmes <jholmes@hostgator.com>"
    description = """ """
    parser = OptionParser( usage=usage, version=version, description=description)
    parser.set_defaults(verbose=0)
    parser.add_option("-d", "--display",
                        action="store", dest="displayState", default='min',
                        help="initial display style: w=wide, m=min")
    (options, args) = parser.parse_args()
    return options, args



def getAllAccountsandOwners():
    AccountDict = dict()
    file = open("/etc/trueuserowners")
    while 1:
        lines = file.readlines()
        if not lines: break
        for line in lines[1:]:
            user, owner = line.split(":")
            AccountDict[user] = owner.strip()
    return AccountDict


def ProcPollHandler():
    sqlite_connection = sqlite3.connect(
                                SQLITE_DATABASE_FILE, 
                                isolation_level=None, 
                                check_same_thread = False
                                )
    sqlite_cursor = sqlite_connection.cursor()
    try:
        sqlite_cursor.execute("drop table process_data")
    except:
        pass
    sqlite_cursor.execute(
        """create table process_data ( 
                pid int primary key, 
                file varchar, 
                username varchar, 
                first_seen real, 
                last_seen real, 
                cpu_user real, 
                cpu_system real, 
                mem_user real, 
                mem_system real 
                )
        """)
    while True:
        try:
            for proc in psutil.process_iter():
                try:
                    if 'php' == proc.name or 'php-cgi' == proc.name and len(proc.cmdline) == 2: 
                        try:
                            cpu_user, cpu_system = list(proc.get_cpu_times())
                            mem_user, mem_system = list(proc.get_memory_info())
                            sqlite_cursor.execute(
                                """INSERT INTO process_data VALUES (?,?,?,?,?,?,?,?,?)""", 
                                (
                                    proc.pid, 
                                    proc.cmdline[1], 
                                    proc.username, 
                                    proc.create_time, 
                                    proc.create_time, 
                                    cpu_user, 
                                    cpu_system,
                                    mem_user, 
                                    mem_system
                                )
                            )
                        except ( sqlite3.IntegrityError, IndexError ):
                            sqlite_cursor.execute(
                                """UPDATE process_data SET last_seen=?, cpu_user=?, cpu_system=?, mem_user=?, mem_system=? WHERE pid=?""",
                                (
                                    time.time(), 
                                    cpu_user, 
                                    cpu_system,
                                    mem_user, 
                                    mem_system,
                                    proc.pid 
                                )
                            )
                except ( psutil.Error, IOError ):
                    continue
            time.sleep(0.05)
        except KeyboardInterrupt:
            sys.exit()


def bytes2human(n):
    """
    >>> bytes2human(10000)
    '9K'
    >>> bytes2human(100001221)
    '95M'
    """
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i+1)*10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = int(float(n) / prefix[s])
            return '%s%s' % (value, s)
    return "%sB" % n



class DisplayHandler():
    def __init__(self):
        if str(options.displayState).lower() in ['w', 'wide']:
            self.state = 2
        elif str(options.displayState).lower() in ['m', 'min']:
            self.state = 1
        self.startTime = datetime.now()
        self.interval = 2
        self.AccountDict = getAllAccountsandOwners()
        self.win = curses.initscr()
        atexit.register(tear_down)
        curses.endwin()
        self.sqlite_connection_reader = sqlite3.connect(
                                                SQLITE_DATABASE_FILE, 
                                                check_same_thread = False
                                                )
        self.sqlite_cursor_read = self.sqlite_connection_reader.cursor()

    def run(self):
        try:
            while 1:
                self.displayStore = str()
                self.windowHeight = self.win.getmaxyx()[0]
                self.lineno = 0
                if self.state == 1: self.DisplayMinHandler()
                if self.state == 2: self.DisplayMaxHandler()
                self.getInput()
        except (KeyboardInterrupt, SystemExit):
            self.win.keypad(0)
            try:
                os.remove(SQLITE_DATABASE_FILE)
            except:
                pass
            global lastDisplayScreen
            lastDisplayScreen = self.displayStore
            ProcPollThread.terminate()
            ProcPollThread.join()
            pass

    def getInput(self):
        loopStart = datetime.now()
        self.win.nodelay(1)
        while (datetime.now() - loopStart).seconds < self.interval:
            time.sleep(0.5)
            c = self.win.getch()
            if c == ord('q') or c == ord('Q'): 
                raise SystemExit
            if c == ord('/'): 
                c = None
                if self.state == 1:
                    self.state = 2
                else:
                    self.state = 1
                break

    def print_line(self, line):
        try:
            self.win.addstr(self.lineno, 0, line, 0)
            self.displayStore += line + "\n"
        except curses.error:
            self.lineno = 0
            self.win.refresh()
            raise
        else:
            self.lineno += 1

    def DisplayMaxHandler(self):
        SQL_TOP_USERS = """SELECT SUM(cpu_user+cpu_system) AS SUM_CPU_USE, COUNT(pid) AS CNT, username FROM process_data GROUP BY username ORDER BY SUM_CPU_USE DESC LIMIT %d""" % self.windowHeight
        SQL_TOP_FILES = """SELECT SUM(cpu_user+cpu_system) AS SUM_CPU_USE, SUM(cpu_user) AS SUM_CPU_USER, SUM(cpu_system) AS SUM_CPU_SYSTEM ,SUM(mem_user+mem_system) AS SUM_MEM_USE, COUNT(pid) AS CNT, SUM(cpu_user+cpu_system)/COUNT(pid) AS AVG_CPU,  SUM(mem_user+mem_system)/COUNT(pid) AS AVG_MEM, file FROM process_data GROUP BY file ORDER BY SUM_CPU_USE DESC LIMIT %d""" % self.windowHeight
        tmp_body = "|\||/| %12.2f | %12.2f | %12.2f | %12s | %10d | %12.2f | %12s | %-80s "
        tmp_body_user = "| %12.2f | %12d | %10s | %10s "
        self.sqlite_cursor_read.execute(SQL_TOP_FILES)
        TOP_FILES = self.sqlite_cursor_read.fetchall()
        self.sqlite_cursor_read.execute(SQL_TOP_USERS)
        TOP_USERS = self.sqlite_cursor_read.fetchall()
        self.win.erase()
        self.print_line( "="*200 )
        self.print_line( "| %12s| %12s | %10s | %10s |\||/| %12s | %12s | %12s | %12s | %10s | %12s | %12s | %-80s " % ( "SUM CPU(sec) ","COUNT", "USER","OWNER","SUM CPU(sec)", "SUM CPU USER", "SUM CPU SYS","SUM MEM", "COUNT", "AVG CPU", "AVG MEM", "FILENAME" ) )
        self.print_line( "-"*200 )
        for i in range(self.windowHeight - 6):
            line = str()
            try:
                line += tmp_body_user % ( float(TOP_USERS[i][0]), int(TOP_USERS[i][1]), str(TOP_USERS[i][2]), self.AccountDict[str(TOP_USERS[i][2])] )
            except ( KeyError, IndexError ) as e:
                line += "| %12s | %12s | %10s | %10s " % ( "","","", "")
            try:
                line += tmp_body % ( float(TOP_FILES[i][0]), float(TOP_FILES[i][1]), float(TOP_FILES[i][2]), bytes2human(int(TOP_FILES[i][3])), int(TOP_FILES[i][4]), float(TOP_FILES[i][5]), bytes2human(int(TOP_FILES[i][6])), str(TOP_FILES[i][7])  )
            except ( KeyError, IndexError ) as e:
                line += "|\||/| %12s | %12s | %12s | %12s | %10s | %12s | %12s | %-80s " % ( "","","","","","","","")
            try:
                self.print_line( line )
            except curses.error:
                break
        self.print_line( "="*200 )
        self.print_line("START TIME: %s\tCURRENT TIME: %s\tRUN TIME: %d seconds\tROW COUNT: %d" % ( self.startTime, datetime.now(), (datetime.now() - self.startTime).seconds , self.windowHeight) )
        curses.endwin()
        self.win.refresh()

    def DisplayMinHandler(self):
        SQL_TOP_USERS = """SELECT SUM(cpu_user+cpu_system) AS SUM_CPU_USE, COUNT(pid) AS CNT, username FROM process_data GROUP BY username ORDER BY SUM_CPU_USE DESC LIMIT %d""" % self.windowHeight
        ROW_COUNT = 50 
        tmp_body_user = "| %12.2f | %12d | %10s | %10s |"
        self.sqlite_cursor_read.execute(SQL_TOP_USERS)
        TOP_USERS = self.sqlite_cursor_read.fetchall()
        self.win.erase()
        self.print_line( "="*60 )
        self.print_line( "| %12s| %12s | %10s | %10s |" % ( "SUM CPU(sec) ","COUNT", "USER","OWNER" ) )
        self.print_line( "-"*60 )
        for i in range(self.windowHeight - 6 ):
            line = str()
            try:
                line += tmp_body_user % ( float(TOP_USERS[i][0]), int(TOP_USERS[i][1]), str(TOP_USERS[i][2]), self.AccountDict[str(TOP_USERS[i][2])] )
            except ( KeyError, IndexError) as e:
                line += "| %12s | %12s | %10s | %10s |" % ( "","","", "")
            try:
                self.print_line( line )
            except curses.error:
                break
        self.print_line( "="*60 )
        self.print_line("START TIME: %s\tCURRENT TIME: %s\tRUN TIME: %d seconds\tROW COUNT: %d" % ( self.startTime, datetime.now(), (datetime.now() - self.startTime).seconds , self.windowHeight) )
        curses.endwin()
        self.win.refresh()



lastDisplayScreen = str()

def tear_down():
    curses.nocbreak()
    curses.echo()
    curses.endwin()
    print lastDisplayScreen

if __name__ == '__main__':
    options, parser = parse_options()
    ProcPollThread = multiprocessing.Process(target=ProcPollHandler)
    ProcPollThread.start()
    # Sleep for split second to load polling thread and initial data set.
    time.sleep(0.5)
    display = DisplayHandler()
    display.run()

