#!/usr/bin/python

import os
import sys
import time
import signal
import socket
import datetime
import ConfigParser

hostname = socket.gethostname()
ProbeConfig = None

import gratia.bdii_status.bdii_common as bdii_common

GratiaCore = None
ProbeConfig = None
ComputeElement = None
ComputeElementRecord = None
StorageElement = None
StorageElementRecord = None

default_bdii = 'ldap://is.grid.iu.edu:2170'

def sendToGratia(gratia_info):
    for info, records in gratia_info.items():
        pid = os.fork()
        if pid == 0: # I am the child
            signal.alarm(5*60)
            try:
                sendToGratia_child(info, records)
            except Exception, e:
                log.exception(e)
                os._exit(0)
        else: # I am parent
            try:
                os.waitpid(pid)
            except:
                pass

def sendToGratia_child(info, record_list):
    probeName, site = info

    try:
        GratiaCore.Initialize(ProbeConfig)
    except Exception, e:
        log.exception(e)
        return
    GratiaCore.Config.setSiteName(site)
    GratiaCore.Config.setMeterName(probeName)
    GratiaCore.Handshake()
    try:
        GratiaCore.SearchOutstandingRecord()
    except Exception, e:
        log.exception(e)
    GratiaCore.Reprocess()

    log.info("Gratia collector to use: %s" % GratiaCore.Config.get_SOAPHost())

    for record in record_list:
        log.info("Sending record for probe %s in site %s to Gratia: %s."% \
            (probeName, site, GratiaCore.Send(record)))

    os._exit(0)

def do_ce_info(cp, ce_entries):
    now = datetime.datetime.now()
    free_cpus = {}
    running_jobs = {}
    waiting_jobs = {}
    total_cpus = {}
    info = {}

    def update_info(info, cluster, attr, new_val):
        info[cluster][attr] = max(info[cluster].get(attr, 0), new_val)

    def add_info(info, cluster, attr, new_val):
        info[cluster][attr] = info[cluster].get(attr, 0) + new_val

    for entry in ce_entries:
        cluster = entry.glue['CEHostingCluster']
        cpus = int(entry.glue['CEInfoTotalCPUs'])
        free = int(entry.glue['CEStateFreeJobSlots'])
        waiting = int(entry.glue['CEStateWaitingJobs'])
        running = int(entry.glue['CEStateRunningJobs'])
        total = running+waiting
        lrmsType = entry.glue["CEInfoLRMSType"]
        if 'CEInfoLRMSVersion' not in entry.glue:
            log.warn("Incomplete GIP info for %s" % entry)
            continue
        lrmsVersion = entry.glue["CEInfoLRMSVersion"]
        if len(lrmsVersion) > 32:
            lrmsVersion=lrmsVersion[:32]
        if cluster not in info:
            info[cluster] = {'lrmsType'    : lrmsType,
                             'lrmsVersion' : lrmsVersion,
                             'hostName'    : cluster,
                             'time'        : now}
        update_info(info, cluster, 'totalCpus', cpus)
        update_info(info, cluster, 'freeCpus',  free)
        add_info(info, cluster, 'runningJobs', running)
        add_info(info, cluster, 'waitingJobs', waiting)

def do_se_info(cp):
    site_entries = bdii_common.read_bdii(cp, "(objectClass=GlueSite)")
    se_entries = bdii_common.read_bdii(cp, "(objectClass=GlueSE)")
    today = datetime.date.today()
    time_now = time.time()

    gratia_info = {}
    for entry in se_entries:
        try:
            site = bdii_common.join_FK(entry, site_entries,
                "SiteUniqueID")
        except ValueError, ve:
            log.warn("Unable to match SE:\n%s" % entry)
            continue
        try:
            site_name = site.glue['SiteName']
            total = int(entry.glue['SESizeTotal'])
            free = int(entry.glue['SESizeFree'])
            se_name = entry.glue['SEName']
        except:
            log.warn("Unable to parse attributes:\n%s" % entry)
            continue

        if total == 0 and free == 0:
            continue

        unique_id = entry.glue['SEUniqueID']
        probeName = 'bdii_storage:%s:%s' % (unique_id, hostname)
        GratiaCore.Config.setMeterName(probeName)
        GratiaCore.Config.setSiteName(se_name)
        se = StorageElement.StorageElement()
        space_unique_id = "%s:%s:%s" % (unique_id, "SE", se_name)
        se.UniqueID(space_unique_id)
        se.SE(se_name)
        se.Name(se_name)
        se.SpaceType("SE")
        se.Timestamp(time_now)
        se.Implementation(entry.glue['SEImplementationName'])
        se.Version(entry.glue['SEImplementationVersion'])
        se.Status(entry.glue['SEStatus'])
        se_list = gratia_info.setdefault((probeName, se_name), [])
        se_list.append(se)

        ser = StorageElementRecord.StorageElementRecord()
        ser.UniqueID(space_unique_id)
        ser.MeasurementType("raw")
        ser.StorageType("disk")
        ser.Timestamp(time_now)
        ser.TotalSpace(total*1000**3)
        ser.FreeSpace(free*1000**3)
        ser.UsedSpace((total-free)*1000**3)
        se_list.append(ser)

    sendToGratia(gratia_info)

def do_site_info(cp):
    ce_entries = bdii_common.read_bdii(cp, "(objectClass=GlueCE)")
    cluster_entries = bdii_common.read_bdii(cp,
        "(objectClass=GlueCluster)", multi=True)
    site_entries = bdii_common.read_bdii(cp, "(objectClass=GlueSite)")
    ce_map = {}
    ce_map2 = {}
    for ce in ce_entries:
        try:
            cluster = ce.glue['ForeignKey'].split('=')[1]
        except:
            continue
        ce_map[ce.glue['CEHostingCluster']] = cluster
        ce_map2[ce.glue['CEUniqueID']] = cluster
    cluster_map = {}
    for cluster in cluster_entries:
        try:
            site = None
            for key in cluster.glue['ForeignKey']:
                kind, name = key.split('=', 1)
                if kind != 'GlueSiteUniqueID':
                    continue
                site = name
            if not site:
                continue
        except:
            continue
        cluster_map[cluster.glue['ClusterName'][0]] = site
    site_map = {}
    for site in site_entries:
        site_map[site.glue['SiteUniqueID']] = site.glue['SiteName']
    return ce_map2, cluster_map, site_map

def findCE(vo_entry, ce_entries):
    for ce_entry in ce_entries:
        if ce_entry.dn[0] == vo_entry.glue["ChunkKey"]:
            return ce_entry
    raise ValueError("Corresponding CE not found for VO entry:\n%s" % vo_entry)

def main():

    # Load up the config file.
    opts = bdii_common.parse_opts()

    # Copy the Gratia libraries into our namespace
    global GratiaCore
    GratiaCore = bdii_common.GratiaCore
    global ProbeConfig
    ProbeConfig = bdii_common.ProbeConfig
    global ComputeElement
    ComputeElement = bdii_common.ComputeElement
    global ComputeElementRecord
    ComputeElementRecord = bdii_common.ComputeElementRecord
    global StorageElement
    StorageElement = bdii_common.StorageElement
    global StorageElementRecord
    StorageElementRecord = bdii_common.StorageElementRecord
    global log
    log = bdii_common.log

    if GratiaCore.Config.getConfigAttribute("EnableProbe") == "0":
        log.info("Probe is not enabled; exiting")
        return 0

    # Use the CLI option, ProbeConfig val, then default (in that order)
    bdii = GratiaCore.Config.getConfigAttribute("BDII")
    if opts.bdii:
        bdii = opts.bdii
    if not bdii:
        bdii = default_bdii
    cp = ConfigParser.ConfigParser()
    cp.add_section("bdii")
    cp.set("bdii", "endpoint", bdii)

    vo_entries = bdii_common.read_bdii(cp, "(objectClass=GlueVOView)")
    ce_entries = bdii_common.read_bdii(cp, "(objectClass=GlueCE)")
    now = datetime.datetime.now()
    time_now = time.time()

    gratia_info = {}

    ce_map, cluster_map, site_map = do_site_info(cp)
    sent_ce_entries = set()
    for entry in vo_entries:
        try:
            ce_entry = findCE(entry, ce_entries)
        except Exception, e:
            #print e
            #print entry
            log.error(e)
            continue
        try:
             info = {"time"        : now,
                "runningJobs"      : entry.glue["CEStateRunningJobs"],
                "totalCpus"        : ce_entry.glue["CEInfoTotalCPUs"],
                "freeJobSlots"     : entry.glue["CEStateFreeJobSlots"],
                "maxTotalJobs"     : ce_entry.glue["CEPolicyMaxTotalJobs"],
                "totalJobs"        : entry.glue["CEStateTotalJobs"],
                "status"           : ce_entry.glue["CEStateStatus"],
                "lrmsType"         : ce_entry.glue["CEInfoLRMSType"],
                "lrmsVersion"      : ce_entry.glue["CEInfoLRMSVersion"],
                "vo"               : entry.glue["VOViewLocalID"],
                "assignedJobSlots" : ce_entry.glue["CEPolicyAssignedJobSlots"],
                "freeCpus"         : ce_entry.glue["CEStateFreeCPUs"],
                "waitingJobs"      : entry.glue["CEStateWaitingJobs"],
                "maxRunningJobs"   : ce_entry.glue["CEPolicyMaxRunningJobs"],
                "hostName"         : ce_entry.glue["CEInfoHostName"],
                "queue"            : ce_entry.glue["CEName"]
               }
        except KeyError, ke:
            log.exception(ke)
            log.warn(ce_entry)
            continue

        ce_unique_id = ce_entry.glue['CEUniqueID']

        if ce_unique_id not in ce_map:
            log.warn("CE Unique ID %s is not in ce_map" % ce_unique_id)
            continue
        if ce_map[ce_unique_id] not in cluster_map:
            log.warn("Cluster ID %s is not in cluster_map" % \
                ce_map[ce_unique_id])
            continue
        if cluster_map[ce_map[ce_unique_id]] not in site_map:
            log.warn("Site ID %s is not in site_map" % cluster_map[ce_map[\
                ce_unique_id]])
            continue
        probeName = 'bdii_compute:%s:%s' % (ce_map[ce_unique_id], hostname)
        siteName = site_map[cluster_map[ce_map[ce_unique_id]]]
        GratiaCore.Config.setMeterName(probeName)
        GratiaCore.Config.setSiteName(siteName)

        ce_list = gratia_info.setdefault((probeName, siteName), [])

        if ce_unique_id not in sent_ce_entries:
            GratiaCore.Config.setMeterName(probeName)
            GratiaCore.Config.setSiteName(siteName)
            ce = ComputeElement.ComputeElement()
            ce.UniqueID(ce_unique_id)
            ce.CEName(ce_entry.glue['CEName'])
            ce.Cluster(ce_entry.glue['CEHostingCluster'])
            ce.HostName(ce_entry.glue['CEInfoHostName'])
            ce.Timestamp(time_now)
            ce.LrmsType(info['lrmsType'])
            ce.LrmsVersion(info['lrmsVersion'])
            ce.MaxRunningJobs(info['maxRunningJobs'])
            ce.MaxTotalJobs(info['maxTotalJobs'])
            ce.AssignedJobSlots(info['assignedJobSlots'])
            ce.Status(ce_entry.glue['CEStateStatus'])
            ce_list.append(ce)
            sent_ce_entries.add(ce_unique_id)

        cer = ComputeElementRecord.ComputeElementRecord()
        cer.UniqueID(ce_unique_id)
        cer.VO(entry.glue['VOViewLocalID'])
        cer.Timestamp(time_now)
        try:
            if int(info['runningJobs']) == 0 and int(info['totalJobs']) == 0 and \
                    int(info['waitingJobs']) == 0:
                continue
        except:
            raise
        cer.RunningJobs(info['runningJobs'])
        cer.TotalJobs(info['totalJobs'])
        cer.WaitingJobs(info['waitingJobs'])

        ce_list.append(cer)

    do_ce_info(cp, ce_entries)
    do_se_info(cp)

    ctr = 0
    for ce, entries in gratia_info:
        ctr += len(entries)
    log.info("Number of unique clusters: %s" % len(gratia_info))
    log.info("Number of unique records: %s" % ctr)

    sendToGratia(gratia_info)



if __name__ == '__main__':
    signal.alarm(10*60)
    main()

