#!/usr/bin/env python3
#-*- coding: UTF-8 -*-

import argparse
from collections import Counter
from mysql import connector


def all_connections(args):
    """返回当前数据库实例中所有的连接
    """
    c = Counter()
    cnx = None
    try:
        cnx = connector.connect(host=args.host,port=args.port,user=args.user,password=args.password)
        cursor = cnx.cursor()
        cursor.execute("select user,host,state from information_schema.processlist;")
        for user,host,state in cursor.fetchall():
            if ':' in host:
                host,_ = host.split(':')
            c.update({host:1})
    except Exception as e:
        print(e)
        exit()
    finally:
        if cnx != None:
            cnx.close()

    #格式化输出
    print("{0:<32} {1}".format("client_host_ip".upper(),"counter".upper()))
    print("-"*48)
    for host_ip,counter in c.most_common(args.top):
        print("{0:<32} {1}".format(host_ip,counter))   

def active_connections(args):
    """返回当前实例中所有的非sleep状态的连接
    """
    c = Counter()
    cnx = None
    try:
        cnx = connector.connect(host=args.host,port=args.port,user=args.user,password=args.password)
        cursor = cnx.cursor()
        cursor.execute("select user,host,state from information_schema.processlist;")
        for user,host,state in cursor.fetchall():
            if ':' in host:
                host,_ = host.split(':')
            if 'sleep' not in state.lower() and state != '':
                c.update({host:1})
    except Exception as e:
        print(e)
        exit()
    finally:
        if cnx != None:
            cnx.close()

    #格式化输出
    print("{0:<32} {1}".format("client_host_ip".upper(),"counter".upper()))
    print("-"*48)
    for host_ip,counter in c.most_common(args.top):
        print("{0:<32} {1}".format(host_ip,counter))   

def all_user(args):
    """与all_connection类似，不同的是以user为维度进行聚合
    """
    c = Counter()
    cnx = None
    try:
        cnx = connector.connect(host=args.host,port=args.port,user=args.user,password=args.password)
        cursor = cnx.cursor()
        cursor.execute("select user,host,state from information_schema.processlist;")
        for user,host,state in cursor.fetchall():
            c.update({user:1})
    except Exception as e:
        print(e)
        exit()
    finally:
        if cnx != None:
            cnx.close()

    #格式化输出
    print("{0:<32} {1}".format("client_host_ip".upper(),"counter".upper()))
    print("-"*48)
    for host_ip,counter in c.most_common(args.top):
        print("{0:<32} {1}".format(host_ip,counter))   

def active_user(args):
    """以活跃用户为维度为当前连接进行聚合
    """
    c = Counter()
    cnx = None
    try:
        cnx = connector.connect(host=args.host,port=args.port,user=args.user,password=args.password)
        cursor = cnx.cursor()
        cursor.execute("select user,host,state from information_schema.processlist;")
        for user,host,state in cursor.fetchall():
            if 'sleep' not in state.lower() and state != '':
                c.update({user:1})
    except Exception as e:
        print(e)
        exit()
    finally:
        if cnx != None:
            cnx.close()

    #格式化输出
    print("{0:<32} {1}".format("client_host_ip".upper(),"counter".upper()))
    print("-"*48)
    for host_ip,counter in c.most_common(args.top):
        print("{0:<32} {1}".format(host_ip,counter))       

operations = {
    'all_conn':all_connections,
    'active_conn':active_connections,
    'all_user':all_user,
    'active_user':active_user,
}

if __name__ == "__main__":
    parser=argparse.ArgumentParser()
    parser.add_argument('--host',help='Connect to host',default='127.0.0.1')
    parser.add_argument('--port',help='Port number to use for connection',default=3306,type=int)
    parser.add_argument('--user',help='User for login if not current user',default='root')
    parser.add_argument('--password',default='Password to use when connecting to server')
    parser.add_argument('--top',default=7,type=int)
    parser.add_argument('operation',choices=operations.keys())
    args=parser.parse_args()
    operations[args.operation](args)