# -*- coding: utf-8 -*-

from time import sleep
import threading
import Queue
import requests
import json
import time
import ntpath
import sys
import os
from sqlalchemy.sql import select

os.environ["HTTPGUARD_SETTINGS"] = "/opt/httpguard/master/conf/config.py"
import app
from route import create_task, sync_node_sites

SHARE_Q = Queue.Queue()  
_WORKER_THREAD_NUM = 4

class MyThread(threading.Thread):

    def __init__(self, func) :
        super(MyThread, self).__init__()
        self.func = func

    def run(self) :
        self.func()

def update_node(id, state, machine_code):
    node = app.Node.query.filter_by(id=id).first()
    node.state = state
    node.machine_code = machine_code
    app.db.session.commit()
    app.db.session.close()

def delete_node_vhost(url):
    try:
        r = requests.post(url,data="",timeout=10)
        status_code = r.status_code
        if status_code != 200:
            return False

        body = r.content
        body =  json.loads(body)
        state = body["state"]
        msg = body["msg"]
        return True

    except:
        return False    


def update_node_failed_times(success, node_id):
    node = app.Node.query.filter_by(id=node_id).first()
    failed_times = node.failed_times
    ip = node.ip
    port = node.port

    if success:
        # 节点恢复, 全量同步配置   
        if failed_times >= 3:
            url = "http://{ip}:{port}/v1/del-all-vhost".format(ip=ip, port=port)
            delete_success = delete_node_vhost(url)
            if not delete_success:
                print "清空节点vhost失败,{url}".format(url=url)
                return

            # 添加同步任务           
            user_id = 1
            sync_node_sites(None, node_id, user_id)

            create_task("sync_config_json","", "",1)
            create_task("sync_nginx_conf", "", "",1)
 
        # 失败次数置为0
        node.failed_times = 0
        app.db.session.commit()
        app.db.session.close()

    else:
        # 计一次失败次数
        node.failed_times = failed_times + 1
        app.db.session.commit()
        app.db.session.close()

def worker() :
    global SHARE_Q
    while not SHARE_Q.empty():
        node = SHARE_Q.get(True, 2)
        id = node.id
        ip = node.ip
        port = node.port
        success = False

        url = "http://{ip}:{port}/v1/guard-status".format(ip=ip, port=port)
        try:
            r = requests.get(url,timeout=10)
            status_code = r.status_code

            # 节点未给master授权
            if status_code == 403:
                update_node(id, "not_auth", None)
                continue

            # 非200认为系统错误
            if status_code != 200:
                update_node(id, "sys_err", None)
                continue

            body = r.content
            try:
                body =  json.loads(body)
                state = body["state"]
                msg = body["msg"]
            except ValueError:
                # 返回非json认为系统错误
                update_node(id, "sys_err", None)
                continue

            if state == "failed":
                update_node(id, "machine_code_failed", None)
                continue

            nginx_running = msg["nginx_running"]
            machine_code = msg["machine_code"]

            # nginx已停止
            if not nginx_running:
                update_node(id, "stopped", machine_code)
                continue

            # 系统正常
            success = True
            update_node(id, "running", machine_code)
                

        except requests.exceptions.ConnectionError:
            update_node(id, "timeout", None)

        except requests.exceptions.Timeout:
            update_node(id, "timeout", None)

        finally:
            update_node_failed_times(success, id)

def main():
    global SHARE_Q
    threads = []
    nodes = app.Node.query.all()
    
    for node in nodes :
        if node.enable == True:
            url = "{ip}:{port}".format(ip=node.ip, port=node.port)
            SHARE_Q.put(node)

    for i in xrange(_WORKER_THREAD_NUM) :
        thread = MyThread(worker)
        thread.start()
        threads.append(thread)

    for thread in threads :
        thread.join()    

    app.db.session.close()
    

if __name__ == '__main__':
    main()        