source: trunk/jobmond/jobmond.py @ 660

Last change on this file since 660 was 660, checked in by ramonb, 12 years ago
  • updated for latest pbs_python
  • changed metric compilation
  • fixed some more indentation
  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 48.9 KB
RevLine 
[23]1#!/usr/bin/env python
[225]2#
3# This file is part of Jobmonarch
4#
[363]5# Copyright (C) 2006-2007  Ramon Bastiaans
[622]6# Copyright (C) 2007, 2009  Dave Love  (SGE code)
[225]7#
8# Jobmonarch is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or
11# (at your option) any later version.
12#
13# Jobmonarch is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with this program; if not, write to the Free Software
20# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21#
[228]22# SVN $Id: jobmond.py 660 2012-09-03 13:16:36Z ramonb $
[227]23#
[23]24
[471]25import sys, getopt, ConfigParser, time, os, socket, string, re
26import xdrlib, socket, syslog, xml, xml.sax
[318]27from xml.sax.handler import feature_namespaces
[622]28from collections import deque
[660]29from types import *
[318]30
[500]31VERSION='0.3.1'
[307]32
[471]33def usage( ver ):
34
[659]35    print 'jobmond %s' %VERSION
[471]36
[659]37    if ver:
38        return 0
[471]39
[659]40    print
41    print 'Purpose:'
42    print '  The Job Monitoring Daemon (jobmond) reports batch jobs information and statistics'
43    print '  to Ganglia, which can be viewed with Job Monarch web frontend'
44    print
45    print 'Usage:   jobmond [OPTIONS]'
46    print
47    print '  -c, --config=FILE  The configuration file to use (default: /etc/jobmond.conf)'
48    print '  -p, --pidfile=FILE Use pid file to store the process id'
49    print '  -h, --help     Print help and exit'
50    print '  -v, --version          Print version and exit'
51    print
[307]52
[212]53def processArgs( args ):
[26]54
[659]55    SHORT_L     = 'p:hvc:'
56    LONG_L      = [ 'help', 'config=', 'pidfile=', 'version' ]
[165]57
[659]58    global PIDFILE
59    PIDFILE     = None
[61]60
[659]61    config_filename = '/etc/jobmond.conf'
[354]62
[659]63    try:
[68]64
[659]65        opts, args  = getopt.getopt( args, SHORT_L, LONG_L )
[185]66
[659]67    except getopt.GetoptError, detail:
[212]68
[659]69        print detail
70        usage()
71        sys.exit( 1 )
[212]72
[659]73    for opt, value in opts:
[212]74
[659]75        if opt in [ '--config', '-c' ]:
76       
77            config_filename = value
[212]78
[659]79        if opt in [ '--pidfile', '-p' ]:
[212]80
[659]81            PIDFILE     = value
82       
83        if opt in [ '--help', '-h' ]:
[307]84 
[659]85            usage( False )
86            sys.exit( 0 )
[212]87
[659]88        if opt in [ '--version', '-v' ]:
[471]89
[659]90            usage( True )
91            sys.exit( 0 )
[471]92
[659]93    return loadConfig( config_filename )
[212]94
[622]95# Fixme:  This doesn't DTRT with commented-out bits of the file.  E.g.
96# it picked up a commented-out `mcast_join' and tried to use a
97# multicast channel when it shouldn't have done.
[520]98class GangliaConfigParser:
99
[659]100    def __init__( self, config_file ):
[520]101
[659]102        self.config_file    = config_file
[520]103
[659]104        if not os.path.exists( self.config_file ):
[520]105
[659]106            debug_msg( 0, "FATAL ERROR: gmond config '" + self.config_file + "' not found!" )
107            sys.exit( 1 )
[520]108
[659]109    def removeQuotes( self, value ):
[520]110
[659]111        clean_value = value
112        clean_value = clean_value.replace( "'", "" )
113        clean_value = clean_value.replace( '"', '' )
114        clean_value = clean_value.strip()
[520]115
[659]116        return clean_value
[520]117
[659]118    def getVal( self, section, valname ):
[520]119
[659]120        cfg_fp      = open( self.config_file )
121        section_start   = False
122        section_found   = False
123        value       = None
[520]124
[659]125        for line in cfg_fp.readlines():
[520]126
[659]127            if line.find( section ) != -1:
[520]128
[659]129                section_found   = True
[520]130
[659]131            if line.find( '{' ) != -1 and section_found:
[520]132
[659]133                section_start   = True
[520]134
[659]135            if line.find( '}' ) != -1 and section_found:
[520]136
[659]137                section_start   = False
138                section_found   = False
[520]139
[659]140            if line.find( valname ) != -1 and section_start:
[520]141
[659]142                value       = string.join( line.split( '=' )[1:], '' ).strip()
[520]143
[659]144        cfg_fp.close()
[520]145
[659]146        return value
[520]147
[659]148    def getInt( self, section, valname ):
[520]149
[659]150        value   = self.getVal( section, valname )
[520]151
[659]152        if not value:
153            return False
[520]154
[659]155        value   = self.removeQuotes( value )
[520]156
[659]157        return int( value )
[520]158
[659]159    def getStr( self, section, valname ):
[520]160
[659]161        value   = self.getVal( section, valname )
[520]162
[659]163        if not value:
164            return False
[520]165
[659]166        value   = self.removeQuotes( value )
[520]167
[659]168        return str( value )
[520]169
170def findGmetric():
171
[659]172    for dir in os.path.expandvars( '$PATH' ).split( ':' ):
[520]173
[659]174        guess   = '%s/%s' %( dir, 'gmetric' )
[520]175
[659]176        if os.path.exists( guess ):
[520]177
[659]178            return guess
[520]179
[659]180    return False
[520]181
[212]182def loadConfig( filename ):
183
[660]184    def getlist( cfg_string ):
[215]185
[660]186        my_list = [ ]
[215]187
[660]188        for item_txt in cfg_string.split( ',' ):
[215]189
[660]190                sep_char = None
[215]191
[660]192                item_txt = item_txt.strip()
[215]193
[660]194                for s_char in [ "'", '"' ]:
[215]195
[660]196                        if item_txt.find( s_char ) != -1:
[215]197
[660]198                                if item_txt.count( s_char ) != 2:
[215]199
[660]200                                        print 'Missing quote: %s' %item_txt
201                                        sys.exit( 1 )
[215]202
[660]203                                else:
[215]204
[660]205                                        sep_char = s_char
206                                        break
[215]207
[660]208                if sep_char:
[215]209
[660]210                        item_txt = item_txt.split( sep_char )[1]
[215]211
[660]212                my_list.append( item_txt )
[215]213
[660]214        return my_list
[215]215
[659]216    cfg     = ConfigParser.ConfigParser()
[212]217
[659]218    cfg.read( filename )
[212]219
[659]220    global DEBUG_LEVEL, DAEMONIZE, BATCH_SERVER, BATCH_POLL_INTERVAL
221    global GMOND_CONF, DETECT_TIME_DIFFS, BATCH_HOST_TRANSLATE
222    global BATCH_API, QUEUE, GMETRIC_TARGET, USE_SYSLOG
223    global SYSLOG_LEVEL, SYSLOG_FACILITY, GMETRIC_BINARY
[212]224
[659]225    DEBUG_LEVEL = cfg.getint( 'DEFAULT', 'DEBUG_LEVEL' )
[212]226
[659]227    DAEMONIZE   = cfg.getboolean( 'DEFAULT', 'DAEMONIZE' )
[212]228
[659]229    SYSLOG_LEVEL    = -1
230    SYSLOG_FACILITY = None
[377]231
[659]232    try:
233        USE_SYSLOG  = cfg.getboolean( 'DEFAULT', 'USE_SYSLOG' )
[212]234
[659]235    except ConfigParser.NoOptionError:
[373]236
[659]237        USE_SYSLOG  = True
[373]238
[659]239        debug_msg( 0, 'ERROR: no option USE_SYSLOG found: assuming yes' )
[373]240
[659]241    if USE_SYSLOG:
[373]242
[659]243        try:
244            SYSLOG_LEVEL    = cfg.getint( 'DEFAULT', 'SYSLOG_LEVEL' )
[373]245
[659]246        except ConfigParser.NoOptionError:
[373]247
[659]248            debug_msg( 0, 'ERROR: no option SYSLOG_LEVEL found: assuming level 0' )
249            SYSLOG_LEVEL    = 0
[373]250
[659]251        try:
[373]252
[659]253            SYSLOG_FACILITY = eval( 'syslog.LOG_' + cfg.get( 'DEFAULT', 'SYSLOG_FACILITY' ) )
[373]254
[659]255        except ConfigParser.NoOptionError:
[373]256
[659]257            SYSLOG_FACILITY = syslog.LOG_DAEMON
[373]258
[659]259            debug_msg( 0, 'ERROR: no option SYSLOG_FACILITY found: assuming facility DAEMON' )
[373]260
[659]261    try:
[373]262
[659]263        BATCH_SERVER        = cfg.get( 'DEFAULT', 'BATCH_SERVER' )
[212]264
[659]265    except ConfigParser.NoOptionError:
[265]266
[659]267        # Backwards compatibility for old configs
268        #
[265]269
[659]270        BATCH_SERVER        = cfg.get( 'DEFAULT', 'TORQUE_SERVER' )
271        api_guess       = 'pbs'
272   
273    try:
274   
275        BATCH_POLL_INTERVAL = cfg.getint( 'DEFAULT', 'BATCH_POLL_INTERVAL' )
[265]276
[659]277    except ConfigParser.NoOptionError:
[265]278
[659]279        # Backwards compatibility for old configs
280        #
[265]281
[659]282        BATCH_POLL_INTERVAL = cfg.getint( 'DEFAULT', 'TORQUE_POLL_INTERVAL' )
283        api_guess       = 'pbs'
284   
285    try:
[212]286
[659]287        GMOND_CONF      = cfg.get( 'DEFAULT', 'GMOND_CONF' )
[353]288
[659]289    except ConfigParser.NoOptionError:
[353]290
[659]291        # Not specified: assume /etc/gmond.conf
292        #
293        GMOND_CONF      = '/etc/gmond.conf'
[353]294
[659]295    ganglia_cfg     = GangliaConfigParser( GMOND_CONF )
[449]296
[659]297    # Let's try to find the GMETRIC_TARGET ourselves first from GMOND_CONF
298    #
299    gmetric_dest_ip     = ganglia_cfg.getStr( 'udp_send_channel', 'mcast_join' )
[449]300
[659]301    if not gmetric_dest_ip:
[449]302
[659]303        # Maybe unicast target then
304        #
305        gmetric_dest_ip     = ganglia_cfg.getStr( 'udp_send_channel', 'host' )
[449]306
[660]307        gmetric_dest_port   = ganglia_cfg.getStr( 'udp_send_channel', 'port' )
[520]308
[659]309    if gmetric_dest_ip and gmetric_dest_port:
[520]310
[659]311        GMETRIC_TARGET  = '%s:%s' %( gmetric_dest_ip, gmetric_dest_port )
312    else:
[520]313
[659]314        debug_msg( 0, "WARNING: Can't parse udp_send_channel from: '%s'" %GMOND_CONF )
[520]315
[659]316        # Couldn't figure it out: let's see if it's in our jobmond.conf
317        #
318        try:
[520]319
[659]320            GMETRIC_TARGET  = cfg.get( 'DEFAULT', 'GMETRIC_TARGET' )
[520]321
[659]322        # Guess not: now just give up
323        #
324        except ConfigParser.NoOptionError:
[520]325
[659]326            GMETRIC_TARGET  = None
[520]327
[659]328            debug_msg( 0, "ERROR: GMETRIC_TARGET not set: internal Gmetric handling aborted. Failing back to DEPRECATED use of gmond.conf/gmetric binary. This will slow down jobmond significantly!" )
[520]329
[659]330    gmetric_bin = findGmetric()
[520]331
[659]332    if gmetric_bin:
[520]333
[659]334        GMETRIC_BINARY      = gmetric_bin
335    else:
336        debug_msg( 0, "WARNING: Can't find gmetric binary anywhere in $PATH" )
[520]337
[659]338        try:
[520]339
[659]340            GMETRIC_BINARY      = cfg.get( 'DEFAULT', 'GMETRIC_BINARY' )
[520]341
[659]342        except ConfigParser.NoOptionError:
[520]343
[659]344            debug_msg( 0, "FATAL ERROR: GMETRIC_BINARY not set and not in $PATH" )
345            sys.exit( 1 )
[520]346
[659]347    DETECT_TIME_DIFFS   = cfg.getboolean( 'DEFAULT', 'DETECT_TIME_DIFFS' )
[212]348
[659]349    BATCH_HOST_TRANSLATE    = getlist( cfg.get( 'DEFAULT', 'BATCH_HOST_TRANSLATE' ) )
[215]350
[659]351    try:
[256]352
[659]353        BATCH_API   = cfg.get( 'DEFAULT', 'BATCH_API' )
[266]354
[659]355    except ConfigParser.NoOptionError, detail:
[266]356
[659]357        if BATCH_SERVER and api_guess:
[354]358
[659]359            BATCH_API   = api_guess
360        else:
361            debug_msg( 0, "FATAL ERROR: BATCH_API not set and can't make guess" )
362            sys.exit( 1 )
[317]363
[659]364    try:
[317]365
[659]366        QUEUE       = getlist( cfg.get( 'DEFAULT', 'QUEUE' ) )
[317]367
[659]368    except ConfigParser.NoOptionError, detail:
[317]369
[659]370        QUEUE       = None
[353]371
[659]372    return True
[212]373
[507]374def fqdn_parts (fqdn):
[520]375
[659]376    """Return pair of host and domain for fully-qualified domain name arg."""
[520]377
[659]378    parts = fqdn.split (".")
[520]379
[659]380    return (parts[0], string.join(parts[1:], "."))
[507]381
[253]382METRIC_MAX_VAL_LEN = 900
383
[61]384class DataProcessor:
[355]385
[659]386    """Class for processing of data"""
[61]387
[659]388    binary = None
[61]389
[659]390    def __init__( self, binary=None ):
[355]391
[659]392        """Remember alternate binary location if supplied"""
[61]393
[659]394        global GMETRIC_BINARY
[449]395
[659]396        if binary:
397            self.binary = binary
[61]398
[659]399        if not self.binary:
400            self.binary = GMETRIC_BINARY
[449]401
[659]402        # Timeout for XML
403        #
404        # From ganglia's documentation:
405        #
406        # 'A metric will be deleted DMAX seconds after it is received, and
407            # DMAX=0 means eternal life.'
[61]408
[659]409        self.dmax = str( int( int( BATCH_POLL_INTERVAL ) * 2 ) )
[80]410
[659]411        if GMOND_CONF:
[354]412
[659]413            incompatible = self.checkGmetricVersion()
[61]414
[659]415            if incompatible:
[355]416
[659]417                debug_msg( 0, 'Gmetric version not compatible, please upgrade to at least 3.0.1' )
418                sys.exit( 1 )
[65]419
[659]420    def checkGmetricVersion( self ):
[355]421
[659]422        """
423        Check version of gmetric is at least 3.0.1
424        for the syntax we use
425        """
[65]426
[659]427        global METRIC_MAX_VAL_LEN
[255]428
[659]429        incompatible    = 0
[341]430
[659]431        gfp     = os.popen( self.binary + ' --version' )
432        lines       = gfp.readlines()
[65]433
[659]434        gfp.close()
[355]435
[659]436        for line in lines:
[355]437
[659]438            line = line.split( ' ' )
[65]439
[659]440            if len( line ) == 2 and str( line ).find( 'gmetric' ) != -1:
441           
442                gmetric_version = line[1].split( '\n' )[0]
[65]443
[659]444                version_major   = int( gmetric_version.split( '.' )[0] )
445                version_minor   = int( gmetric_version.split( '.' )[1] )
446                version_patch   = int( gmetric_version.split( '.' )[2] )
[65]447
[659]448                incompatible    = 0
[65]449
[659]450                if version_major < 3:
[65]451
[659]452                    incompatible = 1
453               
454                elif version_major == 3:
[65]455
[659]456                    if version_minor == 0:
[65]457
[659]458                        if version_patch < 1:
459                       
460                            incompatible = 1
[65]461
[659]462                        # Gmetric 3.0.1 >< 3.0.3 had a bug in the max metric length
463                        #
464                        if version_patch < 3:
[255]465
[659]466                            METRIC_MAX_VAL_LEN = 900
[255]467
[659]468                        elif version_patch >= 3:
[255]469
[659]470                            METRIC_MAX_VAL_LEN = 1400
[255]471
[659]472        return incompatible
[65]473
[659]474    def multicastGmetric( self, metricname, metricval, valtype='string', units='' ):
[355]475
[659]476        """Call gmetric binary and multicast"""
[65]477
[659]478        cmd = self.binary
[65]479
[659]480        if GMETRIC_TARGET:
[61]481
[659]482            GMETRIC_TARGET_HOST = GMETRIC_TARGET.split( ':' )[0]
483            GMETRIC_TARGET_PORT = GMETRIC_TARGET.split( ':' )[1]
[353]484
[659]485            metric_debug        = "[gmetric] name: %s - val: %s - dmax: %s" %( str( metricname ), str( metricval ), str( self.dmax ) )
[353]486
[659]487            debug_msg( 10, printTime() + ' ' + metric_debug)
[353]488
[659]489            gm = Gmetric( GMETRIC_TARGET_HOST, GMETRIC_TARGET_PORT )
[353]490
[659]491            gm.send( str( metricname ), str( metricval ), str( self.dmax ), valtype, units )
[353]492
[659]493        else:
494            try:
495                cmd = cmd + ' -c' + GMOND_CONF
[353]496
[659]497            except NameError:
[353]498
[659]499                debug_msg( 10, 'Assuming /etc/gmond.conf for gmetric cmd (omitting)' )
[353]500
[659]501            cmd = cmd + ' -n' + str( metricname )+ ' -v"' + str( metricval )+ '" -t' + str( valtype ) + ' -d' + str( self.dmax )
[353]502
[659]503            if len( units ) > 0:
[409]504
[659]505                cmd = cmd + ' -u"' + units + '"'
[409]506
[659]507            debug_msg( 10, printTime() + ' ' + cmd )
[353]508
[659]509            os.system( cmd )
[353]510
[318]511class DataGatherer:
[23]512
[659]513    """Skeleton class for batch system DataGatherer"""
[256]514
[659]515    def printJobs( self, jobs ):
[355]516
[659]517        """Print a jobinfo overview"""
[318]518
[659]519        for name, attrs in self.jobs.items():
[318]520
[659]521            print 'job %s' %(name)
[318]522
[659]523            for name, val in attrs.items():
[318]524
[659]525                print '\t%s = %s' %( name, val )
[318]526
[659]527    def printJob( self, jobs, job_id ):
[355]528
[659]529        """Print job with job_id from jobs"""
[318]530
[659]531        print 'job %s' %(job_id)
[318]532
[659]533        for name, val in jobs[ job_id ].items():
[318]534
[659]535            print '\t%s = %s' %( name, val )
[318]536
[660]537    def getAttr( self, d, name ):
[507]538
[659]539        """Return certain attribute from dictionary, if exists"""
[507]540
[660]541        if d.has_key( name ):
[507]542
[660]543            if type( d[ name ] ) == ListType:
[507]544
[660]545                return string.join( d[ name ], ' ' )
546
547            return d[ name ]
548       
549        return ''
550
[659]551    def jobDataChanged( self, jobs, job_id, attrs ):
[507]552
[659]553        """Check if job with attrs and job_id in jobs has changed"""
[507]554
[659]555        if jobs.has_key( job_id ):
[507]556
[659]557            oldData = jobs[ job_id ]   
558        else:
559            return 1
[507]560
[659]561        for name, val in attrs.items():
[507]562
[659]563            if oldData.has_key( name ):
[507]564
[659]565                if oldData[ name ] != attrs[ name ]:
[507]566
[659]567                    return 1
[507]568
[659]569            else:
570                return 1
[507]571
[659]572        return 0
[507]573
[659]574    def submitJobData( self ):
[507]575
[659]576        """Submit job info list"""
[507]577
[659]578        global BATCH_API
[512]579
[659]580        self.dp.multicastGmetric( 'MONARCH-HEARTBEAT', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
[507]581
[659]582        running_jobs    = 0
583        queued_jobs = 0
[507]584
[659]585        # Count how many running/queued jobs we found
[507]586                #
[659]587        for jobid, jobattrs in self.jobs.items():
[507]588
[659]589            if jobattrs[ 'status' ] == 'Q':
[507]590
[659]591                queued_jobs += 1
[507]592
[659]593            elif jobattrs[ 'status' ] == 'R':
[507]594
[659]595                running_jobs += 1
[507]596
[659]597        # Report running/queued jobs as seperate metric for a nice RRD graph
[507]598                #
[659]599        self.dp.multicastGmetric( 'MONARCH-RJ', str( running_jobs ), 'uint32', 'jobs' )
600        self.dp.multicastGmetric( 'MONARCH-QJ', str( queued_jobs ), 'uint32', 'jobs' )
[507]601
[659]602        # Report down/offline nodes in batch (PBS only ATM)
603        #
604        if BATCH_API == 'pbs':
[512]605
[659]606            domain      = fqdn_parts( socket.getfqdn() )[1]
[514]607
[659]608            downed_nodes    = list()
609            offline_nodes   = list()
610       
611            l       = ['state']
612       
613            for name, node in self.pq.getnodes().items():
[512]614
[660]615                if 'down' in node[ 'state' ]:
[512]616
[659]617                    downed_nodes.append( name )
[512]618
[660]619                if 'offline' in node[ 'state' ]:
[512]620
[659]621                    offline_nodes.append( name )
[512]622
[659]623            downnodeslist       = do_nodelist( downed_nodes )
624            offlinenodeslist    = do_nodelist( offline_nodes )
[512]625
[659]626            down_str    = 'nodes=%s domain=%s reported=%s' %( string.join( downnodeslist, ';' ), domain, str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
627            offl_str    = 'nodes=%s domain=%s reported=%s' %( string.join( offlinenodeslist, ';' ), domain, str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
628            self.dp.multicastGmetric( 'MONARCH-DOWN'   , down_str )
629            self.dp.multicastGmetric( 'MONARCH-OFFLINE', offl_str )
[514]630
[659]631        # Now let's spread the knowledge
632        #
633        for jobid, jobattrs in self.jobs.items():
[507]634
[659]635            # Make gmetric values for each job: respect max gmetric value length
636            #
[660]637            gmetrics     = self.compileGmetricVal( jobid, jobattrs )
[507]638
[660]639            for g_name, g_val in gmetrics.items():
[507]640
[660]641                self.dp.multicastGmetric( g_name, g_val )
[507]642
[659]643    def compileGmetricVal( self, jobid, jobattrs ):
[507]644
[660]645        """Create gmetric name/value pairs of jobinfo"""
[507]646
[660]647        gmetrics = { }
[507]648
[659]649        for val_name, val_value in jobattrs.items():
[507]650
[660]651            gmetric_sequence = 0
[507]652
[660]653            if len( val_value ) > METRIC_MAX_VAL_LEN:
[507]654
[660]655                while len( val_value ) > METRIC_MAX_VAL_LEN:
[507]656
[660]657                    gmetric_value   = val_value[:METRIC_MAX_VAL_LEN]
658                    val_value       = val_value[METRIC_MAX_VAL_LEN:]
[507]659
[660]660                    gmetric_name    = 'MONARCHJOB$%s$%s$%s' %( jobid, string.upper(val_name), gmetric_sequence )
[507]661
[660]662                    gmetrics[ gmetric_name ] = gmetric_value
[507]663
[660]664                    gmetric_sequence = gmetric_sequence + 1
665            else:
666                gmetric_value   = val_value
[507]667
[660]668                gmetric_name    = 'MONARCH$%s$%s$%s' %( jobid, string.upper(val_name), gmetric_sequence )
[507]669
[660]670                gmetrics[ gmetric_name ] = gmetric_value
[507]671
[660]672        return gmetrics
[507]673
[660]674    def daemon( self ):
[507]675
[660]676        """Run as daemon forever"""
[507]677
[660]678        # Fork the first child
679        #
680        pid = os.fork()
681        if pid > 0:
682                sys.exit(0)  # end parent
[507]683
[660]684        # creates a session and sets the process group ID
685        #
686        os.setsid()
[507]687
[660]688        # Fork the second child
689        #
690        pid = os.fork()
691        if pid > 0:
692                sys.exit(0)  # end parent
[507]693
[659]694        write_pidfile()
[318]695
[660]696        # Go to the root directory and set the umask
697        #
698        os.chdir('/')
699        os.umask(0)
[318]700
[660]701        sys.stdin.close()
702        sys.stdout.close()
703        sys.stderr.close()
[318]704
[660]705        os.open('/dev/null', os.O_RDWR)
706        os.dup2(0, 1)
707        os.dup2(0, 2)
[318]708
[660]709        self.run()
[318]710
[660]711    def run( self ):
[355]712
[660]713        """Main thread"""
[256]714
[660]715        while ( 1 ):
[659]716       
717            self.getJobData()
718            self.submitJobData()
719            time.sleep( BATCH_POLL_INTERVAL )   
[256]720
[622]721# SGE code by Dave Love <fx@gnu.org>.  Tested with SGE 6.0u8 and 6.0u11.  May
722# work with SGE 6.1 (else should be easily fixable), but definitely doesn't
723# with 6.2.  See also the fixmes.
[256]724
[507]725class NoJobs (Exception):
[659]726    """Exception raised by empty job list in qstat output."""
727    pass
[256]728
[507]729class SgeQstatXMLParser(xml.sax.handler.ContentHandler):
[659]730    """SAX handler for XML output from Sun Grid Engine's `qstat'."""
[318]731
[659]732    def __init__(self):
733        self.value = ""
734        self.joblist = []
735        self.job = {}
736        self.queue = ""
737        self.in_joblist = False
738        self.lrequest = False
739        self.eltq = deque()
740        xml.sax.handler.ContentHandler.__init__(self)
[318]741
[659]742    # The structure of the output is as follows (for SGE 6.0).  It's
743    # similar for 6.1, but radically different for 6.2, and is
744    # undocumented generally.  Unfortunately it's voluminous, and probably
745    # doesn't scale to large clusters/queues.
[318]746
[659]747    # <detailed_job_info  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
748    #   <djob_info>
749    #     <qmaster_response>  <!-- job -->
750    #       ...
751    #       <JB_ja_template> 
752    #         <ulong_sublist>
753    #         ...             <!-- start_time, state ... -->
754    #         </ulong_sublist>
755    #       </JB_ja_template> 
756    #       <JB_ja_tasks>
757    #         <ulong_sublist>
758    #           ...           <!-- task info
759    #         </ulong_sublist>
760    #         ...
761    #       </JB_ja_tasks>
762    #       ...
763    #     </qmaster_response>
764    #   </djob_info>
765    #   <messages>
766    #   ...
[318]767
[659]768    # NB.  We might treat each task as a separate job, like
769    # straight qstat output, but the web interface expects jobs to
770    # be identified by integers, not, say, <job number>.<task>.
[318]771
[659]772    # So, I lied.  If the job list is empty, we get invalid XML
773    # like this, which we need to defend against:
[318]774
[659]775    # <unknown_jobs  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
776    #   <>
777    #     <ST_name>*</ST_name>
778    #   </>
779    # </unknown_jobs>
[318]780
[659]781    def startElement(self, name, attrs):
782        self.value = ""
783        if name == "djob_info": # job list
784            self.in_joblist = True
785        # The job container is "qmaster_response" in SGE 6.0
786        # and 6.1, but "element" in 6.2.  This is only the very
787        # start of what's necessary for 6.2, though (sigh).
788        elif (name == "qmaster_response" or name == "element") \
789                and self.eltq[-1] == "djob_info": # job
790            self.job = {"job_state": "U", "slots": 0,
791                    "nodes": [], "queued_timestamp": "",
792                    "queued_timestamp": "", "queue": "",
793                    "ppn": "0", "RN_max": 0,
794                    # fixme in endElement
795                    "requested_memory": 0, "requested_time": 0
796                    }
797            self.joblist.append(self.job)
798        elif name == "qstat_l_requests": # resource request
799            self.lrequest = True
800        elif name == "unknown_jobs":
801            raise NoJobs
802        self.eltq.append (name)
[318]803
[659]804    def characters(self, ch):
805        self.value += ch
[318]806
[659]807    def endElement(self, name): 
808        """Snarf job elements contents into job dictionary.
809           Translate keys if appropriate."""
[318]810
[659]811        name_trans = {
812          "JB_job_number": "number",
813          "JB_job_name": "name", "JB_owner": "owner",
814          "queue_name": "queue", "JAT_start_time": "start_timestamp",
815          "JB_submission_time": "queued_timestamp"
816          }
817        value = self.value
818        self.eltq.pop ()
[318]819
[659]820        if name == "djob_info":
821            self.in_joblist = False
822            self.job = {}
823        elif name == "JAT_master_queue":
824            self.job["queue"] = value.split("@")[0]
825        elif name == "JG_qhostname":
826            if not (value in self.job["nodes"]):
827                self.job["nodes"].append(value)
828        elif name == "JG_slots": # slots in use
829            self.job["slots"] += int(value)
830        elif name == "RN_max": # requested slots (tasks or parallel)
831            self.job["RN_max"] = max (self.job["RN_max"],
832                          int(value))
833        elif name == "JAT_state": # job state (bitwise or)
834            value = int (value)
835            # Status values from sge_jobL.h
836            #define JIDLE                   0x00000000
837            #define JHELD                   0x00000010
838            #define JMIGRATING              0x00000020
839            #define JQUEUED                 0x00000040
840            #define JRUNNING                0x00000080
841            #define JSUSPENDED              0x00000100
842            #define JTRANSFERING            0x00000200
843            #define JDELETED                0x00000400
844            #define JWAITING                0x00000800
845            #define JEXITING                0x00001000
846            #define JWRITTEN                0x00002000
847            #define JSUSPENDED_ON_THRESHOLD 0x00010000
848            #define JFINISHED               0x00010000
849            if value & 0x80:
850                self.job["status"] = "R"
851            elif value & 0x40:
852                self.job["status"] = "Q"
853            else:
854                self.job["status"] = "O" # `other'
855        elif name == "CE_name" and self.lrequest and self.value in \
856                ("h_cpu", "s_cpu", "cpu", "h_core", "s_core"):
857            # We're in a container for an interesting resource
858            # request; record which type.
859            self.lrequest = self.value
860        elif name == "CE_doubleval" and self.lrequest:
861            # if we're in a container for an interesting
862            # resource request, use the maxmimum of the hard
863            # and soft requests to record the requested CPU
864            # or core.  Fixme:  I'm not sure if this logic is
865            # right.
866            if self.lrequest in ("h_core", "s_core"):
867                self.job["requested_memory"] = \
868                    max (float (value),
869                     self.job["requested_memory"])
870            # Fixme:  Check what cpu means, c.f [hs]_cpu.
871            elif self.lrequest in ("h_cpu", "s_cpu", "cpu"):
872                self.job["requested_time"] = \
873                    max (float (value),
874                     self.job["requested_time"])
875        elif name == "qstat_l_requests":
876            self.lrequest = False
877        elif self.job and self.in_joblist:
878            if name in name_trans:
879                name = name_trans[name]
880                self.job[name] = value
[318]881
[507]882# Abstracted from PBS original.
883# Fixme:  Is it worth (or appropriate for PBS) sorting the result?
[520]884#
885def do_nodelist( nodes ):
886
[659]887    """Translate node list as appropriate."""
[520]888
[659]889    nodeslist       = [ ]
890    my_domain       = fqdn_parts( socket.getfqdn() )[1]
[520]891
[659]892    for node in nodes:
[520]893
[659]894        host        = node.split( '/' )[0] # not relevant for SGE
895        h, host_domain  = fqdn_parts(host)
[520]896
[659]897        if host_domain == my_domain:
[520]898
[659]899            host    = h
[520]900
[659]901        if nodeslist.count( host ) == 0:
[520]902
[659]903            for translate_pattern in BATCH_HOST_TRANSLATE:
[520]904
[659]905                if translate_pattern.find( '/' ) != -1:
[520]906
[659]907                    translate_orig  = \
908                        translate_pattern.split( '/' )[1]
909                    translate_new   = \
910                        translate_pattern.split( '/' )[2]
911                    host = re.sub( translate_orig,
912                               translate_new, host )
913            if not host in nodeslist:
914                nodeslist.append( host )
915    return nodeslist
[318]916
917class SgeDataGatherer(DataGatherer):
918
[659]919    jobs = {}
[61]920
[659]921    def __init__( self ):
922        self.jobs = {}
923        self.timeoffset = 0
924        self.dp = DataProcessor()
[318]925
[659]926    def getJobData( self ):
927        """Gather all data on current jobs in SGE"""
[318]928
[659]929        import popen2
[318]930
[659]931        self.cur_time = 0
932        queues = ""
933        if QUEUE:   # only for specific queues
934            # Fixme:  assumes queue names don't contain single
935            # quote or comma.  Don't know what the SGE rules are.
936            queues = " -q '" + string.join (QUEUE, ",") + "'"
937        # Note the comment in SgeQstatXMLParser about scaling with
938        # this method of getting data.  I haven't found better one.
939        # Output with args `-xml -ext -f -r' is easier to parse
940        # in some ways, harder in others, but it doesn't provide
941        # the submission time (at least SGE 6.0).  The pipeline
942        # into sed corrects bogus XML observed with a configuration
943        # of SGE 6.0u8, which otherwise causes the parsing to hang.
944        piping = popen2.Popen3("qstat -u '*' -j '*' -xml | \
[622]945sed -e 's/reported usage>/reported_usage>/g' -e 's;<\/*JATASK:.*>;;'" \
[659]946                           + queues, True)
947        qstatparser = SgeQstatXMLParser()
948        parse_err = 0
949        try:
950            xml.sax.parse(piping.fromchild, qstatparser)
951        except NoJobs:
952            pass
953        except:
954            parse_err = 1
955            if piping.wait():
[660]956                debug_msg(10,
[659]957                  "qstat error, skipping until next polling interval: "
958                  + piping.childerr.readline())
[660]959                return None
960            elif parse_err:
961                debug_msg(10, "Bad XML output from qstat"())
962                exit (1)
[659]963        for f in piping.fromchild, piping.tochild, piping.childerr:
964            f.close()
965        self.cur_time = time.time()
966        jobs_processed = []
967        for job in qstatparser.joblist:
968            job_id = job["number"]
969            if job["status"] in [ 'Q', 'R' ]:
970                jobs_processed.append(job_id)
971            if job["status"] == "R":
972                job["nodes"] = do_nodelist (job["nodes"])
973                # Fixme: why is job["nodes"] sometimes null?
974                try:
975                    # Fixme: Is this sensible?  The
976                    # PBS-type PPN isn't something you use
977                    # with SGE.
978                    job["ppn"] = float(job["slots"]) / \
979                        len(job["nodes"])
980                except:
981                    job["ppn"] = 0
982                if DETECT_TIME_DIFFS:
983                    # If a job start is later than our
984                    # current date, that must mean
985                    # the SGE server's time is later
986                    # than our local time.
987                    start_timestamp = \
988                        int (job["start_timestamp"])
989                    if start_timestamp > \
990                            int(self.cur_time) + \
991                            int(self.timeoffset):
[318]992
[659]993                        self.timeoffset = \
994                            start_timestamp - \
995                            int(self.cur_time)
996            else:
997                # fixme: Note sure what this should be:
998                job["ppn"] = job["RN_max"]
999                job["nodes"] = "1"
[318]1000
[659]1001            myAttrs = {}
1002            for attr in ["name", "queue", "owner",
1003                     "requested_time", "status",
1004                     "requested_memory", "ppn",
1005                     "start_timestamp", "queued_timestamp"]:
1006                myAttrs[attr] = str(job[attr])
1007            myAttrs["nodes"] = job["nodes"]
1008            myAttrs["reported"] = str(int(self.cur_time) + \
1009                          int(self.timeoffset))
1010            myAttrs["domain"] = fqdn_parts(socket.getfqdn())[1]
1011            myAttrs["poll_interval"] = str(BATCH_POLL_INTERVAL)
[318]1012
[659]1013            if self.jobDataChanged(self.jobs, job_id, myAttrs) \
1014                    and myAttrs["status"] in ["R", "Q"]:
1015                self.jobs[job_id] = myAttrs
1016        for id, attrs in self.jobs.items():
1017            if id not in jobs_processed:
1018                del self.jobs[id]
[318]1019
[524]1020# LSF code by Mahmoud Hanafi <hanafim@users.sourceforge.nt>
1021# Requres LSFObject http://sourceforge.net/projects/lsfobject
1022#
1023class LsfDataGatherer(DataGatherer):
[525]1024
[524]1025        """This is the DataGatherer for LSf"""
1026
1027        global lsfObject
1028
1029        def __init__( self ):
[525]1030
[524]1031                self.jobs = { }
1032                self.timeoffset = 0
1033                self.dp = DataProcessor()
1034                self.initLsfQuery()
1035
[525]1036        def _countDuplicatesInList( self, dupedList ):
1037
[660]1038            countDupes  = { }
[525]1039
[660]1040            for item in dupedList:
[525]1041
[660]1042                if not countDupes.has_key( item ):
[525]1043
[660]1044                    countDupes[ item ]  = 1
1045                else:
1046                    countDupes[ item ]  = countDupes[ item ] + 1
[525]1047
[660]1048            dupeCountList   = [ ]
[525]1049
[660]1050            for item, count in countDupes.items():
[525]1051
[660]1052                dupeCountList.append( ( item, count ) )
[525]1053
[660]1054            return dupeCountList
[524]1055#
1056#lst = ['I1','I2','I1','I3','I4','I4','I7','I7','I7','I7','I7']
1057#print _countDuplicatesInList(lst)
1058#[('I1', 2), ('I3', 1), ('I2', 1), ('I4', 2), ('I7', 5)]
1059########################
1060
1061        def initLsfQuery( self ):
1062                self.pq = None
1063                self.pq = lsfObject.jobInfoEntObject()
1064
1065        def getJobData( self, known_jobs="" ):
1066                """Gather all data on current jobs in LSF"""
1067                if len( known_jobs ) > 0:
1068                        jobs = known_jobs
1069                else:
1070                        jobs = { }
1071                joblist = {}
1072                joblist = self.pq.getJobInfo()
1073                nodelist = ''
1074
1075                self.cur_time = time.time()
1076
1077                jobs_processed = [ ]
1078
1079                for name, attrs in joblist.items():
1080                        job_id = str(name)
1081                        jobs_processed.append( job_id )
1082                        name = self.getAttr( attrs, 'jobName' )
1083                        queue = self.getAttr( self.getAttr( attrs, 'submit') , 'queue' )
1084                        owner = self.getAttr( attrs, 'user' )
1085
1086### THIS IS THE rLimit List index values
1087#define LSF_RLIMIT_CPU      0            /* cpu time in milliseconds */
1088#define LSF_RLIMIT_FSIZE    1            /* maximum file size */
1089#define LSF_RLIMIT_DATA     2            /* data size */
1090#define LSF_RLIMIT_STACK    3            /* stack size */
1091#define LSF_RLIMIT_CORE     4            /* core file size */
1092#define LSF_RLIMIT_RSS      5            /* resident set size */
1093#define LSF_RLIMIT_NOFILE   6            /* open files */
1094#define LSF_RLIMIT_OPEN_MAX 7            /* (from HP-UX) */
1095#define LSF_RLIMIT_VMEM     8            /* maximum swap mem */
1096#define LSF_RLIMIT_SWAP     8
1097#define LSF_RLIMIT_RUN      9            /* max wall-clock time limit */
1098#define LSF_RLIMIT_PROCESS  10           /* process number limit */
1099#define LSF_RLIMIT_THREAD   11           /* thread number limit (introduced in LSF6.0) */
1100#define LSF_RLIM_NLIMITS    12           /* number of resource limits */
1101
1102                        requested_time = self.getAttr( self.getAttr( attrs, 'submit') , 'rLimits' )[9]
1103                        if requested_time == -1: 
1104                                requested_time = ""
1105                        requested_memory = self.getAttr( self.getAttr( attrs, 'submit') , 'rLimits' )[8]
1106                        if requested_memory == -1: 
1107                                requested_memory = ""
1108# This tries to get proc per node. We don't support this right now
1109                        ppn = 0 #self.getAttr( self.getAttr( attrs, 'SubmitList') , 'numProessors' )
1110                        requested_cpus = self.getAttr( self.getAttr( attrs, 'submit') , 'numProcessors' )
1111                        if requested_cpus == None or requested_cpus == "":
1112                                requested_cpus = 1
1113
[660]1114                        if QUEUE:
1115                            for q in QUEUE:
1116                                if q == queue:
1117                                    display_queue = 1
1118                                    break
1119                                else:
1120                                    display_queue = 0
1121                                    continue
1122                        if display_queue == 0:
1123                            continue
[524]1124
1125                        runState = self.getAttr( attrs, 'status' )
1126                        if runState == 4:
1127                                status = 'R'
1128                        else:
1129                                status = 'Q'
1130                        queued_timestamp = self.getAttr( attrs, 'submitTime' )
1131
1132                        if status == 'R':
1133                                start_timestamp = self.getAttr( attrs, 'startTime' )
1134                                nodesCpu =  dict(self._countDuplicatesInList(self.getAttr( attrs, 'exHosts' )))
1135                                nodelist = nodesCpu.keys()
1136
1137                                if DETECT_TIME_DIFFS:
1138
1139                                        # If a job start if later than our current date,
1140                                        # that must mean the Torque server's time is later
1141                                        # than our local time.
1142
1143                                        if int(start_timestamp) > int( int(self.cur_time) + int(self.timeoffset) ):
1144
1145                                                self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
1146
1147                        elif status == 'Q':
1148                                start_timestamp = ''
1149                                count_mynodes = 0
1150                                numeric_node = 1
1151                                nodelist = ''
1152
1153                        myAttrs = { }
1154                        if name == "":
1155                                myAttrs['name'] = "none"
1156                        else:
1157                                myAttrs['name'] = name
1158
[659]1159                        myAttrs[ 'owner' ]      = owner
1160                        myAttrs[ 'requested_time' ] = str(requested_time)
1161                        myAttrs[ 'requested_memory' ]   = str(requested_memory)
1162                        myAttrs[ 'requested_cpus' ] = str(requested_cpus)
1163                        myAttrs[ 'ppn' ]        = str( ppn )
1164                        myAttrs[ 'status' ]     = status
1165                        myAttrs[ 'start_timestamp' ]    = str(start_timestamp)
1166                        myAttrs[ 'queue' ]      = str(queue)
1167                        myAttrs[ 'queued_timestamp' ]   = str(queued_timestamp)
1168                        myAttrs[ 'reported' ]       = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1169                        myAttrs[ 'nodes' ]      = do_nodelist( nodelist )
[660]1170                        myAttrs[ 'domain' ]     = fqdn_parts( socket.getfqdn() )[1]
[659]1171                        myAttrs[ 'poll_interval' ]  = str(BATCH_POLL_INTERVAL)
[524]1172
1173                        if self.jobDataChanged( jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
1174                                jobs[ job_id ] = myAttrs
1175
[525]1176                                debug_msg( 10, printTime() + ' job %s state changed' %(job_id) )
[524]1177
1178                for id, attrs in jobs.items():
1179                        if id not in jobs_processed:
[525]1180                                # This one isn't there anymore
[524]1181                                #
1182                                del jobs[ id ]
1183
[660]1184                self.jobs = jobs
[524]1185
[355]1186class PbsDataGatherer( DataGatherer ):
[318]1187
[659]1188    """This is the DataGatherer for PBS and Torque"""
[318]1189
[659]1190    global PBSQuery, PBSError
[256]1191
[659]1192    def __init__( self ):
[354]1193
[659]1194        """Setup appropriate variables"""
[23]1195
[659]1196        self.jobs   = { }
1197        self.timeoffset = 0
1198        self.dp     = DataProcessor()
[354]1199
[659]1200        self.initPbsQuery()
[23]1201
[659]1202    def initPbsQuery( self ):
[91]1203
[659]1204        self.pq     = None
[354]1205
[659]1206        if( BATCH_SERVER ):
[354]1207
[659]1208            self.pq     = PBSQuery( BATCH_SERVER )
1209        else:
1210            self.pq     = PBSQuery()
[91]1211
[659]1212    def getJobData( self ):
[354]1213
[659]1214        """Gather all data on current jobs in Torque"""
[26]1215
[659]1216        joblist     = {}
1217        self.cur_time   = 0
[349]1218
[659]1219        try:
1220            joblist     = self.pq.getjobs()
1221            self.cur_time   = time.time()
[354]1222
[659]1223        except PBSError, detail:
[354]1224
[659]1225            debug_msg( 10, "Caught PBS unavailable, skipping until next polling interval: " + str( detail ) )
1226            return None
[354]1227
[659]1228        jobs_processed  = [ ]
[26]1229
[659]1230        for name, attrs in joblist.items():
1231            display_queue       = 1
1232            job_id          = name.split( '.' )[0]
[26]1233
[659]1234            name            = self.getAttr( attrs, 'Job_Name' )
1235            queue           = self.getAttr( attrs, 'queue' )
[317]1236
[659]1237            if QUEUE:
1238                for q in QUEUE:
1239                    if q == queue:
1240                        display_queue = 1
1241                        break
1242                    else:
1243                        display_queue = 0
1244                        continue
1245            if display_queue == 0:
1246                continue
[317]1247
1248
[659]1249            owner           = self.getAttr( attrs, 'Job_Owner' ).split( '@' )[0]
[660]1250            requested_time      = self.getAttr( attrs['Resource_List'], 'walltime' )
1251            requested_memory    = self.getAttr( attrs['Resource_List'], 'mem' )
[95]1252
[660]1253            mynoderequest       = self.getAttr( attrs['Resource_List'], 'nodes' )
[95]1254
[659]1255            ppn         = ''
[281]1256
[659]1257            if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
[95]1258
[659]1259                mynoderequest_fields    = mynoderequest.split( ':' )
[281]1260
[659]1261                for mynoderequest_field in mynoderequest_fields:
[281]1262
[659]1263                    if mynoderequest_field.find( 'ppn' ) != -1:
[281]1264
[659]1265                        ppn = mynoderequest_field.split( 'ppn=' )[1]
[281]1266
[659]1267            status          = self.getAttr( attrs, 'job_state' )
[25]1268
[659]1269            if status in [ 'Q', 'R' ]:
[450]1270
[659]1271                jobs_processed.append( job_id )
[450]1272
[659]1273            queued_timestamp    = self.getAttr( attrs, 'ctime' )
[243]1274
[659]1275            if status == 'R':
[133]1276
[659]1277                start_timestamp     = self.getAttr( attrs, 'mtime' )
1278                nodes           = self.getAttr( attrs, 'exec_host' ).split( '+' )
[133]1279
[659]1280                nodeslist       = do_nodelist( nodes )
[354]1281
[659]1282                if DETECT_TIME_DIFFS:
[185]1283
[659]1284                    # If a job start if later than our current date,
1285                    # that must mean the Torque server's time is later
1286                    # than our local time.
1287               
1288                    if int( start_timestamp ) > int( int( self.cur_time ) + int( self.timeoffset ) ):
[185]1289
[659]1290                        self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
[185]1291
[659]1292            elif status == 'Q':
[95]1293
[659]1294                # 'mynodequest' can be a string in the following syntax according to the
1295                # Torque Administator's manual:
1296                #
1297                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1298                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1299                # etc
1300                #
[451]1301
[659]1302                #
1303                # For now we only count the amount of nodes request and ignore properties
1304                #
[451]1305
[659]1306                start_timestamp     = ''
1307                count_mynodes       = 0
[354]1308
[659]1309                for node in mynoderequest.split( '+' ):
[67]1310
[659]1311                    # Just grab the {node_count|hostname} part and ignore properties
1312                    #
1313                    nodepart    = node.split( ':' )[0]
[67]1314
[659]1315                    # Let's assume a node_count value
1316                    #
1317                    numeric_node    = 1
[451]1318
[659]1319                    # Chop the value up into characters
1320                    #
1321                    for letter in nodepart:
[67]1322
[659]1323                        # If this char is not a digit (0-9), this must be a hostname
1324                        #
1325                        if letter not in string.digits:
[133]1326
[659]1327                            numeric_node    = 0
[133]1328
[659]1329                    # If this is a hostname, just count this as one (1) node
1330                    #
1331                    if not numeric_node:
[354]1332
[659]1333                        count_mynodes   = count_mynodes + 1
1334                    else:
[451]1335
[659]1336                        # If this a number, it must be the node_count
1337                        # and increase our count with it's value
1338                        #
1339                        try:
1340                            count_mynodes   = count_mynodes + int( nodepart )
[354]1341
[659]1342                        except ValueError, detail:
[354]1343
[659]1344                            # When we arrive here I must be bugged or very confused
1345                            # THIS SHOULD NOT HAPPEN!
1346                            #
1347                            debug_msg( 10, str( detail ) )
1348                            debug_msg( 10, "Encountered weird node in Resources_List?!" )
1349                            debug_msg( 10, 'nodepart = ' + str( nodepart ) )
1350                            debug_msg( 10, 'job = ' + str( name ) )
1351                            debug_msg( 10, 'attrs = ' + str( attrs ) )
1352                       
1353                nodeslist   = str( count_mynodes )
1354            else:
1355                start_timestamp = ''
1356                nodeslist   = ''
[133]1357
[659]1358            myAttrs             = { }
[26]1359
[659]1360            myAttrs[ 'name' ]       = str( name )
1361            myAttrs[ 'queue' ]      = str( queue )
1362            myAttrs[ 'owner' ]      = str( owner )
1363            myAttrs[ 'requested_time' ] = str( requested_time )
1364            myAttrs[ 'requested_memory' ]   = str( requested_memory )
1365            myAttrs[ 'ppn' ]        = str( ppn )
1366            myAttrs[ 'status' ]     = str( status )
1367            myAttrs[ 'start_timestamp' ]    = str( start_timestamp )
1368            myAttrs[ 'queued_timestamp' ]   = str( queued_timestamp )
1369            myAttrs[ 'reported' ]       = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1370            myAttrs[ 'nodes' ]      = nodeslist
1371            myAttrs[ 'domain' ]     = fqdn_parts( socket.getfqdn() )[1]
1372            myAttrs[ 'poll_interval' ]  = str( BATCH_POLL_INTERVAL )
[354]1373
[659]1374            if self.jobDataChanged( self.jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
[61]1375
[659]1376                self.jobs[ job_id ] = myAttrs
[26]1377
[659]1378        for id, attrs in self.jobs.items():
[76]1379
[659]1380            if id not in jobs_processed:
[76]1381
[659]1382                # This one isn't there anymore; toedeledoki!
1383                #
1384                del self.jobs[ id ]
[76]1385
[363]1386#
1387# Gmetric by Nick Galbreath - nickg(a.t)modp(d.o.t)com
1388# Version 1.0 - 21-April2-2007
1389# http://code.google.com/p/embeddedgmetric/
1390#
1391# Modified by: Ramon Bastiaans
1392# For the Job Monarch Project, see: https://subtrac.sara.nl/oss/jobmonarch/
1393#
1394# added: DEFAULT_TYPE for Gmetric's
1395# added: checkHostProtocol to determine if target is multicast or not
1396# changed: allow default for Gmetric constructor
1397# changed: allow defaults for all send() values except dmax
1398#
1399
[362]1400GMETRIC_DEFAULT_TYPE    = 'string'
1401GMETRIC_DEFAULT_HOST    = '127.0.0.1'
1402GMETRIC_DEFAULT_PORT    = '8649'
[659]1403GMETRIC_DEFAULT_UNITS   = ''
[362]1404
1405class Gmetric:
1406
[659]1407    global GMETRIC_DEFAULT_HOST, GMETRIC_DEFAULT_PORT
[362]1408
[659]1409    slope           = { 'zero' : 0, 'positive' : 1, 'negative' : 2, 'both' : 3, 'unspecified' : 4 }
1410    type            = ( '', 'string', 'uint16', 'int16', 'uint32', 'int32', 'float', 'double', 'timestamp' )
1411    protocol        = ( 'udp', 'multicast' )
[362]1412
[659]1413    def __init__( self, host=GMETRIC_DEFAULT_HOST, port=GMETRIC_DEFAULT_PORT ):
[362]1414               
[659]1415        global GMETRIC_DEFAULT_TYPE
[362]1416
[659]1417        self.prot       = self.checkHostProtocol( host )
1418        self.msg        = xdrlib.Packer()
1419        self.socket     = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
[362]1420
[659]1421        if self.prot not in self.protocol:
[362]1422
[659]1423            raise ValueError( "Protocol must be one of: " + str( self.protocol ) )
[362]1424
[659]1425        if self.prot == 'multicast':
[362]1426
[659]1427            # Set multicast options
1428            #
1429            self.socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20 )
[362]1430
[659]1431        self.hostport   = ( host, int( port ) )
1432        self.slopestr   = 'both'
1433        self.tmax       = 60
[362]1434
[659]1435    def checkHostProtocol( self, ip ):
[362]1436
[659]1437        """Detect if a ip adress is a multicast address"""
[471]1438
[659]1439        MULTICAST_ADDRESS_MIN   = ( "224", "0", "0", "0" )
1440        MULTICAST_ADDRESS_MAX   = ( "239", "255", "255", "255" )
[362]1441
[659]1442        ip_fields               = ip.split( '.' )
[362]1443
[659]1444        if ip_fields >= MULTICAST_ADDRESS_MIN and ip_fields <= MULTICAST_ADDRESS_MAX:
[362]1445
[659]1446            return 'multicast'
1447        else:
1448            return 'udp'
[362]1449
[659]1450    def send( self, name, value, dmax, typestr = '', units = '' ):
[362]1451
[659]1452        if len( units ) == 0:
1453            units       = GMETRIC_DEFAULT_UNITS
[471]1454
[659]1455        if len( typestr ) == 0:
1456            typestr     = GMETRIC_DEFAULT_TYPE
[362]1457
[659]1458        msg             = self.makexdr( name, value, typestr, units, self.slopestr, self.tmax, dmax )
[409]1459
[659]1460        return self.socket.sendto( msg, self.hostport )
[362]1461
[659]1462    def makexdr( self, name, value, typestr, unitstr, slopestr, tmax, dmax ):
[362]1463
[659]1464        if slopestr not in self.slope:
[362]1465
[659]1466            raise ValueError( "Slope must be one of: " + str( self.slope.keys() ) )
[362]1467
[659]1468        if typestr not in self.type:
[362]1469
[659]1470            raise ValueError( "Type must be one of: " + str( self.type ) )
[362]1471
[659]1472        if len( name ) == 0:
[362]1473
[659]1474            raise ValueError( "Name must be non-empty" )
[362]1475
[659]1476        self.msg.reset()
1477        self.msg.pack_int( 0 )
1478        self.msg.pack_string( typestr )
1479        self.msg.pack_string( name )
1480        self.msg.pack_string( str( value ) )
1481        self.msg.pack_string( unitstr )
1482        self.msg.pack_int( self.slope[ slopestr ] )
1483        self.msg.pack_uint( int( tmax ) )
1484        self.msg.pack_uint( int( dmax ) )
[362]1485
[659]1486        return self.msg.get_buffer()
[362]1487
[26]1488def printTime( ):
[354]1489
[659]1490    """Print current time/date in human readable format for log/debug"""
[26]1491
[659]1492    return time.strftime("%a, %d %b %Y %H:%M:%S")
[26]1493
1494def debug_msg( level, msg ):
[354]1495
[659]1496    """Print msg if at or above current debug level"""
[26]1497
[659]1498    global DAEMONIZE, DEBUG_LEVEL, SYSLOG_LEVEL
[377]1499
[660]1500    if (not DAEMONIZE and DEBUG_LEVEL >= level):
[659]1501        sys.stderr.write( msg + '\n' )
[26]1502
[659]1503    if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
1504        syslog.syslog( msg )
[373]1505
[307]1506def write_pidfile():
1507
[659]1508    # Write pidfile if PIDFILE is set
1509    #
1510    if PIDFILE:
[307]1511
[659]1512        pid = os.getpid()
[354]1513
[659]1514        pidfile = open( PIDFILE, 'w' )
[354]1515
[659]1516        pidfile.write( str( pid ) )
1517        pidfile.close()
[307]1518
[23]1519def main():
[354]1520
[659]1521    """Application start"""
[23]1522
[659]1523    global PBSQuery, PBSError, lsfObject
1524    global SYSLOG_FACILITY, USE_SYSLOG, BATCH_API, DAEMONIZE
[256]1525
[659]1526    if not processArgs( sys.argv[1:] ):
[354]1527
[659]1528        sys.exit( 1 )
[212]1529
[659]1530    # Load appropriate DataGatherer depending on which BATCH_API is set
1531    # and any required modules for the Gatherer
1532    #
1533    if BATCH_API == 'pbs':
[256]1534
[659]1535        try:
1536            from PBSQuery import PBSQuery, PBSError
[256]1537
[659]1538        except ImportError:
[256]1539
[659]1540            debug_msg( 0, "FATAL ERROR: BATCH_API set to 'pbs' but python module 'pbs_python' is not installed" )
1541            sys.exit( 1 )
[256]1542
[659]1543        gather = PbsDataGatherer()
[256]1544
[659]1545    elif BATCH_API == 'sge':
[256]1546
[659]1547        # Tested with SGE 6.0u11.
1548        #
1549        gather = SgeDataGatherer()
[368]1550
[659]1551    elif BATCH_API == 'lsf':
[368]1552
[659]1553        try:
1554            from lsfObject import lsfObject
1555        except:
1556            debug_msg(0, "fatal error: BATCH_API set to 'lsf' but python module is not found or installed")
1557            sys.exit( 1)
[256]1558
[659]1559        gather = LsfDataGatherer()
[524]1560
[659]1561    else:
1562        debug_msg( 0, "FATAL ERROR: unknown BATCH_API '" + BATCH_API + "' is not supported" )
[354]1563
[659]1564        sys.exit( 1 )
[256]1565
[659]1566    if( DAEMONIZE and USE_SYSLOG ):
[373]1567
[659]1568        syslog.openlog( 'jobmond', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
[373]1569
[659]1570    if DAEMONIZE:
[354]1571
[659]1572        gather.daemon()
1573    else:
1574        gather.run()
[23]1575
[256]1576# wh00t? someone started me! :)
[65]1577#
[23]1578if __name__ == '__main__':
[659]1579    main()
Note: See TracBrowser for help on using the repository browser.