#!/bin/bash
(
cat <<EOF
from naie.context import Context
Context.init('/home/ossuser/naie_rollback', '/tmp')
Context.set_auth_path(client_file_path="/home/ossuser/naie_rollback/jwt")
from naie.http import HttpClient
from naie.kafka import Producer
import os
import json
import time
from naie.db import DbClient
import re
import uuid

MODEL_LIST = []

def refresh_pipeline():
    try:
        model_list = get_need_restart_model_list()
        topic = "NAIE_APP_MANAGE"
        producer = Producer.get_producer(topic=topic)
        for model in model_list.values():
            model_name = model["name"]
            model_version = model["version"]
            kafka_msg = {"event": "import", "app_name": model_name, "app_version": model_version}
            kafka_msg = json.dumps(kafka_msg)
            producer.produce(kafka_msg.encode("utf-8"))
    except Exception as e:
        print('excute failed! {}'.format(str(e)))

def refresh_model():
    print("1")
    add_model_info()
    model_list = get_need_restart_model_list()
    redeploy_model(model_list)
    delete_model_info()

def delete_model_info():
    with get_db_connect() as connect:
        for model in MODEL_LIST:
            connect.execute(f"delete from msagent_service where name='{model[0]}' and version='{model[1]}'")

def add_model_info():
    with get_db_connect() as connect:
        ip_list = connect.execute(f"select distinct ip from msagent_service").fetchall()
        print(ip_list)
        print("3")
        for model_name in os.listdir("/opt/infers/spark"):
            if model_name == "spark-runner" or model_name == "thirdlib":
                continue
            for model_version in os.listdir(os.path.join("/opt/infers/spark", model_name)):
                if re.search('[0-9]{0,4}\.[0-9]{0,4}\.[0-9]{0,4}', model_version) and os.path.isdir(os.path.join("/opt/infers/spark", model_name, model_version)):
                    result = connect.execute(f"select * from msagent_service where name='{model_name}' and version='{model_version}'").fetchall()
                    print(result)
                    if len(result) == 0:
                        for ip in ip_list:
                            connect.execute(f"insert into msagent_service (id,ip,name,version, create_at, update_at) values ('{uuid.uuid4().hex}','{ip[0]}', '{model_name}', '{model_version}', now(), now())")
                        MODEL_LIST.append([model_name,model_version])

        
def get_db_connect():
    with open(os.environ.get("APP_CONF_FILE"), 'r') as load_f:
        print("2")
        db_name='msagentdb'
        app_version_json = json.load(load_f)
        dbtype = app_version_json.get('databases', {}).get(db_name, [])[0].get('type')
        password = app_version_json.get('databases', {}).get(db_name, [])[0].get('passwd')
        port = app_version_json.get('databases', {}).get(db_name, [])[0].get('port')
        user = app_version_json.get('databases', {}).get(db_name, [])[0].get('user')
        ip = app_version_json.get('databases', {}).get(db_name, [])[0].get('serverName')
        return DbClient.get_connection(ip, port, user, password, user, dbtype)

def get_need_restart_model_list():
    model_list_json = HttpClient.get('ir:///rest/softcomai/inference/v1/services')[1]
    print(f"model_list:${model_list_json}")
    need_redeploy_model_map = {}
    model_list = json.loads(model_list_json)
    for model in model_list['services']:
        if model['ai_platform']=='ODAE' and (not model['name'] in need_redeploy_model_map or model['deploy_at'] > need_redeploy_model_map[model['name']]['deploy_at']):
            need_redeploy_model_map[model['name']]=model
    print(f'${need_redeploy_model_map}')
    return need_redeploy_model_map


def redeploy_model(model_list: list):
    for model in model_list.values():
        HttpClient.put(f'ir:///rest/softcomai/inference/v1/services/usage-state/{model["name"]}/{model["version"]}',
                   {'status':'unused'})
        HttpClient.delete(f'ir:///rest/softcomai/inference/v1/services/{model["name"]}/{model["version"]}')
    check_and_deploy_model(model_list)

def check_and_deploy_model(model_list: list):
    need_add_usage_list={}
    for _ in range(1,100):
        time.sleep(15)
        list_cache = []
        for model in model_list.values():
            model_list_json = HttpClient.get(f'ir:///rest/softcomai/inference/v1/services?service_name={model["name"]}&service_version={model["version"]}')[1]
            if len(json.loads(model_list_json)["services"]) == 0 :
                result = HttpClient.post(f'ir:///rest/softcomai/inference/v1/services/{model["name"]}/{model["version"]}',{'alloc_policy':{'policy_type':'all'},'mode':'on_demand'})
                print(f"{result}")
                need_add_usage_list[model['name']]=model
                list_cache.append(model)
        for model in list_cache :
            model_list.pop(model['name'])
        list_cache.clear()
        time.sleep(15)
        for model in need_add_usage_list.values():
            model_list_json = HttpClient.get(f'ir:///rest/softcomai/inference/v1/services?service_name={model["name"]}&service_version={model["version"]}')[1]
            if json.loads(model_list_json)["services"][0]["status"] == "stopped":
                HttpClient.put(f'ir:///rest/softcomai/inference/v1/services/usage-state/{model["name"]}/{model["version"]}',
                   {'status':'used'})
                list_cache.append(model)
        for model in list_cache:
            need_add_usage_list.pop(model['name'])
        list_cache.clear()
        if len(model_list) == 0 and len(need_add_usage_list) == 0:
            break
    return

if __name__ == '__main__':
    refresh_pipeline()
    refresh_model()
EOF
) > /home/ossuser/naie_rollback/naie_rollback.py
cat /opt/oss/envs/Product-NAIEDeployCombAgent/*/envs/* | awk '{print "export " $0}' > /home/ossuser/naie_rollback/my_env.sh
source /home/ossuser/naie_rollback/my_env.sh
rm -f /home/ossuser/naie_rollback/my_env.sh

my_python_path=`ls -d /opt/infers/spark/*/*/python/lib/python3.8 | head -1`
if [ "_$my_python_path" == "_" ]; then
  exit 0
fi

export PYTHONPATH=${PYTHONPATH}:${my_python_path}/site-packages:${APP_ROOT}/rtsp/mccommon/tools/pyscript
export PYTHONPATH=${PYTHONPATH}:${APP_ROOT}/dbdriver_zenith/pyscript/zenith:${APP_ROOT}/dbdriver_zenith/pyscript:${PYTHONPATH}
export LD_LIBRARY_PATH=${APP_ROOT}/dbdriver_zenith/pyscript/zenith:${LD_LIBRARY_PATH}
${my_python_path}/../../bin/python /home/ossuser/naie_rollback/naie_rollback.py >> /home/ossuser/naie_rollback/test.txt
exit 0
