#!/usr/bin/python3

import json
import random
import subprocess
import sqlite3
import time
import os.path
import sys
from pprint import pprint

#####################################################################
config = {
    # L20队列: 保持空闲3台开机，空闲12小时关机
    'g02': {
        'max_idle_hours': 12,
        'min_idle_hosts': 3,
        "mg_hosts": [],
        "up_batch_size": 0,
    },
    # H100队列：空闲12小时关机全部关机，g01n001和g01n002是子网管理器，至少保持一台开机
    'g01': {
        'max_idle_hours': 12,
        'min_idle_hosts': 1,
        "mg_hosts": ['g01n001', 'g01n002'],
        "up_batch_size": 0,
    },   
    # 天数队列: 保持空闲3台开机，空闲12小时关机
    'g21': {
        'max_idle_hours': 12,
        'min_idle_hosts': 3,
        "mg_hosts": [],
        "up_batch_size": 0,
    },   
    # 按照等待作业需求开机，分批（最大值找联想确认）多次开机，
    # 避免同时开机引起电路故障，机器轮流开机，避免某些机器长时间不开机有故障 
    'c01': {
        'max_idle_hours': 12,
        'min_idle_hosts': 0,
        "mg_hosts": [],
        "up_batch_size": 5,
    },        
}
#########################################################################

PWDB = '/opt/skyformai/work/power.db'
PWTABLE = 'power_hist'
PWCOLS = '(host, queue, ncpu, ngpu, memmb, uptime, offtime)'
CREATE_TABLE_SQL = 'CREATE TABLE IF NOT EXISTS %s ( \
  host text PRIMARY KEY, \
  queue text NOT NULL, \
  ncpu integer, \
  ngpu integer, \
  memmb text, \
  uptime integer, \
  offtime integer \
)' % (PWTABLE)

dry_run = False
debug = False
orig_stdout = None
power_hist = {}
now = int(time.time())

def db_init():  
    try:
        conn = sqlite3.connect(PWDB)
        conn.row_factory = sqlite3.Row            
        c = conn.cursor()
        c.execute(CREATE_TABLE_SQL)
        conn.commit() 
        sql = 'SELECT * FROM %s' % PWTABLE
        c = conn.execute(sql)
        for r in c.fetchall():
            row = dict(r)
            if row['queue'] not in power_hist:
                power_hist[row['queue']] = [] 
            power_hist[row['queue']].append(row)
        conn.close()
    except Exception as e:
        print(f"Sqlite error: {e}")          
    if debug:
        print("=== Power history from database")
        pprint(power_hist)    
    
def db_update(sql): 
    if debug:
        print("=== Update database")
        print(sql)  
    if dry_run:
        return     
    try: 
        conn = sqlite3.connect(PWDB)
        conn.execute(sql)
        conn.commit()
        conn.close()
    except Exception as e:
        print(f"Sqlite error: {e}")  
        
def get_pw_save_sql(hosts, q):
    vals = ''
    for s in hosts:
        for h in q['hosts']:
            if s == h['host']:
                if len(vals) != 0:
                    vals += ','  
                vals += ("('%s', '%s', %d, %d, %d, 0, %d)" % 
                        (h['host'], q['queue'], h['numCPUs'], h['numGPUs'], h['maxMemMB'], now))
    sql = 'INSERT or REPLACE INTO %s %s VALUES %s' % (PWTABLE, PWCOLS, vals)
    return sql 
    
def get_pw_up_sql(hosts, q):
    sql = ''
    for s in hosts:
        for h in q['hosts']:
            if s == h['host']:
                if len(sql) != 0:
                    sql += ';'  
                sql = "UPDATE %s SET uptime=%s, offtime=0 where host='%s'" % (PWTABLE, now, h['host'])              
    return sql 
    
def exec_cmd(cmd):
    if debug:
        print("=== Run power action")
        print(cmd)
    if dry_run:
        return 0
    try:
        sp = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        sp.stdin.write('y\n'.encode())
        out, err = sp.communicate()
        if out:
            print(out.decode("utf-8"))
        if err:
            print(err.decode("utf-8"))
        return sp.returncode 
    except Exception as e:
        print(f"exec_cmd error: {e}")           
        return -1
    
def select_up_hosts_by_host_num(qname, nhost):
    selected = []
    if q['queue'] not in power_hist:
        return selected    
    candidates = {item['host']:item for item in power_hist[qname]}
    candidates = {k: v for k, v in candidates.items() if v['uptime'] == 0}
    while nhost > 0 and len(candidates) > 0:
        off_long_host = ""
        timestamp = 0
        for key, val in candidates.items():
            if timestamp == 0 or val['offtime'] < timestamp:
                timestamp = val['offtime']
                off_long_host = key
        selected.append(off_long_host)
        candidates.pop(off_long_host) 
        nhost -= 1
    return selected  

def select_up_hosts_by_pending_jobs(q):    
    need_cpus = 0
    need_gpus = 0
    askedHost = []
    selected = []
    if q['queue'] not in power_hist:
        return selected
    candidates = {item['host']:item for item in power_hist[q['queue']]}
    candidates = {k: v for k, v in candidates.items() if v['uptime'] == 0}
    for j in q['pending_jobs']:
        need_cpus += j['numCPUs']
        need_gpus += j['numGPUs']
        if len(j['askedHost']) > 0:
            askedHost.extend(j['askedHost'])
    askedHost = list( dict.fromkeys(askedHost))
    for h in askedHost:
        selected.append(h)
        need_cpus -= candidates[h]['ncpu']
        need_gpus -= candidates[h]['ngpu']
        candidates.pop(h)
    while (need_cpus > 0 or need_gpus > 0) and len(candidates) > 0:
        off_long_host = ""
        timestamp = 0
        for key, val in candidates.items():
            if timestamp == 0 or val['offtime'] < timestamp:
                timestamp = val['offtime']
                off_long_host = key
        selected.append(off_long_host)     
        need_cpus -= candidates[off_long_host]['ncpu']
        need_gpus -= candidates[off_long_host]['ngpu']
        candidates.pop(off_long_host)     
    return selected         

# get host status
if len(sys.argv) > 1:
    if os.path.exists(sys.argv[1]):
        with open(sys.argv[1]) as f:
            data = json.load(f)
        dry_run = True        
        debug = True
else:
    data = json.load(sys.stdin) 

if debug:    
    orig_stdout = sys.stdout
    f = open('/tmp/power_sched_out.txt', 'w')
    sys.stdout = f
    print("=== Host status from AIP")
    pprint(data)

# read power history from database
db_init() 

for q in data['queues']:
    if q['queue'] in config:
        qc = config[q['queue']]
        idle_hosts = []
        longtime_idle_hosts = []
        longtime_idle_mg_hosts = []
        selected = []
        for h in q['hosts']:
            if h['status'] == 'ok' and h['numjobs'] == 0:
                idle_hosts.append(h['host'])
                if h['idle_sec'] > qc['max_idle_hours']*3600:
                    is_mgh = False
                    if len(qc['mg_hosts']) > 0: 
                        for mgh in qc['mg_hosts']:
                            if h['host'] == mgh:
                                longtime_idle_mg_hosts.append(h['host'])  
                                is_mgh = True
                                break
                    if is_mgh == False:          
                        longtime_idle_hosts.append(h['host'])    
        if debug:
            print("=== Evaluate queue: %s" % q['queue']) 
            print('idle hosts:')
            print(idle_hosts) 
            print('idle hosts that exceeds max_idle_hours:')
            print(longtime_idle_hosts) 
            print('idle management hosts that exceeds max_idle_hours:')
            print(longtime_idle_mg_hosts) 
                       
        # power up            
        if len(idle_hosts) < qc['min_idle_hosts'] or (qc['min_idle_hosts'] == 0 and len(q['pending_jobs']) > 0): 
            if len(idle_hosts) < qc['min_idle_hosts']:
                selected = select_up_hosts_by_host_num(q['queue'], qc['min_idle_hosts']-len(idle_hosts) )
                if debug:
                    print('selected power up hosts by min host num:')
                    print(selected)
            else:
                selected = select_up_hosts_by_pending_jobs(q)
                if debug:
                    print('selected power up hosts by pending jobs:')
                    print(selected)
            if qc['up_batch_size'] > 0 and len(selected) > qc['up_batch_size']:
                selected = selected[0:qc['up_batch_size']]
                if debug:
                    print('power up batch size limit: %d' % qc['up_batch_size'])
                    print(selected)
            if len(selected) == 0:
                continue        
            # update database
            sql = get_pw_up_sql(selected, q)
            db_update(sql) 
            # execuate power up action
            cmd = data['power_resume_cmd'].strip().split(' ')
            cmd.append(' '.join(selected))
            exec_cmd(cmd)  
        # power save    
        elif ((len(qc['mg_hosts']) == 0 and len(longtime_idle_hosts) > qc['min_idle_hosts']) or 
              (len(qc['mg_hosts']) > 0 and 
                (len(longtime_idle_mg_hosts) > qc['min_idle_hosts'] or len(longtime_idle_hosts) > 0))):
            if len(qc['mg_hosts']) == 0:
                selected = random.sample(longtime_idle_hosts, 
                        len(longtime_idle_hosts)-qc['min_idle_hosts'])
                if debug:
                    print('power save selected hosts:')
                    print(selected)
            else:
                if len(longtime_idle_mg_hosts) > qc['min_idle_hosts']:
                    selected = random.sample(longtime_idle_mg_hosts, 
                        len(longtime_idle_mg_hosts)-qc['min_idle_hosts'])
                    if debug:
                        print('power save selected management hosts:')
                        print(selected)
                if len(longtime_idle_hosts) > 0:    
                    selected.extend(longtime_idle_hosts) 
                    if debug:
                        print('power save selected hosts:')
                        print(selected)    
            if len(selected) == 0:
                continue                                                             
            # update database  
            sql = get_pw_save_sql(selected, q)
            db_update(sql) 
            # execuate power save action
            for sh in selected:
                cmd = data['power_stop_cmd'].strip().split(' ')
                cmd.append(sh)
                exec_cmd(cmd)    

if debug:
    sys.stdout = orig_stdout
    f.close()
            
