#!/usr/bin/python

from optparse import OptionParser
import getpass
import subprocess
import sys
import datetime
import time

desc = '''This program simply collects runtime statistics from mysql at a set interval and records them to a log file.  The VARIABLES arguments provided after any options are simply prefixes of any runtime variables that should be recorded.  If no VARIABLES arguments are provided, all provided runtime variables will be recorded.'''
parser = OptionParser(description=desc, usage='%prog [options] [VARIABLES...]')
CMD_DEFAULT = 'mysqladmin.lnk'
parser.add_option('-s', '--server', dest='server', help='the database server host', default='localhost')
parser.add_option('-u', '--user', dest='user', default=getpass.getuser(), help='the database user to connect with')
parser.add_option('-p', '--passwd', dest='passwd', help='the database password to connect with')
parser.add_option('-i', '--interval', dest='interval', default=10, help='the number of seconds to wait between statistics collection events')
parser.add_option('-c', '--command', dest='command', default=CMD_DEFAULT, help='the command line command used to run mysqladmin')
parser.add_option('-f', '--filename', dest='filename', default='mysqlstats.log', help='the filename to write the mysql statistics to')

options, args = parser.parse_args()

if not args:
    args = ['']

cmdOptions = '-u "%s" -h "%s" ' % (options.user, options.server)
if options.passwd is not None:
    cmdOptions += '--password="%s"' % options.passwd
fullCmd = '%s %s ' % (options.command, cmdOptions)

def parseOutput(statusOutput, threadsOutput):
    output = [ '# mysqlmonitor output ' + str(datetime.datetime.today())]
    for line in statusOutput.splitlines()[3:-1]:
        varName = line.split()[1].strip()
        value = line[line.find('|', 1) + 1:-1]
        valid = False
        for prefix in args:
            if varName.lower().startswith(prefix.strip().lower()):
                valid = True
        if valid:
            output.append('%s\t%s' % (varName, value))
    output.append('\n# process list\n' + threadsOutput)
    return '\n'.join(output)


header = ['# mysqlmonitor log started ' + str(datetime.datetime.today())]
header.append('# host ' + options.server)
header.append('# dbuser ' + options.user)
header = '\n'.join(header) + '\n'
file(options.filename, 'w').write(header)

while True:
    popen =  subprocess.Popen(fullCmd + 'extended', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if popen.wait() != 0:
        sys.exit('ERROR: Was unable to connect to mysql server with given settings.  Error message was:\n\n%s' % popen.stderr.read())
    output1 = popen.stdout.read()

    popen =  subprocess.Popen(fullCmd + 'processlist', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if popen.wait() != 0:
        sys.exit('ERROR: Was unable to connect to mysql server with given settings.  Error message was:\n\n%s' % popen.stderr.read())
    output2 = popen.stdout.read()


    newOutput = parseOutput(output1, output2)
    f = file(options.filename)
    curText = f.read()
    f.close()
    file(options.filename, 'w').write(curText + '\n' + newOutput)
    time.sleep(float(options.interval))



