#!/usr/bin/env python
#
# Gratia plugin for gLExec-GUMS 
#

import os
import pwd
import sys
import time
import random
import socket
import optparse

import gratia.glexec.gratia_glexec_parser as gratia_glexec_parser
import gratia.common.Gratia as Gratia
import gratia.common.GratiaCore as GratiaCore
import gratia.common.GratiaWrapper as GratiaWrapper
from gratia.common.GratiaCore import DebugPrint

def parse_opts():
            
    global ProbeConfig
            
    parser = optparse.OptionParser(usage="%prog [options] dir1 dir2")
    parser.add_option("-f", "--gratia_config", help="Location of the Gratia config; "
        "defaults to /etc/gratia/glexec/ProbeConfig.", dest="gratia_config",
        default="/etc/gratia/glexec/ProbeConfig")
    parser.add_option("-s", "--sleep", help="Do a random amount of sleep, up to the"
        " specified number of seconds before running.", dest="sleep",
        default=0, type="int")
    parser.add_option("-v", "--verbose", help="Enable verbose logging to stdout.",
        default=False, action="store_true", dest="verbose")

    opts, args = parser.parse_args()

    # Initialize Gratia
    if not opts.gratia_config or not os.path.exists(opts.gratia_config):
        raise Exception("Gratia config, %s, does not exist." % opts.gratia_config)
    GratiaCore.Config = GratiaCore.ProbeConfiguration(opts.gratia_config)

    if opts.verbose:
        GratiaCore.Config.set_DebugLevel(5)

    return opts, args

#
# Process transactions
#
def get_check_fname(data_dir):
    return os.path.join(data_dir,'glexec_plugin.chk')

def load_last_check(data_dir):
    check_fname=get_check_fname(data_dir)
    if os.path.exists(check_fname):
        fd=open(check_fname,"r")
        try:
            last_check_str=fd.read().strip()
        finally:
            fd.close()
        return long(last_check_str)
    else:
        return 0 #never done anything

def save_last_check(data_dir,last_check):
    check_fname=get_check_fname(data_dir)
    fd = open(check_fname,"w")
    try:
        fd.write("%il\n"%last_check);
    finally:
        fd.close()
    return

#
# Process data
#

def getCE(host_proxy):
    #currently glexec is running on the worker nodes where proxy
    #of ce host certificate is installed
    #it is not necessarily will be true in the future
    #so if host certificate proxy is unavailable we will assume
    #that we are running node on ce and return hostname instead

    # os.popen can generate deprecation warnings.  Simply replace.
    stdout_r, stdout_w = os.pipe()
    pid = os.fork()
    if pid == 0:
        # Child
        try:
            new_stderr_fd = os.dup(2)
            dev_null_fd = os.open("/dev/null", os.O_WRONLY)
            os.dup2(dev_null_fd, 2)
            os.close(dev_null_fd)
            os.close(stdout_r)
            os.dup2(stdout_w, 1)
            os.close(stdout_w)
            os.close(0)
            os.execl("grid-proxy-info", "grid-proxy-info", "-identity", "-f", str(host_proxy))
        finally:
            os._exit(1)

    os.close(stdout_w)
    stdout = os.read(stdout_r, 16*1024)
    os.close(stdout_r)
    exit_status = os.waitpid(pid, 0)
    
    if exit_status!=0:
	return get_host()

    return stdout.split("/CN=", 2)[-1]

# a cached way to convert uid to name
UID_DICT={}
def uid2name(uid):
    global UID_DICT
    if not UID_DICT.has_key(uid):
        try:
            UID_DICT[uid]=pwd.getpwuid(uid)[0]
        except:
            UID_DICT[uid]="uid%i"%uid
    return UID_DICT[uid]

def get_host():
    network_interface=socket.gethostbyname(socket.gethostname())
    local_hostname = socket.gethostbyaddr(network_interface)[0]
    return local_hostname[0:]

def send_one(el,
             host, # uname -n
             cename):
    r=Gratia.UsageRecord("BatchPilot")
    r.MachineName(cename)
    r.Host(host)
    r.LocalUserId(uid2name(el['jobuid'])) # uid number
    if el.has_key("DN"):
        r.DN(el["DN"])

    if el.has_key("FQAN"):
        # If we have an FQAN, then set both
        r.VOName(el["FQAN"])
        if el.has_key("VO"):
            r.ReportableVOName(el["VO"])
    elif el.has_key("VO"):
        # Otherwise, just set one.
        r.VOName(el["VO"])

    r.WallDuration(el['end']-el['start'])
    r.CpuDuration(el['usercpu'],'user')
    r.CpuDuration(el['syscpu'],'sys')
    r.StartTime(el['start'])
    r.EndTime(el['end'])
    #print Gratia.Send(r)
    Gratia.Send(r)
    #print host,r

#
# Main
#

def main():

    try:
        opts, dirs = parse_opts()
    except Exception, e:
        print >> sys.stderr, str(e)
        sys.exit(1)
        
    # Sanity checks for the probe's runtime environment.
    GratiaWrapper.CheckPreconditions()

    if opts.sleep:
        rnd = random.randint(1, int(opts.sleep)) 
        DebugPrint(2, "Sleeping for %d seconds before proceeding." % rnd)
        time.sleep(rnd)
    
    # Make sure we have an exclusive lock for this probe.
    GratiaWrapper.ExclusiveLock()

    rev =  Gratia.ExtractSvnRevision("$Revision: 4685 $")
    Gratia.RegisterReporter("glexec_meter.py", str(rev) + " (tag %%%RPMVERSION%%%)")
    GratiaCore.Initialize(opts.gratia_config)

    cename=getCE(Gratia.Config.get_CertificateFile())
    data_dir=Gratia.Config.get_DataFolder()
    logfile=Gratia.Config.getConfigAttribute('gLExecMonitorLog')

    last_check=load_last_check(data_dir)
    host=get_host()
    glexec_data=gratia_glexec_parser.parse_log(logfile,last_check+1)
    # find out only finished jobs
    ids=[]
    for id in glexec_data.keys():
        el=glexec_data[id]
        if el.has_key('end'):
            ids.append(id)

    # sort by termination time
    ids.sort(lambda e1,e2:cmp(glexec_data[e1]['end'],glexec_data[e2]['end']))

    max_end=last_check
    for id in ids:
        el=glexec_data[id]
        send_one(el,host,cename)
        if el['end']>max_end:
            max_end=el['end']
            save_last_check(data_dir,max_end)
    
if __name__== '__main__':
    main()
