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

import os
os.environ["HTTPGUARD_SETTINGS"] = "/opt/httpguard/master/conf/config.py"
from app import db, Line_group, Config, line, Task
from public_func import make_msg, mark_task_start, mark_task_success, mark_task_failed, mark_task_del, mark_task_done_one
from sqlalchemy import desc
import app
from time import sleep
import time
import requests
import json
import ntpath
import sys
import os
import datetime
from cloudxns.api import *
import httplib
import socket
from collections import OrderedDict
import threading
import Queue

threadLock = threading.Lock()
SHARE_Q = Queue.Queue()  
TASK_SUCCESS = True
_WORKER_THREAD_NUM = 4
TASK_RET = ""

class MyThread(threading.Thread) :

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

    def run(self) :
        self.func()

def heartbeat(name):
    heartbeat_file = os.path.join("/tmp",name + ".heartbeat")
    with open(heartbeat_file,"w") as fp:
        fp.write("")

def worker() :
    global SHARE_Q
    global TASK_SUCCESS
    global TASK_RET
    while not SHARE_Q.empty():
        data = SHARE_Q.get(True, 2)
        ip = data["ip"]
        port = data["port"]
        site_id = data['site_id']
        name = data['name']
        url_clean = data['url']
        ngx_cache_dir = data['ngx_cache_dir']
        task_id = data["task_id"]

        url = "http://{ip}:{port}/v1/{name}".format(ip=ip, port=port, name=name)

        try:
            r = requests.post(url, data=json.dumps({"site_id":site_id,"url":url_clean,"ngx_cache_dir":ngx_cache_dir}),timeout=30)
            status_code = r.status_code
            if status_code != 200:
                with threadLock:
                    TASK_RET = "{TASK_RET}\nfailed: node {ip}:{port} \t{name} return status_code:{status_code}".format(TASK_RET=TASK_RET, ip=ip, port=port, status_code=status_code,name=name)
                    TASK_SUCCESS = False
                    continue

            content = r.content
            content = json.loads(content)
            state = content["state"]
            msg = content["msg"]
            if state == "success":
                with threadLock:
                    TASK_RET = u"{TASK_RET}\nsuccess: node {ip}:{port} \t{name} success.".format(ip=ip, port=port, TASK_RET=TASK_RET,name=name)
                    mark_task_done_one(task_id)
                    continue
            else:
                with threadLock:
                    TASK_RET = u"{TASK_RET}\nfailed: node {ip}:{port} \t{name} return err:{msg}.".format(ip=ip, port=port,msg=msg, TASK_RET=TASK_RET,name=name)
                    TASK_SUCCESS = False
                    continue

        except requests.exceptions.Timeout:
            with threadLock:
                TASK_RET = u"{TASK_RET}\nfailed: node {ip}:{port} \t{name} timeout.".format(ip=ip, port=port, TASK_RET=TASK_RET,name=name)
                TASK_SUCCESS = False
                continue

        except requests.exceptions.ConnectionError:
            with threadLock:
                TASK_RET = u"{TASK_RET}\nfailed: node {ip}:{port} \t{name} connectionError.".format(ip=ip, port=port, TASK_RET=TASK_RET,name=name)
                TASK_SUCCESS = False
                continue

    

def main():
    global SHARE_Q
    global TASK_SUCCESS
    global TASK_RET

    TASK_SUCCESS = True
    TASK_RET = ''    
    sleep_time = 5

    task = Task.query.filter( ((Task.type=="clean_site_cache") | (Task.type=="clear_site_certain_cache") | (Task.type == "clean_site_whitelist") | (Task.type == "clean_site_blacklist")) & (Task.delflag == 0) & ( Task.state != "success") ).first()
    if task is None:
        db.session.close()
        return sleep_time

    task_id = task.id
    value = task.value
    name = task.type
    user_id = task.user_id
    data = json.loads(value)
    line_group_id = data['line_group_id']
    site_id = data['site_id']
    domains = data['domains']
   
    url = ""
    try:
        url = data['url']
    except KeyError:
        pass

    ngx_cache_dir = Config.query.filter_by(name="ngx_cache_dir").first().value

    title = u"{name} {domains}".format(domains=domains,name=name)
    type = name
    res = domains

    sleep_time = 1
    line_group = Line_group.query.filter_by(id=line_group_id).first()
    nodes = line_group.nodes

    task_amount = 0
    for node in nodes:
        if node.failed_times >= 3:
            continue

        task_amount = task_amount + 1
        data = {"site_id":site_id, "ip":node.ip,"port":node.port,"name":name,"url":url,"ngx_cache_dir":ngx_cache_dir,"task_id":task_id}
        SHARE_Q.put(data)

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

    # 开始任务
    mark_task_start(task_id, task_amount)
    for thread in threads :
        thread.join()

    if TASK_SUCCESS:
        level = "success"
        mark_task_success(task_id, TASK_RET)
    else:
        level = "failed"
        mark_task_failed(task_id, TASK_RET)
        sleep_time = 60

    data = TASK_RET
    if data != '':
        make_msg(title, data, user_id, type, res, level)
    db.session.close()
    return sleep_time
    

if __name__ == '__main__':
    main()