#!/usr/bin/python
#TODO: это тут лежит только чтобы не потерять файл при закрытии openstack. В идеале надо бы как-то дешево воссоздать мониторинг mysql-баз
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
import MySQLdb
from threading import Thread
import socket

databases={"user-m": {"host": "wmcrobot-dbm.search.yandex.net", "user": "user_ro_dev", "password": "user_ro_dev", "db": "robot", "port": 3306, "master": True},
           "user-s": {"host": "wmcrobot-dbs1.search.yandex.net", "user": "user_ro_dev", "password": "user_ro_dev", "db": "robot", "port": 3306, "master": False},
           "host0-m": {"host": "wmchost-db02m.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_04", "port": 3306, "master": True},
           "host0-s": {"host": "wmchost-db02s.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_04", "port": 3306, "master": False},
           "host1-m": {"host": "wmchost-db03m.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_05", "port": 3306, "master": True},
           "host1-s": {"host": "wmchost-db03s.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_05", "port": 3306, "master": False},
           "host2-m": {"host": "wmchost-db04m.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_06", "port": 3306, "master": True},
           "host2-s": {"host": "wmchost-db04s.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_06", "port": 3306, "master": False},
           "host3-m": {"host": "wmchost-db05m.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_07", "port": 3306, "master": True},
           "host3-s": {"host": "wmchost-db05s.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_07", "port": 3306, "master": False},
           "host4-m": {"host": "wmchost-db06m.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_08", "port": 3306, "master": True},
           "host4-s": {"host": "wmchost-db06s.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_08", "port": 3306, "master": False},
           "host5-m": {"host": "wmchost-db07m.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_09", "port": 3306, "master": True},
           "host5-s": {"host": "wmchost-db07s.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_09", "port": 3306, "master": False},
           "host6-m": {"host": "wmchost-db08m.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_10", "port": 3306, "master": True},
           "host6-s": {"host": "wmchost-db08s.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_10", "port": 3306, "master": False},
           "host7-m": {"host": "wmchost-db01m.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_03", "port": 3306, "master": True},
           "host7-s": {"host": "wmchost-db01s.search.yandex.net", "user": "host_ro_dev", "password": "host_ro_dev", "db": "host_03", "port": 3306, "master": False}}

PORT_NUMBER = 8084

def check(name):
    d = databases[name]
    try:
        conn = MySQLdb.connect(host=d["ip"], user=d["user"], passwd=d["password"], db=d["db"], port=d["port"], connect_timeout=5)
    except MySQLdb.OperationalError:
        return "FAILED"
    test_query = "SELECT 1"
    if d["master"] == False:
        test_query = "SHOW GLOBAL STATUS like 'slave_running'"
    slave_status = ""
    try:
        c = conn.cursor()
        c.execute(test_query)
        row = c.fetchone()
        c.close
        if d["master"] == False:
            slave_status = row[1];
    except IOError:
        return "FAILED"
    finally:
        conn.close()
    if slave_status:
        return "OK;" + slave_status
    else:
        return "OK"

class MySQLThread(Thread):
    def __init__(self, name):
        Thread.__init__(self)
        self.name = name

    def run(self):
        self.state = check(self.name)

    def get_state(self):
        return self.state

    def get_name(self):
        return self.name

#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):

    #Handler for the GET requests
    def do_GET(self):

        try:
            mimetype='application/json'
            sendReply = True

            if sendReply == True:
                self.send_response(200)
                self.send_header('Content-type',mimetype)
                self.send_header('Access-Control-Allow-Origin', 'http://wmc-monitoring.i-folb.fog.yandex.net')
                self.send_header('Access-Control-Allow-Credentials', 'true')
                self.end_headers()

                #states = {}
                #for (name, d) in sorted(databases.items()):
                #       states[name] = check(name)

                threads = [MySQLThread(name) for name in sorted(databases.keys())]
                for t in threads:
                    t.start()
                states = {}
                for t in threads:
                    t.join()
                    states[t.get_name()] = t.get_state()

                s = ",".join("{\"name\": \"%s\", \"status\": \"%s\"}" % (name, states[name]) for name in sorted(states.keys()))
                self.wfile.write("".join(["{\"databases\": [", s, "]}"]))
            return


        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)

for (k, d) in databases.items():
    t = socket.getaddrinfo(d["host"], None, socket.AF_INET6)
    d["ip"] = t[0][4][0]
try:
    #Create a web server and define the handler to manage the
    #incoming request
    server = HTTPServer(('', PORT_NUMBER), myHandler)
    print 'Started httpserver on port ' , PORT_NUMBER

    #Wait forever for incoming htto requests
    server.serve_forever()

except KeyboardInterrupt:
    print '^C received, shutting down the web server'
    server.socket.close()
