# -*- coding: utf-8 -*-
import os
os.environ["HTTPGUARD_SETTINGS"] = "/opt/httpguard/master/conf/config.py"
from app import db, Message, Config, Site, Node, 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,func,asc
from time import sleep
import threading
import Queue
import json
from jinja2 import Template
import zlib
import requests
import time
import datetime
import ntpath
import sys
import base64

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 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"]
        task_id = data['task_id']
        servers = data['servers']
        servers_json_string = json.dumps(servers)
        servers_json_gzip = zlib.compress(servers_json_string)

        task_type = data['task_type']
        if task_type != "del_site":
            url = "http://{ip}:{port}/v1/save-nginx-vhost".format(ip=ip, port=port)
        else:
            url = "http://{ip}:{port}/v1/del-nginx-vhost".format(ip=ip, port=port)

        try:
            r = requests.post(url, data=servers_json_gzip,timeout=120)
            status_code = r.status_code
            if status_code != 200:
                with threadLock:
                    TASK_RET = "{TASK_RET}\nfailed: node {ip}:{port}\tsave-nginx-vhost return status_code:{status_code}".format(TASK_RET=TASK_RET, ip=ip, port=port, status_code=status_code)
                    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} \tsave-nginx-vhost success.".format(ip=ip, port=port, TASK_RET=TASK_RET)
                    mark_task_done_one(task_id)
                    continue
            else:
                with threadLock:
                    TASK_RET = u"{TASK_RET}\nfailed: node {ip}:{port} \tsave-nginx-vhost return err:{msg}.".format(ip=ip, port=port,msg=msg, TASK_RET=TASK_RET)
                    TASK_SUCCESS = False
                    continue

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

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

def render_nginx_vhost_tpl(upstreams, server, map_data, ngx_cache_dir,ngx_cache_size):
    if server["customize_https_port"] == 0 or server["customize_https_port"] == 443:
        nginx_tpl_file = "conf/nginx.conf.site.tpl"
    else:
        nginx_tpl_file = "conf/nginx.ohter.conf.site.tpl"

    with open(nginx_tpl_file) as fp:
        nginx_tpl = fp.read()

    template = Template(nginx_tpl)
    return template.render(upstreams=upstreams, server=server, map_data = map_data, ngx_cache_dir=ngx_cache_dir, ngx_cache_size=ngx_cache_size)


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

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 == "sync_site") | (Task.type == "del_site") | (Task.type == "sync_node_site" ) ) & (Task.delflag == 0) & ( Task.state != "success")  ).first()
    if task is None:
        db.session.close()
        return sleep_time
        
    # 查询cache_dir, ngx_cache_size
    ngx_cache_dir = Config.query.filter_by(name="ngx_cache_dir").first().value
    ngx_cache_size = Config.query.filter_by(name="ngx_cache_size").first().value

    task_id = task.id
    task_type= task.type
    value = task.value
    user_id = task.user_id
    details = json.loads(value)
    if not isinstance(details,list):
        details = [details]

    mark_task_start(task_id, len(details))
    for detail in details:
        if not isinstance(detail,dict):
            detail = json.loads(detail)

        node_id = detail['node_id']
        site_id = str(detail['site_id'])
        try:
            domain = detail['domain']
        except KeyError:
            domain = site_id
                
        node = Node.query.filter_by(id=node_id).first()
        if node is None or node.enable == False or node.failed_times >= 3:
            continue

        title = u"sync website {domain}".format(domain=domain)
        type = "sync_site"
        res = domain
        level = "failed"

        servers = []
        for sid in site_id.split("|"):
            if task_type != "del_site":
                site = Site.query.filter_by(id=sid).first()
                if site is None:
                    continue               
                         
                domain = site.domain
                upstream_ip = site.upstream_ip
                http_port = str(site.http_port)
                enable_https = site.enable_https
                https_port = str(site.https_port)
                http_back_to_source = site.http_back_to_source
                force_https = site.force_https
                customize_https_port = site.customize_https_port
                ca_type = site.ca_type
                crt = site.crt
                key = site.key
                error404 = site.error404.encode("utf-8")
                error50x = site.error50x.encode("utf-8")
                cc_rule = site.cc_rule
                auto_cc_rule = site.auto_cc_rule
                allow_spider = site.allow_spider
                hotlink = site.hotlink
                hsts = site.hsts
                enable_http2 = site.enable_http2
                proxy_connect_timeout = site.proxy_connect_timeout
                proxy_send_timeout = site.proxy_send_timeout
                proxy_read_timeout = site.proxy_read_timeout
                proxy_next_upstream = site.proxy_next_upstream
                acl_rule = site.acl_rule
                proxy_ssl_protocols = site.proxy_ssl_protocols

                if enable_http2:
                    http2 = "http2"
                else:
                    http2 = ""    

                # 解析map为json
                map_data_tmp = site.map_data
                map_data_tmp = json.loads(map_data_tmp)

                # 解析proxy_cache为json            
                proxy_cache_tmp = site.proxy_cache
                proxy_cache_tmp = json.loads(proxy_cache_tmp)

                # 解析rewrite_data为json            
                rewrite_data = site.rewrite_data
                rewrite_data = json.loads(rewrite_data)

                # 解析upstreams为json            
                upstreams = site.upstreams
                if upstreams == "" or upstreams is None:
                    upstreams = "{}"

                upstreams = json.loads(upstreams)

                # 处理proxy_cache中的nocache,当nocache使用的是map变量时,自动在后面加site_id
                map_val_name_arr = [ map_val['val_name'] for map_val in map_data_tmp]
                proxy_cache = []
                for p in proxy_cache_tmp:
                    nocache = p['nocache']
                    nocache_arr = []
                    for i in nocache.split():
                        if i in map_val_name_arr:
                            nocache_arr.append(i+"_"+sid)
                        else:
                            nocache_arr.append(i)

                    p['nocache'] = " ".join(nocache_arr)
                    proxy_cache.append(p)    

                # map变量处理,后面加sid
                map_data = []
                for map_val in map_data_tmp:
                    map_val['val_name'] = map_val['val_name'] + "_" + sid
                    map_data.append(map_val)

                # 判断/是否配置了缓存
                for cache in proxy_cache:
                    if cache["url"] == "/":
                        location_root_dupl = True
                        break
                else:
                    location_root_dupl = False

                server = {"domain":domain,"enable_https":enable_https,"http_back_to_source":http_back_to_source,"force_https":force_https,"ca_type":ca_type,"crt":crt,"key":key,
                           "proxy_cache":proxy_cache,"error404":error404,"error50x":error50x,"cc_rule":cc_rule,"auto_cc_rule":auto_cc_rule,"allow_spider":allow_spider,"hotlink":hotlink,"hsts":hsts,
                           "location_root_dupl":location_root_dupl,"site_id":sid,"rewrite_data":rewrite_data,"http2":http2,"http_port":http_port,"https_port":https_port,
                            "proxy_connect_timeout":proxy_connect_timeout,"proxy_send_timeout":proxy_send_timeout,"proxy_read_timeout":proxy_read_timeout,"proxy_next_upstream":proxy_next_upstream,
                            "upstream_ip":upstream_ip,"acl_rule":acl_rule,"proxy_ssl_protocols":proxy_ssl_protocols, "customize_https_port": customize_https_port}

                nginx_vhost_conf = render_nginx_vhost_tpl(upstreams, server, map_data, ngx_cache_dir, ngx_cache_size)
                servers.append({"vhost":base64.b64encode(nginx_vhost_conf),"site_id":sid,"error404":base64.b64encode(error404),
                                "error50x":base64.b64encode(error50x),"crt":base64.b64encode(crt),"key":base64.b64encode(key), "ngx_cache_dir":base64.b64encode(ngx_cache_dir)})
                                              
            else:
                servers.append({"site_id":sid,"ngx_cache_dir":ngx_cache_dir})
            
        data = {"task_type":task_type, "task_id":task_id, "ip":node.ip,"port":node.port,"name":node.name,"servers":servers }
        SHARE_Q.put(data)

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

    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

    if task_type == "sync_node_site":
        title = u"sync node {node_name} {node_ip}".format(node_name=node.name, node_ip=node.ip)
    elif task_type == "sync_site":
        title = u"sync website {domain}".format(domain=domain)
    else:
        title = u"delete website {domain}".format(domain=domain)

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

if __name__ == '__main__':
    main()