import sys
import os
import asyncio
import logging
import time
import requests
import alb_utils
import gateway_config
from concurrent.futures import ThreadPoolExecutor

health_instances = []

def gateway_health_check(ecs_client, instance_id, max_wait_time=None):
    """
    服务健康检查
    :param ecs_client: 客户端连接
    :param instance_id: instanceId
    :param max_wait_time: 最长等待时间,单位:s
    :return:
    """
    global health_instances
    start_time = time.time()
    ip_address = alb_utils.get_ip_address(ecs_client=ecs_client, instance_id=instance_id)
    while True:
        health_check_url = f"http://{ip_address}:9000/healthcheck"
        try:
            http_code = requests.get(health_check_url).status_code
        except:
            logging.info(f"images is downloading ip: {ip_address}")
            http_code = 0

        if http_code == 200:
            health_instances.append((instance_id, ip_address))
            logging.info(f"health check success, instance: {instance_id}/{ip_address}")
            break
        elif max_wait_time is not None:
            now = time.time()
            if (now - start_time) >= max_wait_time:
                logging.info(f"health check error, instance: {instance_id}/{ip_address}")
                break
            else:
                time.sleep(10)
        else:
            time.sleep(10)


async def ess_instance(ecs_client, alb_client, ess_count, max_workers, port):
    """
    扩容机器并运行新服务
    :param ecs_client: 购买机器客户端连接
    :param alb_client: 修改负载均衡权限
    :param ess_count: 扩容数量
    :param max_workers: 线程数
    :param port: 后端服务器使用的端口
    :return:
    """
    # 1. 购买机器并启动
    ess_instance_ids = alb_utils.create_multiple_instances(
        amount=ess_count,
        ecs_client=ecs_client,
        **gateway_config.instance_config_j,
    )
    time.sleep(60)

    # 2. 发送启动脚本到机器上
    alb_utils.send_file_to_ecs(ecs_client=ecs_client, instance_id_list=ess_instance_ids, **gateway_config.start_sh)
    logging.info(f"send start shell file finished, count: {len(ess_instance_ids)} instances: {ess_instance_ids}")
    # 3. 启动服务
    start_sh_param = "latest"
    server_start_sh = os.path.join(gateway_config.start_sh['target_dir'], gateway_config.start_sh['name'])
    server_start_commend = f"sh {server_start_sh} {start_sh_param}"
    alb_utils.run_command(ecs_client=ecs_client, instance_ids=ess_instance_ids, command=server_start_commend)
    # 4. 异步探活
    global health_instances
    health_instances = []
    max_wait_time = 360
    loop = asyncio.get_running_loop()
    executor = ThreadPoolExecutor(max_workers=max_workers)
    tasks = [
        loop.run_in_executor(executor, gateway_health_check, *args) for args in
        [(ecs_client, instance_id, max_wait_time) for instance_id in ess_instance_ids]
    ]
    await asyncio.wait(tasks)
    logging.info(f"health instances count: {len(health_instances)}, {health_instances}")

    # 5. 挂载流量到ALB
    if len(health_instances) > 0:
        # 所有机器探活成功
        time.sleep(20)
        # instance_id_list = []
        # for instance_id, ip in health_instances:
        #     instance_id_list.append(instance_id)
        # #     for server_group_id in gateway_config.server_group_id_list:
        health_instance_ids = [instance_id for instance_id, _ in health_instances]
        alb_utils.add_servers_to_server_group(alb_client, gateway_config.server_group_id_list, health_instance_ids, weight=100, port=port)
        logging.info(f"ess count: {ess_count}, "
                     f"create count: {len(ess_instance_ids)}, "
                     f"finished count: {len(health_instances)}")
    else:
        logging.info(f"ess count: {ess_count}, "
                     f"create count: {len(ess_instance_ids)}, "
                     f"health count: {len(health_instances)}")
        sys.exit()



def main():
    try:
        ecs_client = alb_utils.connect_client(access_key_id=gateway_config.ecs_client_params['access_key_id'],
                                          access_key_secret=gateway_config.ecs_client_params['access_key_secret'],
                                          region_id=gateway_config.ecs_client_params['region_id'])
        alb_client = alb_utils.connect_alb_client(
            access_key_id=gateway_config.alb_client_params['access_key_id'],
            access_key_secret=gateway_config.alb_client_params['access_key_secret'],
            endpoint=gateway_config.alb_client_params['endpoint']
        )
        # 获取批量创建ECS实例的数量
        ess_instance_count = int(sys.argv[1])
        # 扩容机器并启动服务
        logging.info(f"ess instances start ...")
        logging.info(f"ess instance count: {ess_instance_count}")
        asyncio.run(ess_instance(ecs_client=ecs_client,
                                 alb_client=alb_client,
                                 ess_count=ess_instance_count, max_workers=2, port=gateway_config.port))
        logging.info(f"ess instances end!")
    except Exception as e:
        logging.error(e)


if __name__ == '__main__':
    main()