#!/bin/env python
#-*-coding:utf-8-*-

import MySQLdb
import string
import time  
import datetime
import os
import re
import json
import sys 
reload(sys) 
sys.setdefaultencoding('utf8')
import ConfigParser
import smtplib
from email.mime.text import MIMEText
from email.message import Message
from email.header import Header
from pymongo import MongoClient
import dba_crypto as crypt
basePath = "/usr/local/camelbell"
fCnf = "%s/etc/config.ini" % (basePath)

def get_item(data_dict,item,default='-1'):
    if data_dict.has_key(item):
	return data_dict[item]
    else:
	return default

def get_config(group,config_name,default='-1'):
    config = ConfigParser.ConfigParser()
    config.readfp(open(fCnf,'rw'))
    if config.has_option(group,config_name):
	config_value=config.get(group,config_name).strip(' ').strip('\'').strip('\"')
    else:
	config_value=default
    return config_value

def get_option(key):
    conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8')
    conn.select_db(dbname)
    cursor = conn.cursor()
    sql="select value from options where name='%s'" % (key)
    count=cursor.execute(sql)
    if count == 0 :
        result=0
    else:
        result=(cursor.fetchone())[0]
    cursor.close()
    conn.close()
    return result

def filters(data):
    return data.strip(' ').strip('\n').strip('\br')

server_key = 'monitor_server'
host = get_config(server_key,'host')
port = get_config(server_key,'port')
user = get_config(server_key,'user')
passwd = get_config(server_key,'passwd')
dbname = get_config(server_key,'dbname')

server_mongodb_key = 'monitor_server_mongodb'
mongodb_host = get_config(server_mongodb_key,'host')
mongodb_port = get_config(server_mongodb_key,'port')
mongodb_user = get_config(server_mongodb_key,'user')
mongodb_passwd = get_config(server_mongodb_key,'passwd')
mongodb_dbname = get_config(server_mongodb_key,'dbname')
mongodb_replicaSet = get_config(server_mongodb_key,'replicaSet')

'''
# collection 函数文档
http://api.mongodb.com/python/current/api/pymongo/collection.html?_ga=1.219309790.610772200.1468379950#pymongo.collection.Collection.find
'''

def mongodb_save(tb_name, params):
   inpParams = params
   inpParams.pop("id", None)
   connect_mongodb = None
   try:
        connect_mongodb = MongoClient(host=mongodb_host,port=int(mongodb_port),replicaSet=mongodb_replicaSet)
        db = connect_mongodb.get_database(mongodb_dbname)
        db.authenticate(mongodb_user, mongodb_passwd, mechanism='SCRAM-SHA-1')
	tb = db[tb_name]
	tb.insert_one(inpParams)
	#print tb.find_one()
	#print tb.find_one(sort=[("create_time",-1)])
	print tb.count()
	'''
	tlines = tb.find(limit=10).sort([("create_time",-1)])
	for tline in tlines:
	    print tline
	'''
   except Exception, e:
        logger_msg="insert alarm to mongodb %s:%s/%s,%s/%s : %s" %(mongodb_host,mongodb_port,mongodb_dbname,mongodb_user,mongodb_passwd,e)
        print logger_msg
   finally:
	if connect_mongodb != None:
	    connect_mongodb.close()

def other_save(tb_name, params):
    mongodb_save(tb_name, params)

def mysql_exec_many(sqls,params=None):
    try:
    	conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8')
    	conn.select_db(dbname)
    	curs = conn.cursor()
	curs.execute("set session sql_mode=''")
	for i in range(0,len(sqls)):
	    sql = sqls[i]
	    if params != None and params[i] <> '':
		curs.execute(sql,params[i])
	    else:
		curs.execute(sql)
        curs.close()
        conn.commit()
        conn.close()
    except Exception,e:
        print "mysql execute: %s,%s" % (sqls, e)
        conn.rollback() 

def mysql_exec(sql,params=''):
    try:
    	conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8')
    	conn.select_db(dbname)
    	curs = conn.cursor()
	'''
	curs.execute("set session sql_mode=''")
	curs.execute("SELECT CONNECTION_ID() AS cid")
	cnntID = (curs.fetchall())[0][0]
	#print sql
	'''
    	if params <> '':
            if len(params) > 0 and (isinstance(params[0], tuple) or isinstance(params[0], list)):
                curs.executemany(sql, params)
	    else:
		curs.execute(sql,params)
        else:
            curs.execute(sql)
        curs.close()
        conn.commit()
        conn.close()
    except Exception, e:
        print "Error: %s" % (sql)
        print "Exception: %s" % (e)
	conn.rollback()



def mysql_query(sql):
    conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8')
    conn.select_db(dbname)
    cursor = conn.cursor()
    #cursor.execute("set session sql_mode=''")
    count=cursor.execute(sql)
    if count == 0 :
        result=0

    else:
        result=cursor.fetchall()
    cursor.close()
    conn.close()
    return result


send_mail_max_count = get_option('send_mail_max_count')
send_mail_sleep_time = get_option('send_mail_sleep_time')
mail_to_list_common = get_option('send_mail_to_list')

def add_alarm(server_id,tags,db
_host,db_port,create_time,db_type,alarm_item,alarm_value,level,message,send_mail=1,send_mail_to_list=mail_to_list_common, send_sms=0, send_sms_to_list=''):
    inpParams = locals()
    try: 
	conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8')
	conn.select_db(dbname)
	curs = conn.cursor()
	sql="insert into alarm(server_id,tags,host,port,create_time,db_type,alarm_item,alarm_value,level,message,send_mail,send_mail_to_list,send_sms,send_sms_to_list) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);"
	param=(server_id,tags,db_host,db_port,create_time,db_type,alarm_item,alarm_value,level,message,send_mail,send_mail_to_list,send_sms,send_sms_to_list)
	curs.execute(sql,param)

	if send_mail == 1:
	    temp_sql = "insert into alarm_temp(server_id,ip,db_type,alarm_item,alarm_type) values(%s,%s,%s,%s,%s);"
	    temp_param = (server_id,db_host,db_type,alarm_item,'mail')
	    curs.execute(temp_sql,temp_param)
	if send_sms == 1:
	    temp_sql = "insert into alarm_temp(server_id,ip,db_type,alarm_item,alarm_type) values(%s,%s,%s,%s,%s);"
	    temp_param = (server_id,db_host,db_type,alarm_item,'sms')
	    curs.execute(temp_sql,temp_param)
	if (send_mail ==0 and send_sms==0):
	    temp_sql = "insert into alarm_temp(server_id,ip,db_type,alarm_item,alarm_type) values(%s,%s,%s,%s,%s);"
	    temp_param = (server_id,db_host,db_type,alarm_item,'none')
	    curs.execute(temp_sql,temp_param)
	conn.commit()
	curs.close()
	conn.close()
    except Exception,e:
	print "Add alarm: " + str(e)     

       
    # insert mongodb
    mongodb_save("alarm_logs",inpParams)


def check_if_ok(server_id,tags,db_host,db_port,create_time,db_type,alarm_item,alarm_value,message,send_mail,send_mail_to_list,send_sms,send_sms_to_list):
    conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,charset='utf8')
    conn.select_db(dbname)
    curs = conn.cursor()
    if db_type=='os':
        alarm_count=curs.execute("select id from alarm_temp where ip='%s' and alarm_item='%s' ;" %(db_host,alarm_item))
        mysql_exec("delete from alarm_temp where ip='%s'  and alarm_item='%s' ;" %(db_host,alarm_item),'')
    else:
        alarm_count=curs.execute("select id from alarm_temp where server_id=%s and db_type='%s' and alarm_item='%s' ;" %(server_id,db_type,alarm_item))                    
        mysql_exec("delete from alarm_temp where server_id=%s and db_type='%s' and alarm_item='%s' ;" %(server_id,db_type,alarm_item),'')

    if int(alarm_count) > 0 :
        sql="insert into alarm(server_id,tags,host,port,create_time,db_type,alarm_item,alarm_value,level,message,send_mail,send_mail_to_list,send_sms,send_sms_to_list) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);"
        param=(server_id,tags,db_host,db_port,create_time,db_type,alarm_item,alarm_value,'ok',message,send_mail,send_mail_to_list,send_sms,send_sms_to_list)
        mysql_exec(sql,param)

    curs.close()
    conn.close()
    
    
def update_send_mail_status(server,db_type,alarm_item,send_mail,send_mail_max_count):
    conn=MySQLdb.connect(host=host,user=user,passwd=passwd,port=int(port),connect_timeout=5,c