#!/usr/bin/python
#
# SkyForm AIP bill generator for multiple clusters
# Copyright 2019 Skycloud Software
#
#
import subprocess, os, sys, datetime, re, json, getopt

def usage():
    print 'Usage:', os.path.basename(sys.argv[0]), '[-d cluster1_top_dir [-d cluster2_top_dir ...]]'
    print '\t\t', '[-m month(format yyyy-mm)]'
    print '\t\t', '[-c cluster_name]'
    print '\t\t', '[-u user|usergroup]'
    print '\t\t', '[-q "queue"]'
    print '\t\t', '[-J "jobname"]'
    print '\t\t', '[-D "job_description"]'
    sys.exit(0);

currentdate = datetime.datetime.now()
targetmonth = str(currentdate.year) + '-' + str(currentdate.month)
acctmonth='0'
jsonformat=0

def calcmonth(mstr):
    global currentdate
    y = int(mstr[0:4])
    m = int(mstr[5:])
    if y < 2019 or y > currentdate.year or m < 1 or m > 12 or (y == currentdate.year and m > currentdate.month):
        print "Error:", mstr, "is not valid (yyyy-mm)"
        usage()
    if y == currentdate.year:
        return str(currentdate.month - m)
    else:
        return str((currentdate.year - y) * 12 + currentdate.month - m)


dirs = []
clusters = []

monthpattern = re.compile("[0-9]*-[0-9]*")
try:
    opts, args = getopt.getopt(sys.argv[1:], "c:d:D:J:hm:u:jq:")
except getopt.GetoptError:
    print 'Invalid option'
    usage()

user='all'
queue=''
cluster=''
jname=''
description=''

for opt, arg in opts:
    if opt == '-h':
        usage()
    elif opt == '-m':
        if monthpattern.match(arg):
            acctmonth = calcmonth(arg)
            targetmonth = arg
        else:
            print 'Invalid month'
            usage()
    elif opt == '-d':
        if not os.path.isdir(arg):
            print "Error:", arg, "is not an accessible directory"
            usage()
        dirs.append(arg)
    elif opt == '-c':
        cluster = arg
    elif opt == '-u':
        user = arg
    elif opt == '-j':
        jsonformat = 1
    elif opt == '-q':
        queue = arg
    elif opt == '-J':
        jname = arg
    elif opt == '-D':
        description = arg
    else:
        print 'Invalid option', opt, arg
        usage()

if len(dirs) == 0:
    envdir = os.getenv('CB_ENVDIR')
    if len(envdir) == 0:
        print 'AIP environment is not set'
        sys.exit(1)
    dir = os.path.dirname(envdir)
    if not os.path.isdir(dir):
        print 'AIP environment error. Cannot access', dir
        sys.exit(1)
    dirs.append(dir)

jobs = []

# print "Month:", acctmonth

def adddata(command, cluster='aip'):
    global jobs, clusters
    if queue != '':
        command.extend(['-q', queue])
    if jname != '':
        command.extend(['-J', jname])
    if description != '':
        command.extend(['-D', description])
    out = subprocess.check_output(command)
    try:
        detail = json.loads(out)
    except:
        return
    for j in detail:
        j['Cluster'] = cluster 
        
    jobs.extend(detail)
    clusters.append(cluster)

for dir in dirs:
    if not os.path.isdir(dir + '/work/data'):
        if os.path.isdir(dir + '/clusters'):
            root = dir + '/clusters'
            for d in os.listdir(root):
                if (not d == 'default') and os.path.isdir(os.path.join(root,d)):
                    if cluster != '' and cluster != d:
                        continue
                    os.environ['CB_ENVDIR'] = os.path.join(root, d, 'etc')
                    command = ['ctask', 'cacct.wrap', '-a', acctmonth, '-u', user]
                    adddata(command, d) 
        else:
            print 'AIP environment error.', dir + '/work/data', 'does not exist'
            sys.exit(1)
    else:
        command = ['cacct', '-f', dir + '/work/data', '-a', acctmonth, '-u', user]
        adddata(command)

bill = {}
details = []
bill['Month'] = targetmonth
bill['User'] = user
bill['Clusters'] = dirs
if queue == '':
    bill['Queues'] = 'all'
else:
    bill['Queues'] = queue

cpuhour = 0
memhour = 0
gpuhour = 0
apphours = []
corehour = 1.0/3600.0
gbhour = 1.0/(3600.0 * 1024.0 * 1024.0)
gb = 1.0/(1024.0 * 1024.0)
apps = {}

for job in jobs:
    jobbill = {}
    dt = datetime.datetime.fromtimestamp(job['EndTime'])
    jobbill['JobId'] = job['JobId']
    jobbill['EndDate'] = dt.strftime('%Y/%m/%d')
    if job['SlotTime'] == 0 or job['Slots'] == 0:
        continue
    jobbill['CPU_Hours'] = job['SlotTime'] * corehour
    jobruntime = job['SlotTime'] / job['Slots']
    jobbill['runTime'] = jobruntime * corehour
    jobbill['Mem_GB_Hours'] = job['MaxMem'] * gbhour
    ngpus = 0
    for alloc in job['Allocation']:
        for host in alloc['Hosts']:
            if 'Assigned Resource Units' in host:
                for aru in host['Assigned Resource Units']:
                    if 'gpu' in aru:
                        for n in aru['gpu']:
                            ngpus += 1
    if job['App'] != "":
        if job['App'] in apps:
            apps[job['App']] += jobbill['CPU_Hours']
        else:
            apps[job['App']] = jobbill['CPU_Hours']
        jobbill['App'] = job['App']
    else:
        jobbill['App'] = ''
    jobbill['User'] = job['User']
    jobbill['Queue'] = job['Queue']
    jobbill['GPU_Hours'] = ngpus * jobruntime * corehour
    jobbill['Cluster'] = job['Cluster']
    jobbill['JobName'] = job['Jobname']
    jobbill['JobDescription'] = job['JobDescription']
    gpuhour += jobbill['GPU_Hours']
    cpuhour += job['SlotTime']
    memhour += job['MaxMem']
    details.append(jobbill)

details.sort(key=lambda x: x['EndDate'])

bill['CPU_Hours'] = cpuhour * corehour
bill['Mem_GB_Hours'] = memhour * gbhour
bill['GPU_Hours'] = gpuhour
bill['App_Hours'] = apps
bill['Details'] = details
bill['Clusters'] = clusters

if jsonformat == 1:
    print json.dumps(bill)
else:
    bar = 80*'='
    extStr = ''
    if jname != '':
        extStr += ' Jobname: ' + jname
    if description != '':
        extStr += ' Job description: ' + description
    print 7*' ', 'BILL of', bill['Month'], 'for USER:', bill['User'], 'in QUEUES:', bill['Queues'], 'in', clusters
    if extStr != '':
        print 6*' ', extStr 
    print bar
    print 'Total CPU Hours:', round(bill['CPU_Hours'], 3)
    print 'Total memory GB Hours:', round(bill['Mem_GB_Hours'],3)
    print 'Total GPU Hours:', round(bill['GPU_Hours'], 3)
    print 'Application Hours:'
    for appname, apphour in apps.iteritems():
        print ' -', appname + ':\t', round(apphour,3)
    print bar
    print '       DETAILS'
    print bar
    formatstr = '{:<10} {:<12} {:<10} {:<10} {:<10} {:<10} {:<10} {:<12} {:<10} {:<8} {:<10} {:<12}'
    print formatstr.format('END_DATE', 'USER', 'JOBID', 'CPU(Hr)', 'MEM(GB-Hr)', 'GPU(Hr)', 'RUN(Hr)', 'APP', 'QUEUE', 'CLUSTER', 'JOBNAME','DESCRIPTION')
    for job in bill['Details']:
        print formatstr.format(job['EndDate'],job['User'],job['JobId'],\
             str(round(job['CPU_Hours'],4)),str(round(job['Mem_GB_Hours'],4)),\
             str(round(job['GPU_Hours'],4)),str(round(job['runTime'],4)),\
             job['App'], job['Queue'], job['Cluster'],\
             job['JobName'], job['JobDescription'])
