#!/usr/bin/env python

import os
import sys
import time
import types
import socket
import logging
import urllib2
import datetime
import optparse
import ConfigParser
import logging.handlers
import xml.dom.minidom

hostname = socket.gethostname()
ProbeConfig = None

import gratia.bdii_status.bdii_common as bdii_common

GratiaCore = None
Subcluster = None

default_OIM_url = 'http://myosg.grid.iu.edu/misccpuinfo/xml?datasource=cpuinfo&count_sg_1=on'
default_bdii = 'ldap://is.grid.iu.edu:2170'

def get_cpu_normalizations():
    url = GratiaCore.Config.getConfigAttribute("OIMNormalizationUrl")
    if not url:
        url = default_OIM_url
    try:
        dom = xml.dom.minidom.parse(urllib2.urlopen(url))
    except:
        raise
        raise Exception("Unable to parse CPU XML data from OIM!")
    results = {}
    for cpu_dom in dom.getElementsByTagName("CPUInfo"):
        name_dom = cpu_dom.getElementsByTagName("Name")
        try:
            name = str(name_dom[0].firstChild.data)
        except:
            continue
        normalization_dom = cpu_dom.getElementsByTagName( \
            "NormalizationConstant")
        try:
            normalization = float(str(normalization_dom[0].firstChild.data))
        except:
            continue
        normalization *= 1000
        normalization = int(round(normalization))

        hs_dom = cpu_dom.getElementsByTagName("HEPSPEC")
        try:
            hs = float(str(hs_dom[0].firstChild.data))
        except:
            continue
        if not hs and normalization:
            hs = 4.0*normalization
        if hs and not normalization:
            normalization = int(round(hs / 4.0 * 1000.0))

        notes_dom= cpu_dom.getElementsByTagName("Notes")
        try:
            notes = str(notes_dom[0].firstChild.data)
        except:
            continue
        results[name] = (normalization, hs, notes)
    return results

def create_site_dict(ce_entries, cp):
    """
    Determine site ownership of CEs.
    """
    # Query BDII for the cluster and site entries
    cluster_entries = bdii_common.read_bdii(cp,
        query="(objectClass=GlueCluster)", multi=True)
    site_entries = bdii_common.read_bdii(cp,
        query="(objectClass=GlueSite)")
    ownership = {}

    # Determine the site's advertised ownership.
    for ce in ce_entries:
        try:
            # First, we join the CE to the cluster:
            cluster = bdii_common.join_FK(ce, cluster_entries,
                "ClusterUniqueID")
            #if ce.glue['CEHostingCluster'] == 'red.unl.edu':
            #    print cluster
            # Then, join the cluster to the site:
            site = bdii_common.join_FK(cluster, site_entries,
                "SiteUniqueID")
            ownership[ce.glue["CEHostingCluster"]] = site.glue["SiteName"]
        except Exception, e:
            print e
            pass

    return ownership

def create_count_dict(entries):
    """
    Convert a list of all the CE's LDAP entries to a dictionary which uses the 
    cluster name as the key and the estimated number of CPUs at the site as 
    the value.
    """
    cluster_info = {}
    for entry in entries:
        cpus = int(entry.glue['CEInfoTotalCPUs'])
        cluster = entry.glue['CEHostingCluster']
        if (cluster in cluster_info and cluster_info[cluster] <= cpus) or \
               (cluster not in cluster_info):
           cluster_info[cluster] = cpus
    return cluster_info

def correct_sc_info(cluster, cpu, sc_info, specint):
    """
    Correct the information in the subclusters and set the
    KSI2K value for the subcluster.
    """
    for sc in sc_info[cluster]:
        phy_cpus = int(sc.glue["SubClusterPhysicalCPUs"])
        log_cpus = int(sc.glue["SubClusterLogicalCPUs"])
        # If the physical CPUs were set by the admin instead of the
        # logical CPUs, then transfer that setting over.
        if phy_cpus > 4 and log_cpus in [0, 2, 4, 8]:
            sc.glue["SubClusterLogicalCPUs"] = phy_cpus
            log_cpus = phy_cpus
        # If the subcluster information looks suspiciously like
        # information for only one host, set it to the CPUs in
        # the cluster.  This is only active when there is one
        # subcluster (as sites like UCSD purposely put in even
        # very small sub clusters).
        if log_cpus in [2, 4, 8] and len(sc_info[cluster]) == 1:
            sc.glue["SubClusterLogicalCPUs"] = cpu
        # The benchmark values are hardcoded to 400 or 2000.  If the hardcoded
        # value has not been changed, then pull it from the lookup table
        # in the config file.
        if "HostBenchmarkSI00" not in sc.glue or \
                (int(sc.glue["HostBenchmarkSI00"]) in [400, 2000]):
            cpu_model = sc.glue["HostProcessorModel"]
            if cpu_model not in specint:
                raise KeyError("Unknown CPU model: %s" % cpu_model)
            si2k, hs, note = specint[cpu_model]
            if hs:
                si2k = hs * 250
            sc.glue["HostBenchmarkSI00"] = si2k
        # Finally, the KSI2K value is the per-core number multiplied by
        # the number of cores.
        ksi2k = int(sc.glue["HostBenchmarkSI00"])* \
            int(sc.glue["SubClusterLogicalCPUs"]) / 1000
        sc.glue["KSI2K"] = ksi2k

def sub_cluster_info(ce_list, cp):
    """
    Given a list of CE names (not LDAP entries), return a dictionary where
    the key is the CE name and the value is a list of SubClusters associated
    with that CE.
    """
    sc_entries = bdii_common.read_bdii(cp,
        query="(objectClass=GlueSubCluster)")
    sc_info = {}
    sc_total = {}
    for ce in ce_list:
        my_sc = sc_info.get(ce, [])
        sc_info[ce] = my_sc
        for sc in sc_entries:
            if "999999" in sc.glue['SubClusterLogicalCPUs']:
                continue
            desired_ck = "GlueClusterUniqueID=%s" % ce
            if "ChunkKey" in sc.glue and sc.glue["ChunkKey"] == desired_ck:
                my_sc.append(sc)
    return sc_info

def main():

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

    global GratiaCore
    GratiaCore = bdii_common.GratiaCore
    global ProbeConfig
    ProbeConfig = bdii_common.ProbeConfig
    global Subcluster
    Subcluster = bdii_common.Subcluster

    if GratiaCore.Config.getConfigAttribute("EnableProbe") == "0":
        print "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)

    # Read the CE entries from the BDII.    
    entries = bdii_common.read_bdii(cp, query="(&(objectClass=GlueCE))")
    
    cluster_info = create_count_dict(entries)

    # Map from the cluster hostname to the unique ID
    id_to_hostname = {}
    for entry in entries:
        fk = entry.glue['ForeignKey']
        info = fk.split("=", 1)
        if len(info) != 2:
            continue
        if info[0] != "GlueClusterUniqueID":
            print >> sys.stderr, "Entry has unknown cluster FK: %s" % entry
            continue
        id = info[1]
        id_to_hostname[id] = entry.glue['CEHostingCluster']

    sc_info = sub_cluster_info(id_to_hostname.keys(), cp)

    # For each unique cluster ID, map to one of the cluster hostnames
    new_sc_info = {}
    for id, info in sc_info.items():
        if id not in id_to_hostname:
            print >> sys.stderr, "ID %s has no matching cluster hostname." % id
            continue
        new_sc_info[id_to_hostname[id]] = info
    sc_info = new_sc_info

    specint = get_cpu_normalizations()

    now = datetime.datetime.now()

    site_ownership = create_site_dict(entries, cp)
    #print site_ownership

    gratia_info = {}

    for cluster, cpu in cluster_info.items():
        print "* Cluster: ", cluster
        if cluster not in sc_info:
            continue
        correct_sc_info(cluster, cpu, sc_info, specint)
        # Print out SC info.
        if len(sc_info[cluster]) > 0:
            print " - Sub-clusters:"
        for sc in sc_info[cluster]:
            print "   - %(SubClusterUniqueID)s, CPU Model:" \
                " %(HostProcessorModel)s, Cores: %(SubClusterLogicalCPUs)s," \
                " KSI2K: %(KSI2K)s" % sc.glue
            if int(sc.glue["HostBenchmarkSI00"]) != 400:
                cpu_si2k = int(sc.glue["HostBenchmarkSI00"])
            if cluster not in site_ownership:
                print >> sys.stderr, "Problem with %s site ownership; " \
                    "skipping." % cluster
                continue
            site = site_ownership[cluster]

            # Send the subcluster to Gratia
            GratiaCore.Config.setSiteName(site)
            GratiaCore.Config.setMeterName('bdii_subcluster:%s:%s' % (cluster,
                hostname))

            s = Subcluster.Subcluster()
            s.UniqueID(sc.glue['SubClusterUniqueID'])
            s.Name(sc.glue['SubClusterName'])
            s.Cluster(cluster)
            #s.Platform()
            s.OS(sc.glue['HostOperatingSystemName'])
            s.OSVersion(sc.glue['HostOperatingSystemRelease'])
            s.Cores(sc.glue['SubClusterLogicalCPUs'])
            s.Cpus(sc.glue['SubClusterPhysicalCPUs'])
            s.RAM(sc.glue['HostMainMemoryRAMSize'])
            s.Processor(sc.glue['HostProcessorModel'])
            s.BenchmarkName('SI2K')
            s.BenchmarkValue(cpu_si2k)
            try:
                smp_size = int(sc.glue['HostArchitectureSMPSize'])
                cpus = int(sc.glue['SubClusterPhysicalCPUs'])
                s.Hosts(cpus/smp_size)
            except:
                pass
            s.Timestamp(time.time())
            site_list = gratia_info.setdefault((site, cluster), [])
            site_list.append(s)

    sendToGratia(gratia_info)

def sendToGratia(gratia_info):
    for cluster, subclusters in gratia_info.items():
        pid = os.fork()
        if pid == 0: # I am the child
            sendToGratia_child(cluster, subclusters)
            return
        else: # I am parent
            os.wait()

def sendToGratia_child(cluster, sc_list):
    site, cluster = cluster

    try:
        GratiaCore.Initialize(ProbeConfig)
    except Exception, e:
        print e
        return

    GratiaCore.Config.setSiteName(site)
    GratiaCore.Config.setMeterName('bdii_subcluster:%s' % cluster)

    for s in sc_list:
        print "Sending subcluster of cluster %s in site %s to Gratia: %s."% \
            (cluster, site, GratiaCore.Send(s))
        
if __name__ == '__main__':
    main()


