#!/usr/bin/python
# Copyright (c) Members of the EGEE Collaboration. 2004. 
# See http://www.eu-egee.org/partners/ for details on the copyright
# holders.  
#
# Licensed under the Apache License, Version 2.0 (the "License"); 
# you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
#
#     http://www.apache.org/licenses/LICENSE-2.0 
#
# Unless required by applicable law or agreed to in writing, software 
# distributed under the License is distributed on an "AS IS" BASIS, 
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
# See the License for the specific language governing permissions and 
# limitations under the License.

import sys
import logging
import logging.config

from SLURMInfoUtils import *


def main():
    
    if len(sys.argv) <> 2:
        sys.stderr.write("Usage: info-dynamic-slurm <config-file>\n")
        sys.exit(1)
    
    try:
        logging.config.fileConfig(sys.argv[1])
    except Exception, conf_log_err:
        logging.basicConfig(stream=sys.stderr)
    
    try:
        
        config = CommonUtils.readConfigFile(sys.argv[1])

        slurmCfg = SControlInfoHandler.parseConfiguration()
        
        infoContainer = SInfoHandler.parsePartInfo()
        
        memInfoContainer = SControlInfoHandler.parsePartInfo()
        
        if slurmCfg.acctEnabled:
            acctContainer = SAcctMgrHandler.parsePolicies(vomap=config['vomap'], cluster=slurmCfg.clustername)
        else:
            acctContainer = None
        
        if config['enable_glue_2_1']:
        
            usedGPUSlots = 0
            totalGPUSlots = 0
            
            nodesInfo = SControlInfoHandler.parseNodesInfo()
            for nodeName, gpuNum in nodesInfo.gpuTable.iteritems():
                try:

                    totalGPUSlots += gpuNum
                    smiHandler = NvidiaSMIHandler.parseGPUInfo(nodeName)
                    for nProcs in smiHandler.num_of_procs.values():
                        if nProcs > 0:
                            usedGPUSlots += 1

                except Exception, ex:
                    sys.stderr.write(repr(ex) + '\n')

            gpuStats = (totalGPUSlots, usedGPUSlots)
        else:
            gpuStats = None
            
        if config['outputformat'] <> "glue2":
            GLUE1Handler.process(config, infoContainer, acctContainer, slurmCfg)
        
        if config['outputformat'] <> "glue1":
            GLUE2Handler.process(config, infoContainer, memInfoContainer, acctContainer, slurmCfg, gpuStats)
        
    except:
        sys.stderr.write(CommonUtils.errorMsgFromTrace() + '\n')
        sys.exit(2)
        

if __name__ == "__main__":
    main()

