source: branches/1.0/jobmond/jobmond.py @ 863

Last change on this file since 863 was 854, checked in by ramonb, 11 years ago

jobmond.py:

  • print warning if BATCH_SERVER != localhost and BATCH_API does not support connecting to remote BATCH_SERVER
  • fun fact: discovered that developers of the SGE/LSF implementation also completely ignore the BATCH_SERVER setting
  • see #162
  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 64.3 KB
RevLine 
[23]1#!/usr/bin/env python
[225]2#
3# This file is part of Jobmonarch
4#
[691]5# Copyright (C) 2006-2013  Ramon Bastiaans
[623]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 854 2013-05-13 20:27:15Z ramonb $
[227]23#
[23]24
[694]25# vi :set ts=4
26
[471]27import sys, getopt, ConfigParser, time, os, socket, string, re
[837]28import xdrlib, socket, syslog, xml, xml.sax, shlex, os.path, pwd
[318]29from xml.sax.handler import feature_namespaces
[623]30from collections import deque
[699]31from glob import glob
[318]32
[829]33VERSION='1.0'
[307]34
[471]35def usage( ver ):
36
[691]37    print 'jobmond %s' %VERSION
[471]38
[691]39    if ver:
40        return 0
[471]41
[691]42    print
43    print 'Purpose:'
44    print '  The Job Monitoring Daemon (jobmond) reports batch jobs information and statistics'
45    print '  to Ganglia, which can be viewed with Job Monarch web frontend'
46    print
47    print 'Usage:    jobmond [OPTIONS]'
48    print
49    print '  -c, --config=FILE    The configuration file to use (default: /etc/jobmond.conf)'
50    print '  -p, --pidfile=FILE    Use pid file to store the process id'
51    print '  -h, --help        Print help and exit'
52    print '  -v, --version      Print version and exit'
53    print
[307]54
[212]55def processArgs( args ):
[26]56
[701]57    SHORT_L      = 'p:hvc:'
58    LONG_L       = [ 'help', 'config=', 'pidfile=', 'version' ]
[165]59
[704]60    global PIDFILE, JOBMOND_CONF
[701]61    PIDFILE      = None
[61]62
[701]63    JOBMOND_CONF = '/etc/jobmond.conf'
[354]64
[691]65    try:
[68]66
[691]67        opts, args    = getopt.getopt( args, SHORT_L, LONG_L )
[185]68
[691]69    except getopt.GetoptError, detail:
[212]70
[691]71        print detail
[851]72        usage( False )
[691]73        sys.exit( 1 )
[212]74
[691]75    for opt, value in opts:
[212]76
[691]77        if opt in [ '--config', '-c' ]:
78       
[701]79            JOBMOND_CONF = value
[212]80
[691]81        if opt in [ '--pidfile', '-p' ]:
[212]82
[701]83            PIDFILE      = value
[691]84       
85        if opt in [ '--help', '-h' ]:
[307]86 
[691]87            usage( False )
88            sys.exit( 0 )
[212]89
[691]90        if opt in [ '--version', '-v' ]:
[471]91
[691]92            usage( True )
93            sys.exit( 0 )
[471]94
[701]95    return loadConfig( JOBMOND_CONF )
[212]96
[520]97class GangliaConfigParser:
98
[699]99    def __init__( self, filename ):
[520]100
[699]101        self.conf_lijst   = [ ]
102        self.conf_dict    = { }
103        self.filename     = filename
104        self.file_pointer = file( filename, 'r' )
105        self.lexx         = shlex.shlex( self.file_pointer )
106        self.lexx.whitespace_split = True
[520]107
[699]108        self.parse()
[520]109
[699]110    def __del__( self ):
[520]111
[699]112        """
113        Cleanup: close file descriptor
114        """
115
116        self.file_pointer.close()
117        del self.lexx
118        del self.conf_lijst
119
[691]120    def removeQuotes( self, value ):
[520]121
[699]122        clean_value = value
123        clean_value = clean_value.replace( "'", "" )
124        clean_value = clean_value.replace( '"', '' )
125        clean_value = clean_value.strip()
[520]126
[691]127        return clean_value
[520]128
[699]129    def removeBraces( self, value ):
[520]130
[699]131        clean_value = value
132        clean_value = clean_value.replace( "(", "" )
133        clean_value = clean_value.replace( ')', '' )
134        clean_value = clean_value.strip()
[520]135
[699]136        return clean_value
[520]137
[699]138    def parse( self ):
[520]139
[699]140        """
141        Parse self.filename using shlex scanning.
142        - Removes /* comments */
143        - Traverses (recursively) through all include () statements
144        - Stores complete valid config tokens in self.conf_list
[520]145
[699]146        i.e.:
147            ['globals',
148             '{',
149             'daemonize',
150             '=',
151             'yes',
152             'setuid',
153             '=',
154             'yes',
155             'user',
156             '=',
157             'ganglia',
158             'debug_level',
159             '=',
160             '0',
161             <etc> ]
162        """
[520]163
[699]164        t = 'bogus'
165        c = False
166        i = False
[520]167
[699]168        while t != self.lexx.eof:
169            #print 'get token'
170            t = self.lexx.get_token()
[520]171
[699]172            if len( t ) >= 2:
[520]173
[699]174                if len( t ) >= 4:
[520]175
[699]176                    if t[:2] == '/*' and t[-2:] == '*/':
[520]177
[699]178                        #print 'comment line'
179                        #print 'skipping: %s' %t
180                        continue
[520]181
[699]182                if t == '/*' or t[:2] == '/*':
183                    c = True
184                    #print 'comment start'
185                    #print 'skipping: %s' %t
186                    continue
[520]187
[699]188                if t == '*/' or t[-2:] == '*/':
189                    c = False
190                    #print 'skipping: %s' %t
191                    #print 'comment end'
192                    continue
193
194            if c:
195                #print 'skipping: %s' %t
196                continue
197
198            if t == 'include':
199                i = True
200                #print 'include start'
201                #print 'skipping: %s' %t
202                continue
203
204            if i:
205
206                #print 'include start: %s' %t
207
208                t2 = self.removeQuotes( t )
209                t2 = self.removeBraces( t )
210
211                for in_file in glob( self.removeQuotes(t2) ):
212
213                    #print 'including file: %s' %in_file
214                    parse_infile = GangliaConfigParser( in_file )
215
216                    self.conf_lijst = self.conf_lijst + parse_infile.getConfLijst()
217
218                    del parse_infile
219
220                i = False
221                #print 'include end'
222                #print 'skipping: %s' %t
223                continue
224
225            #print 'keep: %s' %t
226            self.conf_lijst.append( self.removeQuotes(t) )
227
228    def getConfLijst( self ):
229
230        return self.conf_lijst
231
232    def confListToDict( self, parent_list=None ):
233
234        """
235        Recursively traverses a conf_list and creates dictionary from it
236        """
237
238        new_dict = { }
239        count    = 0
240        skip     = 0
241
242        if not parent_list:
243            parent_list = self.conf_lijst
244
245        #print 'entering confListToDict(): (parent) list size %s' %len(parent_list)
246
247        for n, c in enumerate( parent_list ):
248
249            count = count + 1
250
251            #print 'CL: n %d c %s' %(n, c)
252
253            if skip > 0:
254
255                #print '- skipped'
256                skip = skip - 1
257                continue
258
259            if (n+1) <= (len( parent_list )-1):
260
261                if parent_list[(n+1)] == '{':
262
263                    if not new_dict.has_key( c ):
264                        new_dict[ c ] = [ ]
265
266                    (temp_new_dict, skip) = self.confListToDict( parent_list[(n+2):] )
267                    new_dict[ c ].append( temp_new_dict )
268
269                if parent_list[(n+1)] == '=' and (n+2) <= (len( parent_list )-1):
270
271                    if not new_dict.has_key( c ):
272                        new_dict[ c ] = [ ]
273
274                    new_dict[ c ].append( parent_list[ (n+2) ] )
275
276                    skip = 2
277
278                if parent_list[n] == '}':
279
280                    #print 'leaving confListToDict(): new dict = %s' %new_dict
281                    return (new_dict, count)
282
283    def makeConfDict( self ):
284
285        """
286        Walks through self.conf_list and creates a dictionary based upon config values
287
288        i.e.:
289            'tcp_accept_channel': [{'acl': [{'access': [{'action': ['"allow"'],
290                                                         'ip': ['"127.0.0.1"'],
291                                                         'mask': ['32']}]}],
292                                    'port': ['8649']}],
293            'udp_recv_channel': [{'port': ['8649']}],
294            'udp_send_channel': [{'host': ['145.101.32.3'],
295                                  'port': ['8649']},
296                                 {'host': ['145.101.32.207'],
297                                  'port': ['8649']}]}
298        """
299
300        new_dict = { }
301        skip     = 0
302
303        #print 'entering makeConfDict()'
304
305        for n, c in enumerate( self.conf_lijst ):
306
307            #print 'M: n %d c %s' %(n, c)
308
309            if skip > 0:
310
311                #print '- skipped'
312                skip = skip - 1
313                continue
314
315            if (n+1) <= (len( self.conf_lijst )-1):
316
317                if self.conf_lijst[(n+1)] == '{':
318
319                    if not new_dict.has_key( c ):
320                        new_dict[ c ] = [ ]
321
322                    ( temp_new_dict, skip ) = self.confListToDict( self.conf_lijst[(n+2):] )
323                    new_dict[ c ].append( temp_new_dict )
324
325                if self.conf_lijst[(n+1)] == '=' and (n+2) <= (len( self.conf_lijst )-1):
326
327                    if not new_dict.has_key( c ):
328                        new_dict[ c ] = [ ]
329
330                    new_dict[ c ].append( self.conf_lijst[ (n+2) ] )
331
332                    skip = 2
333
334        self.conf_dict = new_dict
335        #print 'leaving makeConfDict(): conf dict size %d' %len( self.conf_dict )
336
337    def checkConfDict( self ):
338
339        if len( self.conf_lijst ) == 0:
340
341            raise Exception("Something went wrong generating conf list for %s" %self.file_name )
342
343        if len( self.conf_dict ) == 0:
344
345            self.makeConfDict()
346
347    def getConfDict( self ):
348
349        self.checkConfDict()
350        return self.conf_dict
351
352    def getUdpSendChannels( self ):
353
354        self.checkConfDict()
355
[707]356        udp_send_channels = [ ] # IP:PORT
357
358        if not self.conf_dict.has_key( 'udp_send_channel' ):
359            return None
360
361        for u in self.conf_dict[ 'udp_send_channel' ]:
362
363            if u.has_key( 'mcast_join' ):
364
365                ip = u['mcast_join'][0]
366
367            elif u.has_key( 'host' ):
368
369                ip = u['host'][0]
370
371            port = u['port'][0]
372
373            udp_send_channels.append( ( ip, port ) )
374
375        if len( udp_send_channels ) == 0:
376            return None
377
378        return udp_send_channels
379
[699]380    def getSectionLastOption( self, section, option ):
381
382        """
383        Get last option set in a config section that could be set multiple times in multiple (include) files.
384
385        i.e.: getSectionLastOption( 'globals', 'send_metadata_interval' )
386        """
387
388        self.checkConfDict()
389        value = None
390
391        if not self.conf_dict.has_key( section ):
392
393            return None
394
395        # Could be set multiple times in multiple (include) files: get last one set
396        for c in self.conf_dict[ section ]:
397
398                if c.has_key( option ):
399
[705]400                    value = c[ option ][0]
[699]401
[705]402        return value
[699]403
404    def getClusterName( self ):
405
406        return self.getSectionLastOption( 'cluster', 'name' )
407
408    def getVal( self, section, option ):
409
410        return self.getSectionLastOption( section, option )
411
[691]412    def getInt( self, section, valname ):
[520]413
[691]414        value    = self.getVal( section, valname )
[520]415
[691]416        if not value:
[699]417            return None
[520]418
[691]419        return int( value )
[520]420
[691]421    def getStr( self, section, valname ):
[520]422
[691]423        value    = self.getVal( section, valname )
[520]424
[691]425        if not value:
[699]426            return None
[520]427
[691]428        return str( value )
[520]429
430def findGmetric():
431
[691]432    for dir in os.path.expandvars( '$PATH' ).split( ':' ):
[520]433
[691]434        guess    = '%s/%s' %( dir, 'gmetric' )
[520]435
[691]436        if os.path.exists( guess ):
[520]437
[691]438            return guess
[520]439
[691]440    return False
[520]441
[212]442def loadConfig( filename ):
443
[691]444    def getlist( cfg_string ):
[215]445
[691]446        my_list = [ ]
[215]447
[691]448        for item_txt in cfg_string.split( ',' ):
[215]449
[691]450            sep_char = None
[215]451
[691]452            item_txt = item_txt.strip()
[215]453
[691]454            for s_char in [ "'", '"' ]:
[215]455
[691]456                if item_txt.find( s_char ) != -1:
[215]457
[691]458                    if item_txt.count( s_char ) != 2:
[215]459
[691]460                        print 'Missing quote: %s' %item_txt
461                        sys.exit( 1 )
[215]462
[691]463                    else:
[215]464
[691]465                        sep_char = s_char
466                        break
[215]467
[691]468            if sep_char:
[215]469
[691]470                item_txt = item_txt.split( sep_char )[1]
[215]471
[691]472            my_list.append( item_txt )
[215]473
[691]474        return my_list
[215]475
[784]476    if not os.path.isfile( JOBMOND_CONF ):
477
478        print "Is not a file or does not exist: '%s'" %JOBMOND_CONF
479        sys.exit( 1 )
480
481    try:
482        f = open( JOBMOND_CONF, 'r' )
483    except IOError, detail:
484        print "Cannot read config file: '%s'" %JOBMOND_CONF
485        sys.exit( 1 )
486    else:
487        f.close()
488
[691]489    cfg        = ConfigParser.ConfigParser()
[212]490
[691]491    cfg.read( filename )
[212]492
[691]493    global DEBUG_LEVEL, DAEMONIZE, BATCH_SERVER, BATCH_POLL_INTERVAL
494    global GMOND_CONF, DETECT_TIME_DIFFS, BATCH_HOST_TRANSLATE
495    global BATCH_API, QUEUE, GMETRIC_TARGET, USE_SYSLOG
496    global SYSLOG_LEVEL, SYSLOG_FACILITY, GMETRIC_BINARY
[707]497    global METRIC_MAX_VAL_LEN, GMOND_UDP_SEND_CHANNELS
[212]498
[701]499    DEBUG_LEVEL = cfg.getint( 'DEFAULT', 'DEBUG_LEVEL' )
[212]500
[701]501    DAEMONIZE   = cfg.getboolean( 'DEFAULT', 'DAEMONIZE' )
[212]502
[691]503    SYSLOG_LEVEL    = -1
[701]504    SYSLOG_FACILITY = None
[377]505
[691]506    try:
[701]507        USE_SYSLOG  = cfg.getboolean( 'DEFAULT', 'USE_SYSLOG' )
[212]508
[691]509    except ConfigParser.NoOptionError:
[373]510
[701]511        USE_SYSLOG  = True
[373]512
[691]513        debug_msg( 0, 'ERROR: no option USE_SYSLOG found: assuming yes' )
[373]514
[691]515    if USE_SYSLOG:
[373]516
[691]517        try:
[701]518            SYSLOG_LEVEL = cfg.getint( 'DEFAULT', 'SYSLOG_LEVEL' )
[373]519
[691]520        except ConfigParser.NoOptionError:
[373]521
[691]522            debug_msg( 0, 'ERROR: no option SYSLOG_LEVEL found: assuming level 0' )
[701]523            SYSLOG_LEVEL = 0
[373]524
[691]525        try:
[373]526
[691]527            SYSLOG_FACILITY = eval( 'syslog.LOG_' + cfg.get( 'DEFAULT', 'SYSLOG_FACILITY' ) )
[373]528
[691]529        except ConfigParser.NoOptionError:
[373]530
[691]531            SYSLOG_FACILITY = syslog.LOG_DAEMON
[373]532
[691]533            debug_msg( 0, 'ERROR: no option SYSLOG_FACILITY found: assuming facility DAEMON' )
[373]534
[691]535    try:
[373]536
[701]537        BATCH_SERVER = cfg.get( 'DEFAULT', 'BATCH_SERVER' )
[212]538
[691]539    except ConfigParser.NoOptionError:
[265]540
[691]541        # Backwards compatibility for old configs
542        #
[265]543
[701]544        BATCH_SERVER = cfg.get( 'DEFAULT', 'TORQUE_SERVER' )
545        api_guess    = 'pbs'
[691]546   
547    try:
548   
[701]549        BATCH_POLL_INTERVAL = cfg.getint( 'DEFAULT', 'BATCH_POLL_INTERVAL' )
[265]550
[691]551    except ConfigParser.NoOptionError:
[265]552
[691]553        # Backwards compatibility for old configs
554        #
[265]555
[701]556        BATCH_POLL_INTERVAL = cfg.getint( 'DEFAULT', 'TORQUE_POLL_INTERVAL' )
557        api_guess           = 'pbs'
[691]558   
559    try:
[212]560
[701]561        GMOND_CONF          = cfg.get( 'DEFAULT', 'GMOND_CONF' )
[353]562
[691]563    except ConfigParser.NoOptionError:
[353]564
[703]565        # Not specified: assume /etc/ganglia/gmond.conf
[691]566        #
[703]567        GMOND_CONF          = '/etc/ganglia/gmond.conf'
[353]568
[707]569    ganglia_cfg             = GangliaConfigParser( GMOND_CONF )
570    GMETRIC_TARGET          = None
[449]571
[707]572    GMOND_UDP_SEND_CHANNELS = ganglia_cfg.getUdpSendChannels()
[449]573
[707]574    if not GMOND_UDP_SEND_CHANNELS:
[449]575
[701]576        debug_msg( 0, "WARNING: Can't parse udp_send_channel from: '%s' - Trying: %s" %( GMOND_CONF, JOBMOND_CONF ) )
[520]577
[691]578        # Couldn't figure it out: let's see if it's in our jobmond.conf
579        #
580        try:
[520]581
[691]582            GMETRIC_TARGET    = cfg.get( 'DEFAULT', 'GMETRIC_TARGET' )
[520]583
[691]584        # Guess not: now just give up
[701]585       
[691]586        except ConfigParser.NoOptionError:
[520]587
[691]588            GMETRIC_TARGET    = None
[520]589
[691]590            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]591
[701]592            gmetric_bin    = findGmetric()
[520]593
[701]594            if gmetric_bin:
[520]595
[701]596                GMETRIC_BINARY     = gmetric_bin
597            else:
598                debug_msg( 0, "WARNING: Can't find gmetric binary anywhere in $PATH" )
[520]599
[701]600                try:
[520]601
[701]602                    GMETRIC_BINARY = cfg.get( 'DEFAULT', 'GMETRIC_BINARY' )
[520]603
[701]604                except ConfigParser.NoOptionError:
[520]605
[786]606                    print "FATAL ERROR: GMETRIC_BINARY not set and not in $PATH"
[701]607                    sys.exit( 1 )
[520]608
[701]609    #TODO: is this really still needed or should be automatic
[691]610    DETECT_TIME_DIFFS    = cfg.getboolean( 'DEFAULT', 'DETECT_TIME_DIFFS' )
[212]611
[701]612    BATCH_HOST_TRANSLATE = getlist( cfg.get( 'DEFAULT', 'BATCH_HOST_TRANSLATE' ) )
[215]613
[691]614    try:
[256]615
[691]616        BATCH_API    = cfg.get( 'DEFAULT', 'BATCH_API' )
[266]617
[691]618    except ConfigParser.NoOptionError, detail:
[266]619
[691]620        if BATCH_SERVER and api_guess:
[354]621
[691]622            BATCH_API    = api_guess
623        else:
[786]624            print "FATAL ERROR: BATCH_API not set and can't make guess"
[691]625            sys.exit( 1 )
[317]626
[691]627    try:
[317]628
[691]629        QUEUE        = getlist( cfg.get( 'DEFAULT', 'QUEUE' ) )
[317]630
[691]631    except ConfigParser.NoOptionError, detail:
[317]632
[691]633        QUEUE        = None
[353]634
[701]635    METRIC_MAX_VAL_LEN = ganglia_cfg.getInt( 'globals', 'max_udp_msg_len' )
636
[691]637    return True
[212]638
[507]639def fqdn_parts (fqdn):
[520]640
[691]641    """Return pair of host and domain for fully-qualified domain name arg."""
[520]642
[691]643    parts = fqdn.split (".")
[520]644
[691]645    return (parts[0], string.join(parts[1:], "."))
[507]646
[61]647class DataProcessor:
[355]648
[691]649    """Class for processing of data"""
[61]650
[691]651    binary = None
[61]652
[691]653    def __init__( self, binary=None ):
[355]654
[691]655        """Remember alternate binary location if supplied"""
[61]656
[691]657        global GMETRIC_BINARY, GMOND_CONF
[449]658
[691]659        if binary:
660            self.binary = binary
[61]661
[707]662        if not self.binary and not GMETRIC_TARGET and not GMOND_UDP_SEND_CHANNELS:
[691]663            self.binary = GMETRIC_BINARY
[449]664
[691]665        # Timeout for XML
666        #
667        # From ganglia's documentation:
668        #
669        # 'A metric will be deleted DMAX seconds after it is received, and
670        # DMAX=0 means eternal life.'
[61]671
[691]672        self.dmax = str( int( int( BATCH_POLL_INTERVAL ) * 2 ) )
[80]673
[707]674        if GMOND_CONF and not GMETRIC_TARGET and not GMOND_UDP_SEND_CHANNELS:
[354]675
[691]676            incompatible = self.checkGmetricVersion()
[61]677
[691]678            if incompatible:
[355]679
[786]680                print 'Ganglia/Gmetric version not compatible, please upgrade to at least 3.4.0'
[691]681                sys.exit( 1 )
[65]682
[691]683    def checkGmetricVersion( self ):
[355]684
[691]685        """
[692]686        Check version of gmetric is at least 3.4.0
[691]687        for the syntax we use
688        """
[65]689
[691]690        global METRIC_MAX_VAL_LEN, GMETRIC_TARGET
[255]691
[691]692        incompatible    = 0
[341]693
[691]694        gfp        = os.popen( self.binary + ' --version' )
[692]695        lines      = gfp.readlines()
[65]696
[691]697        gfp.close()
[355]698
[691]699        for line in lines:
[355]700
[691]701            line = line.split( ' ' )
[65]702
[691]703            if len( line ) == 2 and str( line ).find( 'gmetric' ) != -1:
704           
705                gmetric_version    = line[1].split( '\n' )[0]
[65]706
[691]707                version_major    = int( gmetric_version.split( '.' )[0] )
708                version_minor    = int( gmetric_version.split( '.' )[1] )
709                version_patch    = int( gmetric_version.split( '.' )[2] )
[65]710
[691]711                incompatible    = 0
[65]712
[691]713                if version_major < 3:
[65]714
[691]715                    incompatible = 1
716               
717                elif version_major == 3:
[65]718
[692]719                    if version_minor < 4:
[65]720
[692]721                        incompatible = 1
[65]722
[691]723        return incompatible
[65]724
[691]725    def multicastGmetric( self, metricname, metricval, valtype='string', units='' ):
[355]726
[691]727        """Call gmetric binary and multicast"""
[65]728
[691]729        cmd = self.binary
[65]730
[707]731        if GMOND_UDP_SEND_CHANNELS:
[61]732
[707]733            for c_ip, c_port  in GMOND_UDP_SEND_CHANNELS:
734
735                metric_debug        = "[gmetric %s:%s] name: %s - val: %s - dmax: %s" %( str(c_ip), str(c_port), str( metricname ), str( metricval ), str( self.dmax ) )
736
737                debug_msg( 10, printTime() + ' ' + metric_debug)
738
739                gm = Gmetric( c_ip, c_port )
740
741                gm.send( str( metricname ), str( metricval ), str( self.dmax ), valtype, units )
742
743        elif GMETRIC_TARGET:
744
[691]745            GMETRIC_TARGET_HOST    = GMETRIC_TARGET.split( ':' )[0]
746            GMETRIC_TARGET_PORT    = GMETRIC_TARGET.split( ':' )[1]
[353]747
[691]748            metric_debug        = "[gmetric] name: %s - val: %s - dmax: %s" %( str( metricname ), str( metricval ), str( self.dmax ) )
[353]749
[691]750            debug_msg( 10, printTime() + ' ' + metric_debug)
[353]751
[691]752            gm = Gmetric( GMETRIC_TARGET_HOST, GMETRIC_TARGET_PORT )
[353]753
[691]754            gm.send( str( metricname ), str( metricval ), str( self.dmax ), valtype, units )
[353]755
[691]756        else:
757            try:
758                cmd = cmd + ' -c' + GMOND_CONF
[353]759
[691]760            except NameError:
[353]761
[705]762                debug_msg( 10, 'Assuming /etc/ganglia/gmond.conf for gmetric cmd' )
[353]763
[691]764            cmd = cmd + ' -n' + str( metricname )+ ' -v"' + str( metricval )+ '" -t' + str( valtype ) + ' -d' + str( self.dmax )
[353]765
[691]766            if len( units ) > 0:
[409]767
[691]768                cmd = cmd + ' -u"' + units + '"'
[409]769
[691]770            debug_msg( 10, printTime() + ' ' + cmd )
[353]771
[691]772            os.system( cmd )
[353]773
[318]774class DataGatherer:
[23]775
[691]776    """Skeleton class for batch system DataGatherer"""
[256]777
[691]778    def printJobs( self, jobs ):
[355]779
[691]780        """Print a jobinfo overview"""
[318]781
[691]782        for name, attrs in self.jobs.items():
[318]783
[691]784            print 'job %s' %(name)
[318]785
[691]786            for name, val in attrs.items():
[318]787
[691]788                print '\t%s = %s' %( name, val )
[318]789
[691]790    def printJob( self, jobs, job_id ):
[355]791
[691]792        """Print job with job_id from jobs"""
[318]793
[691]794        print 'job %s' %(job_id)
[318]795
[691]796        for name, val in jobs[ job_id ].items():
[318]797
[691]798            print '\t%s = %s' %( name, val )
[318]799
[691]800    def getAttr( self, attrs, name ):
[507]801
[691]802        """Return certain attribute from dictionary, if exists"""
[507]803
[691]804        if attrs.has_key( name ):
[507]805
[691]806            return attrs[ name ]
807        else:
808            return ''
[507]809
[691]810    def jobDataChanged( self, jobs, job_id, attrs ):
[507]811
[691]812        """Check if job with attrs and job_id in jobs has changed"""
[507]813
[691]814        if jobs.has_key( job_id ):
[507]815
[691]816            oldData = jobs[ job_id ]   
817        else:
818            return 1
[507]819
[691]820        for name, val in attrs.items():
[507]821
[691]822            if oldData.has_key( name ):
[507]823
[691]824                if oldData[ name ] != attrs[ name ]:
[507]825
[691]826                    return 1
[507]827
[691]828            else:
829                return 1
[507]830
[691]831        return 0
[507]832
[691]833    def submitJobData( self ):
[507]834
[691]835        """Submit job info list"""
[507]836
[691]837        global BATCH_API
[512]838
[728]839        self.dp.multicastGmetric( 'zplugin_monarch_heartbeat', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
[507]840
[724]841        running_jobs = 0
842        queued_jobs  = 0
[507]843
[691]844        # Count how many running/queued jobs we found
845        #
846        for jobid, jobattrs in self.jobs.items():
[507]847
[691]848            if jobattrs[ 'status' ] == 'Q':
[507]849
[691]850                queued_jobs += 1
[507]851
[691]852            elif jobattrs[ 'status' ] == 'R':
[507]853
[691]854                running_jobs += 1
[507]855
[691]856        # Report running/queued jobs as seperate metric for a nice RRD graph
857        #
[728]858        self.dp.multicastGmetric( 'zplugin_monarch_rj', str( running_jobs ), 'uint32', 'jobs' )
859        self.dp.multicastGmetric( 'zplugin_monarch_qj', str( queued_jobs ), 'uint32', 'jobs' )
[507]860
[691]861        # Report down/offline nodes in batch (PBS only ATM)
862        #
863        if BATCH_API == 'pbs':
[512]864
[691]865            domain        = fqdn_parts( socket.getfqdn() )[1]
[514]866
[728]867            downed_nodes  = list()
868            offline_nodes = list()
[691]869       
870            l        = ['state']
[512]871
[790]872            nodelist = self.getNodeData()
873
874            for name, node in nodelist.items():
875
[691]876                if ( node[ 'state' ].find( "down" ) != -1 ):
[512]877
[691]878                    downed_nodes.append( name )
[512]879
[691]880                if ( node[ 'state' ].find( "offline" ) != -1 ):
[512]881
[691]882                    offline_nodes.append( name )
[512]883
[728]884            downnodeslist    = do_nodelist( downed_nodes )
885            offlinenodeslist = do_nodelist( offline_nodes )
[512]886
[691]887            down_str    = 'nodes=%s domain=%s reported=%s' %( string.join( downnodeslist, ';' ), domain, str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
888            offl_str    = 'nodes=%s domain=%s reported=%s' %( string.join( offlinenodeslist, ';' ), domain, str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
[728]889            self.dp.multicastGmetric( 'zplugin_monarch_down'   , down_str )
890            self.dp.multicastGmetric( 'zplugin_monarch_offline', offl_str )
[514]891
[691]892        # Now let's spread the knowledge
893        #
894        for jobid, jobattrs in self.jobs.items():
[507]895
[691]896            # Make gmetric values for each job: respect max gmetric value length
897            #
898            gmetric_val        = self.compileGmetricVal( jobid, jobattrs )
899            metric_increment    = 0
[507]900
[691]901            # If we have more job info than max gmetric value length allows, split it up
902            # amongst multiple metrics
903            #
904            for val in gmetric_val:
[507]905
[728]906                metric_name = 'zplugin_monarch_job_%s_%s' %( str(metric_increment) , str( jobid ) )
907                self.dp.multicastGmetric( metric_name, val )
[507]908
[691]909                # Increase follow number if this jobinfo is split up amongst more than 1 gmetric
910                #
911                metric_increment    = metric_increment + 1
[507]912
[691]913    def compileGmetricVal( self, jobid, jobattrs ):
[507]914
[691]915        """Create a val string for gmetric of jobinfo"""
[507]916
[691]917        gval_lists    = [ ]
918        val_list    = { }
[507]919
[691]920        for val_name, val_value in jobattrs.items():
[507]921
[691]922            # These are our own metric names, i.e.: status, start_timestamp, etc
923            #
924            val_list_names_len    = len( string.join( val_list.keys() ) ) + len(val_list.keys())
[507]925
[691]926            # These are their corresponding values
927            #
928            val_list_vals_len    = len( string.join( val_list.values() ) ) + len(val_list.values())
[507]929
[691]930            if val_name == 'nodes' and jobattrs['status'] == 'R':
[507]931
[691]932                node_str = None
[507]933
[691]934                for node in val_value:
[507]935
[691]936                    if node_str:
[507]937
[691]938                        node_str = node_str + ';' + node
939                    else:
940                        node_str = node
[507]941
[691]942                    # Make sure if we add this new info, that the total metric's value length does not exceed METRIC_MAX_VAL_LEN
943                    #
944                    if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(node_str) ) > METRIC_MAX_VAL_LEN:
[507]945
[691]946                        # It's too big, we need to make a new gmetric for the additional info
947                        #
948                        val_list[ val_name ]    = node_str
[507]949
[691]950                        gval_lists.append( val_list )
[507]951
[691]952                        val_list        = { }
953                        node_str        = None
[507]954
[691]955                val_list[ val_name ]    = node_str
[507]956
[691]957                gval_lists.append( val_list )
[507]958
[691]959                val_list        = { }
[507]960
[691]961            elif val_value != '':
[507]962
[691]963                # Make sure if we add this new info, that the total metric's value length does not exceed METRIC_MAX_VAL_LEN
964                #
965                if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(str(val_value)) ) > METRIC_MAX_VAL_LEN:
[507]966
[691]967                    # It's too big, we need to make a new gmetric for the additional info
968                    #
969                    gval_lists.append( val_list )
[507]970
[691]971                    val_list        = { }
[507]972
[691]973                val_list[ val_name ]    = val_value
[507]974
[691]975        if len( val_list ) > 0:
[507]976
[691]977            gval_lists.append( val_list )
[507]978
[691]979        str_list    = [ ]
[507]980
[691]981        # Now append the value names and values together, i.e.: stop_timestamp=value, etc
982        #
983        for val_list in gval_lists:
[507]984
[691]985            my_val_str    = None
[507]986
[691]987            for val_name, val_value in val_list.items():
[507]988
[691]989                if type(val_value) == list:
[579]990
[691]991                    val_value    = val_value.join( ',' )
[579]992
[691]993                if my_val_str:
[507]994
[691]995                    try:
996                        # fixme: It's getting
997                        # ('nodes', None) items
998                        my_val_str = my_val_str + ' ' + val_name + '=' + val_value
999                    except:
1000                        pass
[623]1001
[691]1002                else:
1003                    my_val_str = val_name + '=' + val_value
[507]1004
[691]1005            str_list.append( my_val_str )
[507]1006
[691]1007        return str_list
[507]1008
[691]1009    def daemon( self ):
[355]1010
[691]1011        """Run as daemon forever"""
[256]1012
[691]1013        # Fork the first child
1014        #
1015        pid = os.fork()
1016        if pid > 0:
1017            sys.exit(0)  # end parent
[256]1018
[691]1019        # creates a session and sets the process group ID
1020        #
1021        os.setsid()
[318]1022
[691]1023        # Fork the second child
1024        #
1025        pid = os.fork()
1026        if pid > 0:
1027            sys.exit(0)  # end parent
[318]1028
[691]1029        write_pidfile()
[318]1030
[691]1031        # Go to the root directory and set the umask
1032        #
1033        os.chdir('/')
1034        os.umask(0)
[318]1035
[691]1036        sys.stdin.close()
1037        sys.stdout.close()
1038        sys.stderr.close()
[318]1039
[691]1040        os.open('/dev/null', os.O_RDWR)
1041        os.dup2(0, 1)
1042        os.dup2(0, 2)
[318]1043
[691]1044        self.run()
[318]1045
[691]1046    def run( self ):
[355]1047
[691]1048        """Main thread"""
[256]1049
[691]1050        while ( 1 ):
1051       
1052            self.getJobData()
1053            self.submitJobData()
1054            time.sleep( BATCH_POLL_INTERVAL )   
[256]1055
[623]1056# SGE code by Dave Love <fx@gnu.org>.  Tested with SGE 6.0u8 and 6.0u11.  May
1057# work with SGE 6.1 (else should be easily fixable), but definitely doesn't
1058# with 6.2.  See also the fixmes.
[256]1059
[507]1060class NoJobs (Exception):
[691]1061    """Exception raised by empty job list in qstat output."""
1062    pass
[256]1063
[507]1064class SgeQstatXMLParser(xml.sax.handler.ContentHandler):
[691]1065    """SAX handler for XML output from Sun Grid Engine's `qstat'."""
[318]1066
[691]1067    def __init__(self):
1068        self.value = ""
1069        self.joblist = []
1070        self.job = {}
1071        self.queue = ""
1072        self.in_joblist = False
1073        self.lrequest = False
1074        self.eltq = deque()
1075        xml.sax.handler.ContentHandler.__init__(self)
[318]1076
[691]1077    # The structure of the output is as follows (for SGE 6.0).  It's
1078    # similar for 6.1, but radically different for 6.2, and is
1079    # undocumented generally.  Unfortunately it's voluminous, and probably
1080    # doesn't scale to large clusters/queues.
[318]1081
[691]1082    # <detailed_job_info  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
1083    #   <djob_info>
1084    #     <qmaster_response>  <!-- job -->
1085    #       ...
1086    #       <JB_ja_template> 
1087    #     <ulong_sublist>
1088    #     ...         <!-- start_time, state ... -->
1089    #     </ulong_sublist>
1090    #       </JB_ja_template> 
1091    #       <JB_ja_tasks>
1092    #     <ulong_sublist>
1093    #       ...       <!-- task info
1094    #     </ulong_sublist>
1095    #     ...
1096    #       </JB_ja_tasks>
1097    #       ...
1098    #     </qmaster_response>
1099    #   </djob_info>
1100    #   <messages>
1101    #   ...
[318]1102
[691]1103    # NB.  We might treat each task as a separate job, like
1104    # straight qstat output, but the web interface expects jobs to
1105    # be identified by integers, not, say, <job number>.<task>.
[318]1106
[691]1107    # So, I lied.  If the job list is empty, we get invalid XML
1108    # like this, which we need to defend against:
[318]1109
[691]1110    # <unknown_jobs  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
1111    #   <>
1112    #     <ST_name>*</ST_name>
1113    #   </>
1114    # </unknown_jobs>
[318]1115
[691]1116    def startElement(self, name, attrs):
1117        self.value = ""
1118        if name == "djob_info":    # job list
1119            self.in_joblist = True
1120        # The job container is "qmaster_response" in SGE 6.0
1121        # and 6.1, but "element" in 6.2.  This is only the very
1122        # start of what's necessary for 6.2, though (sigh).
1123        elif (name == "qmaster_response" or name == "element") \
1124                and self.eltq[-1] == "djob_info": # job
1125            self.job = {"job_state": "U", "slots": 0,
1126                    "nodes": [], "queued_timestamp": "",
1127                    "queued_timestamp": "", "queue": "",
1128                    "ppn": "0", "RN_max": 0,
1129                    # fixme in endElement
1130                    "requested_memory": 0, "requested_time": 0
1131                    }
1132            self.joblist.append(self.job)
1133        elif name == "qstat_l_requests": # resource request
1134            self.lrequest = True
1135        elif name == "unknown_jobs":
1136            raise NoJobs
1137        self.eltq.append (name)
[318]1138
[691]1139    def characters(self, ch):
1140        self.value += ch
[318]1141
[691]1142    def endElement(self, name): 
1143        """Snarf job elements contents into job dictionary.
1144           Translate keys if appropriate."""
[318]1145
[691]1146        name_trans = {
1147          "JB_job_number": "number",
1148          "JB_job_name": "name", "JB_owner": "owner",
1149          "queue_name": "queue", "JAT_start_time": "start_timestamp",
1150          "JB_submission_time": "queued_timestamp"
1151          }
1152        value = self.value
1153        self.eltq.pop ()
[318]1154
[691]1155        if name == "djob_info":
1156            self.in_joblist = False
1157            self.job = {}
1158        elif name == "JAT_master_queue":
1159            self.job["queue"] = value.split("@")[0]
1160        elif name == "JG_qhostname":
1161            if not (value in self.job["nodes"]):
1162                self.job["nodes"].append(value)
1163        elif name == "JG_slots": # slots in use
1164            self.job["slots"] += int(value)
1165        elif name == "RN_max": # requested slots (tasks or parallel)
1166            self.job["RN_max"] = max (self.job["RN_max"],
1167                          int(value))
1168        elif name == "JAT_state": # job state (bitwise or)
1169            value = int (value)
1170            # Status values from sge_jobL.h
1171            #define JIDLE           0x00000000
1172            #define JHELD           0x00000010
1173            #define JMIGRATING          0x00000020
1174            #define JQUEUED         0x00000040
1175            #define JRUNNING        0x00000080
1176            #define JSUSPENDED          0x00000100
1177            #define JTRANSFERING        0x00000200
1178            #define JDELETED        0x00000400
1179            #define JWAITING        0x00000800
1180            #define JEXITING        0x00001000
1181            #define JWRITTEN        0x00002000
1182            #define JSUSPENDED_ON_THRESHOLD 0x00010000
1183            #define JFINISHED           0x00010000
1184            if value & 0x80:
1185                self.job["status"] = "R"
1186            elif value & 0x40:
1187                self.job["status"] = "Q"
1188            else:
1189                self.job["status"] = "O" # `other'
1190        elif name == "CE_name" and self.lrequest and self.value in \
1191                ("h_cpu", "s_cpu", "cpu", "h_core", "s_core"):
1192            # We're in a container for an interesting resource
1193            # request; record which type.
1194            self.lrequest = self.value
1195        elif name == "CE_doubleval" and self.lrequest:
1196            # if we're in a container for an interesting
1197            # resource request, use the maxmimum of the hard
1198            # and soft requests to record the requested CPU
1199            # or core.  Fixme:  I'm not sure if this logic is
1200            # right.
1201            if self.lrequest in ("h_core", "s_core"):
1202                self.job["requested_memory"] = \
1203                    max (float (value),
1204                     self.job["requested_memory"])
1205            # Fixme:  Check what cpu means, c.f [hs]_cpu.
1206            elif self.lrequest in ("h_cpu", "s_cpu", "cpu"):
1207                self.job["requested_time"] = \
1208                    max (float (value),
1209                     self.job["requested_time"])
1210        elif name == "qstat_l_requests":
1211            self.lrequest = False
1212        elif self.job and self.in_joblist:
1213            if name in name_trans:
1214                name = name_trans[name]
1215                self.job[name] = value
[318]1216
[507]1217# Abstracted from PBS original.
1218# Fixme:  Is it worth (or appropriate for PBS) sorting the result?
[520]1219#
1220def do_nodelist( nodes ):
1221
[691]1222    """Translate node list as appropriate."""
[520]1223
[691]1224    nodeslist        = [ ]
1225    my_domain        = fqdn_parts( socket.getfqdn() )[1]
[520]1226
[691]1227    for node in nodes:
[520]1228
[691]1229        host        = node.split( '/' )[0] # not relevant for SGE
1230        h, host_domain    = fqdn_parts(host)
[520]1231
[691]1232        if host_domain == my_domain:
[520]1233
[691]1234            host    = h
[520]1235
[691]1236        if nodeslist.count( host ) == 0:
[520]1237
[691]1238            for translate_pattern in BATCH_HOST_TRANSLATE:
[520]1239
[691]1240                if translate_pattern.find( '/' ) != -1:
[520]1241
[691]1242                    translate_orig    = \
1243                        translate_pattern.split( '/' )[1]
1244                    translate_new    = \
1245                        translate_pattern.split( '/' )[2]
1246                    host = re.sub( translate_orig,
1247                               translate_new, host )
1248            if not host in nodeslist:
1249                nodeslist.append( host )
1250    return nodeslist
[318]1251
[837]1252class SLURMDataGatherer( DataGatherer ):
1253
1254    global pyslurm
1255
1256    """This is the DataGatherer for SLURM"""
1257
1258    def __init__( self ):
1259
1260        """Setup appropriate variables"""
1261
1262        self.jobs       = { }
1263        self.timeoffset = 0
1264        self.dp         = DataProcessor()
1265
1266    def getNodeData( self ):
1267
1268        slurm_type = pyslurm.node()
1269
1270        nodedict = slurm_type.get()
1271
1272        return nodedict
1273
1274    def getJobData( self ):
1275
1276        """Gather all data on current jobs"""
1277
1278        joblist            = {}
1279
1280        self.cur_time  = time.time()
1281
1282        slurm_type = pyslurm.job()
1283        joblist    = slurm_type.get()
1284
1285        jobs_processed    = [ ]
1286
1287        for name, attrs in joblist.items():
1288            display_queue = 1
1289            job_id        = name
1290
1291            name          = self.getAttr( attrs, 'name' )
1292            queue         = self.getAttr( attrs, 'partition' )
1293
1294            if QUEUE:
1295                for q in QUEUE:
1296                    if q == queue:
1297                        display_queue = 1
1298                        break
1299                    else:
1300                        display_queue = 0
1301                        continue
1302            if display_queue == 0:
1303                continue
1304
1305            owner_uid        = attrs[ 'user_id' ]
1306            ( owner, owner_pw, owner_uid, owner_gid, owner_gecos, owner_dir, owner_shell ) = pwd.getpwuid( owner_uid )
1307
1308            requested_time   = self.getAttr( attrs, 'time_limit' )
[852]1309            min_memory       = self.getAttr( attrs, 'pn_min_memory' )
[837]1310
[852]1311            if min_memory == 0:
1312
1313                requested_memory = ''
1314
1315            else:
1316                requested_memory = min_memory
1317
[853]1318            min_cpus = self.getAttr( attrs, 'pn_min_cpus' )
[837]1319
[853]1320            if min_cpus == 0:
1321
1322                ppn = ''
1323
1324            else:
1325                ppn = min_cpus
1326
[837]1327            ( something, status_long ) = self.getAttr( attrs, 'job_state' )
1328
1329            status = 'Q'
1330
1331            if status_long == 'RUNNING':
1332
1333                status = 'R'
1334
1335            elif status_long == 'COMPLETED':
1336
1337                continue
1338
1339            jobs_processed.append( job_id )
1340
1341            queued_timestamp = self.getAttr( attrs, 'submit_time' )
1342
1343            start_timestamp = ''
1344            nodeslist       = ''
1345
1346            if status == 'R':
1347
1348                start_timestamp = self.getAttr( attrs, 'start_time' )
[851]1349                nodes           = attrs[ 'nodes' ]
[837]1350
[851]1351                if not nodes:
[837]1352
[851]1353                    # This should not happen
1354
1355                    # Something wrong: running but 'nodes' returned empty by pyslurm
1356                    # Possible pyslurm bug: abort/quit/warning
1357
1358                    err_msg = 'FATAL ERROR: job %s running but nodes returned empty: pyslurm bugged?' %job_id
1359
1360                    print err_msg
1361                    debug_msg( 0, err_msg )
1362                    sys.exit(1)
1363
1364                my_nodelist = [ ]
1365
1366                slurm_hostlist  = pyslurm.hostlist()
1367                slurm_hostlist.create( nodes )
1368                slurm_hostlist.uniq()
1369
1370                while slurm_hostlist.count() > 0:
1371
1372                    my_nodelist.append( slurm_hostlist.pop() )
1373
1374                slurm_hostlist.destroy()
1375
1376                del slurm_hostlist
1377
1378                nodeslist       = do_nodelist( my_nodelist )
1379
[837]1380                if DETECT_TIME_DIFFS:
1381
1382                    # If a job start if later than our current date,
1383                    # that must mean the Torque server's time is later
1384                    # than our local time.
1385               
1386                    if int( start_timestamp ) > int( int( self.cur_time ) + int( self.timeoffset ) ):
1387
1388                        self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
1389
1390            elif status == 'Q':
1391
1392                nodeslist       = str( attrs[ 'num_nodes' ] )
1393
1394            else:
1395                start_timestamp = ''
1396                nodeslist       = ''
1397
1398            myAttrs                = { }
1399
1400            myAttrs[ 'name' ]             = str( name )
1401            myAttrs[ 'queue' ]            = str( queue )
1402            myAttrs[ 'owner' ]            = str( owner )
1403            myAttrs[ 'requested_time' ]   = str( requested_time )
1404            myAttrs[ 'requested_memory' ] = str( requested_memory )
1405            myAttrs[ 'ppn' ]              = str( ppn )
1406            myAttrs[ 'status' ]           = str( status )
1407            myAttrs[ 'start_timestamp' ]  = str( start_timestamp )
1408            myAttrs[ 'queued_timestamp' ] = str( queued_timestamp )
1409            myAttrs[ 'reported' ]         = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1410            myAttrs[ 'nodes' ]            = nodeslist
1411            myAttrs[ 'domain' ]           = fqdn_parts( socket.getfqdn() )[1]
1412            myAttrs[ 'poll_interval' ]    = str( BATCH_POLL_INTERVAL )
1413
1414            if self.jobDataChanged( self.jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
1415
1416                self.jobs[ job_id ] = myAttrs
1417
1418        for id, attrs in self.jobs.items():
1419
1420            if id not in jobs_processed:
1421
1422                # This one isn't there anymore; toedeledoki!
1423                #
1424                del self.jobs[ id ]
1425
[318]1426class SgeDataGatherer(DataGatherer):
1427
[691]1428    jobs = {}
[61]1429
[691]1430    def __init__( self ):
1431        self.jobs = {}
1432        self.timeoffset = 0
1433        self.dp = DataProcessor()
[318]1434
[691]1435    def getJobData( self ):
1436        """Gather all data on current jobs in SGE"""
[318]1437
[691]1438        import popen2
[318]1439
[691]1440        self.cur_time = 0
1441        queues = ""
1442        if QUEUE:    # only for specific queues
1443            # Fixme:  assumes queue names don't contain single
1444            # quote or comma.  Don't know what the SGE rules are.
1445            queues = " -q '" + string.join (QUEUE, ",") + "'"
1446        # Note the comment in SgeQstatXMLParser about scaling with
1447        # this method of getting data.  I haven't found better one.
1448        # Output with args `-xml -ext -f -r' is easier to parse
1449        # in some ways, harder in others, but it doesn't provide
1450        # the submission time (at least SGE 6.0).  The pipeline
1451        # into sed corrects bogus XML observed with a configuration
1452        # of SGE 6.0u8, which otherwise causes the parsing to hang.
1453        piping = popen2.Popen3("qstat -u '*' -j '*' -xml | \
[623]1454sed -e 's/reported usage>/reported_usage>/g' -e 's;<\/*JATASK:.*>;;'" \
[691]1455                           + queues, True)
1456        qstatparser = SgeQstatXMLParser()
1457        parse_err = 0
1458        try:
1459            xml.sax.parse(piping.fromchild, qstatparser)
1460        except NoJobs:
1461            pass
1462        except:
1463            parse_err = 1
[704]1464        if piping.wait():
1465            debug_msg(10, "qstat error, skipping until next polling interval: " + piping.childerr.readline())
[691]1466            return None
1467        elif parse_err:
1468            debug_msg(10, "Bad XML output from qstat"())
1469            exit (1)
1470        for f in piping.fromchild, piping.tochild, piping.childerr:
1471            f.close()
1472        self.cur_time = time.time()
1473        jobs_processed = []
1474        for job in qstatparser.joblist:
1475            job_id = job["number"]
1476            if job["status"] in [ 'Q', 'R' ]:
1477                jobs_processed.append(job_id)
1478            if job["status"] == "R":
1479                job["nodes"] = do_nodelist (job["nodes"])
1480                # Fixme: why is job["nodes"] sometimes null?
1481                try:
1482                    # Fixme: Is this sensible?  The
1483                    # PBS-type PPN isn't something you use
1484                    # with SGE.
[704]1485                    job["ppn"] = float(job["slots"]) / len(job["nodes"])
[691]1486                except:
1487                    job["ppn"] = 0
1488                if DETECT_TIME_DIFFS:
1489                    # If a job start is later than our
1490                    # current date, that must mean
1491                    # the SGE server's time is later
1492                    # than our local time.
[704]1493                    start_timestamp = int (job["start_timestamp"])
1494                    if start_timestamp > int(self.cur_time) + int(self.timeoffset):
[318]1495
[704]1496                        self.timeoffset    = start_timestamp - int(self.cur_time)
[691]1497            else:
1498                # fixme: Note sure what this should be:
1499                job["ppn"] = job["RN_max"]
1500                job["nodes"] = "1"
[318]1501
[691]1502            myAttrs = {}
1503            for attr in ["name", "queue", "owner",
1504                     "requested_time", "status",
1505                     "requested_memory", "ppn",
1506                     "start_timestamp", "queued_timestamp"]:
1507                myAttrs[attr] = str(job[attr])
1508            myAttrs["nodes"] = job["nodes"]
[704]1509            myAttrs["reported"] = str(int(self.cur_time) + int(self.timeoffset))
[691]1510            myAttrs["domain"] = fqdn_parts(socket.getfqdn())[1]
1511            myAttrs["poll_interval"] = str(BATCH_POLL_INTERVAL)
[318]1512
[704]1513            if self.jobDataChanged(self.jobs, job_id, myAttrs) and myAttrs["status"] in ["R", "Q"]:
[691]1514                self.jobs[job_id] = myAttrs
1515        for id, attrs in self.jobs.items():
1516            if id not in jobs_processed:
1517                del self.jobs[id]
[318]1518
[524]1519# LSF code by Mahmoud Hanafi <hanafim@users.sourceforge.nt>
1520# Requres LSFObject http://sourceforge.net/projects/lsfobject
1521#
1522class LsfDataGatherer(DataGatherer):
[525]1523
[691]1524    """This is the DataGatherer for LSf"""
[524]1525
[691]1526    global lsfObject
[524]1527
[691]1528    def __init__( self ):
[525]1529
[691]1530        self.jobs = { }
1531        self.timeoffset = 0
1532        self.dp = DataProcessor()
1533        self.initLsfQuery()
[524]1534
[691]1535    def _countDuplicatesInList( self, dupedList ):
[525]1536
[691]1537        countDupes    = { }
[525]1538
[691]1539        for item in dupedList:
[525]1540
[691]1541            if not countDupes.has_key( item ):
[525]1542
[691]1543                countDupes[ item ]    = 1
1544            else:
1545                countDupes[ item ]    = countDupes[ item ] + 1
[525]1546
[691]1547        dupeCountList    = [ ]
[525]1548
[691]1549        for item, count in countDupes.items():
[525]1550
[691]1551            dupeCountList.append( ( item, count ) )
[525]1552
[691]1553        return dupeCountList
[524]1554#
1555#lst = ['I1','I2','I1','I3','I4','I4','I7','I7','I7','I7','I7']
1556#print _countDuplicatesInList(lst)
1557#[('I1', 2), ('I3', 1), ('I2', 1), ('I4', 2), ('I7', 5)]
1558########################
1559
[691]1560    def initLsfQuery( self ):
1561        self.pq = None
1562        self.pq = lsfObject.jobInfoEntObject()
[524]1563
[691]1564    def getJobData( self, known_jobs="" ):
1565        """Gather all data on current jobs in LSF"""
1566        if len( known_jobs ) > 0:
1567            jobs = known_jobs
1568        else:
1569            jobs = { }
1570        joblist = {}
1571        joblist = self.pq.getJobInfo()
1572        nodelist = ''
[524]1573
[691]1574        self.cur_time = time.time()
[524]1575
[691]1576        jobs_processed = [ ]
[524]1577
[691]1578        for name, attrs in joblist.items():
1579            job_id = str(name)
1580            jobs_processed.append( job_id )
1581            name = self.getAttr( attrs, 'jobName' )
1582            queue = self.getAttr( self.getAttr( attrs, 'submit') , 'queue' )
1583            owner = self.getAttr( attrs, 'user' )
[524]1584
1585### THIS IS THE rLimit List index values
[691]1586#define LSF_RLIMIT_CPU      0        /* cpu time in milliseconds */
1587#define LSF_RLIMIT_FSIZE    1        /* maximum file size */
1588#define LSF_RLIMIT_DATA     2        /* data size */
1589#define LSF_RLIMIT_STACK    3        /* stack size */
1590#define LSF_RLIMIT_CORE     4        /* core file size */
1591#define LSF_RLIMIT_RSS      5        /* resident set size */
1592#define LSF_RLIMIT_NOFILE   6        /* open files */
1593#define LSF_RLIMIT_OPEN_MAX 7        /* (from HP-UX) */
1594#define LSF_RLIMIT_VMEM     8        /* maximum swap mem */
[524]1595#define LSF_RLIMIT_SWAP     8
[691]1596#define LSF_RLIMIT_RUN      9        /* max wall-clock time limit */
1597#define LSF_RLIMIT_PROCESS  10       /* process number limit */
1598#define LSF_RLIMIT_THREAD   11       /* thread number limit (introduced in LSF6.0) */
1599#define LSF_RLIM_NLIMITS    12       /* number of resource limits */
[524]1600
[691]1601            requested_time = self.getAttr( self.getAttr( attrs, 'submit') , 'rLimits' )[9]
1602            if requested_time == -1: 
1603                requested_time = ""
1604            requested_memory = self.getAttr( self.getAttr( attrs, 'submit') , 'rLimits' )[8]
1605            if requested_memory == -1: 
1606                requested_memory = ""
[524]1607# This tries to get proc per node. We don't support this right now
[691]1608            ppn = 0 #self.getAttr( self.getAttr( attrs, 'SubmitList') , 'numProessors' )
1609            requested_cpus = self.getAttr( self.getAttr( attrs, 'submit') , 'numProcessors' )
1610            if requested_cpus == None or requested_cpus == "":
1611                requested_cpus = 1
[524]1612
[691]1613            if QUEUE:
1614                for q in QUEUE:
1615                    if q == queue:
1616                        display_queue = 1
1617                        break
1618                    else:
1619                        display_queue = 0
1620                        continue
1621            if display_queue == 0:
1622                continue
[524]1623
[691]1624            runState = self.getAttr( attrs, 'status' )
1625            if runState == 4:
1626                status = 'R'
1627            else:
1628                status = 'Q'
1629            queued_timestamp = self.getAttr( attrs, 'submitTime' )
[524]1630
[691]1631            if status == 'R':
1632                start_timestamp = self.getAttr( attrs, 'startTime' )
1633                nodesCpu =  dict(self._countDuplicatesInList(self.getAttr( attrs, 'exHosts' )))
1634                nodelist = nodesCpu.keys()
[524]1635
[691]1636                if DETECT_TIME_DIFFS:
[524]1637
[691]1638                    # If a job start if later than our current date,
1639                    # that must mean the Torque server's time is later
1640                    # than our local time.
[524]1641
[691]1642                    if int(start_timestamp) > int( int(self.cur_time) + int(self.timeoffset) ):
[524]1643
[691]1644                        self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
[524]1645
[691]1646            elif status == 'Q':
1647                start_timestamp = ''
1648                count_mynodes = 0
1649                numeric_node = 1
1650                nodelist = ''
[524]1651
[691]1652            myAttrs = { }
1653            if name == "":
1654                myAttrs['name'] = "none"
1655            else:
1656                myAttrs['name'] = name
[524]1657
[691]1658            myAttrs[ 'owner' ]        = owner
1659            myAttrs[ 'requested_time' ]    = str(requested_time)
1660            myAttrs[ 'requested_memory' ]    = str(requested_memory)
1661            myAttrs[ 'requested_cpus' ]    = str(requested_cpus)
1662            myAttrs[ 'ppn' ]        = str( ppn )
1663            myAttrs[ 'status' ]        = status
1664            myAttrs[ 'start_timestamp' ]    = str(start_timestamp)
1665            myAttrs[ 'queue' ]        = str(queue)
1666            myAttrs[ 'queued_timestamp' ]    = str(queued_timestamp)
1667            myAttrs[ 'reported' ]        = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1668            myAttrs[ 'nodes' ]        = do_nodelist( nodelist )
1669            myAttrs[ 'domain' ]        = fqdn_parts( socket.getfqdn() )[1]
1670            myAttrs[ 'poll_interval' ]    = str(BATCH_POLL_INTERVAL)
[524]1671
[691]1672            if self.jobDataChanged( jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
1673                jobs[ job_id ] = myAttrs
[524]1674
[691]1675                debug_msg( 10, printTime() + ' job %s state changed' %(job_id) )
[524]1676
[691]1677        for id, attrs in jobs.items():
1678            if id not in jobs_processed:
1679                # This one isn't there anymore
1680                #
1681                del jobs[ id ]
1682        self.jobs=jobs
[524]1683
1684
[355]1685class PbsDataGatherer( DataGatherer ):
[318]1686
[691]1687    """This is the DataGatherer for PBS and Torque"""
[318]1688
[691]1689    global PBSQuery, PBSError
[256]1690
[691]1691    def __init__( self ):
[354]1692
[691]1693        """Setup appropriate variables"""
[23]1694
[785]1695        self.jobs       = { }
1696        self.timeoffset = 0
1697        self.dp         = DataProcessor()
[354]1698
[691]1699        self.initPbsQuery()
[23]1700
[691]1701    def initPbsQuery( self ):
[91]1702
[785]1703        self.pq = None
[354]1704
[788]1705        try:
[354]1706
[788]1707            if( BATCH_SERVER ):
[91]1708
[788]1709                self.pq = PBSQuery( BATCH_SERVER )
1710            else:
1711                self.pq = PBSQuery()
1712
1713        except PBSError, details:
1714            print 'Cannot connect to pbs server'
1715            print details
1716            sys.exit( 1 )
1717
[691]1718        try:
[791]1719            # TODO: actually use new data structure
[691]1720            self.pq.old_data_structure()
[656]1721
[691]1722        except AttributeError:
[656]1723
[691]1724            # pbs_query is older
1725            #
1726            pass
[656]1727
[790]1728    def getNodeData( self ):
1729
1730        nodedict = { }
1731
1732        try:
1733            nodedict = self.pq.getnodes()
1734
1735        except PBSError, detail:
1736
1737            debug_msg( 10, "PBS server unavailable, skipping until next polling interval: " + str( detail ) )
1738
1739        return nodedict
1740
[691]1741    def getJobData( self ):
[354]1742
[691]1743        """Gather all data on current jobs in Torque"""
[26]1744
[785]1745        joblist            = {}
1746        self.cur_time      = 0
[349]1747
[691]1748        try:
1749            joblist        = self.pq.getjobs()
[785]1750            self.cur_time  = time.time()
[354]1751
[691]1752        except PBSError, detail:
[354]1753
[790]1754            debug_msg( 10, "PBS server unavailable, skipping until next polling interval: " + str( detail ) )
[691]1755            return None
[354]1756
[691]1757        jobs_processed    = [ ]
[26]1758
[691]1759        for name, attrs in joblist.items():
[785]1760            display_queue = 1
1761            job_id        = name.split( '.' )[0]
[26]1762
[785]1763            name          = self.getAttr( attrs, 'Job_Name' )
1764            queue         = self.getAttr( attrs, 'queue' )
[317]1765
[691]1766            if QUEUE:
1767                for q in QUEUE:
1768                    if q == queue:
1769                        display_queue = 1
1770                        break
1771                    else:
1772                        display_queue = 0
1773                        continue
1774            if display_queue == 0:
1775                continue
[317]1776
1777
[691]1778            owner            = self.getAttr( attrs, 'Job_Owner' ).split( '@' )[0]
[785]1779            requested_time   = self.getAttr( attrs, 'Resource_List.walltime' )
1780            requested_memory = self.getAttr( attrs, 'Resource_List.mem' )
[95]1781
[785]1782            mynoderequest    = self.getAttr( attrs, 'Resource_List.nodes' )
[95]1783
[785]1784            ppn = ''
[281]1785
[691]1786            if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
[95]1787
[785]1788                mynoderequest_fields = mynoderequest.split( ':' )
[281]1789
[691]1790                for mynoderequest_field in mynoderequest_fields:
[281]1791
[691]1792                    if mynoderequest_field.find( 'ppn' ) != -1:
[281]1793
[785]1794                        ppn = mynoderequest_field.split( 'ppn=' )[1]
[281]1795
[785]1796            status = self.getAttr( attrs, 'job_state' )
[25]1797
[691]1798            if status in [ 'Q', 'R' ]:
[450]1799
[691]1800                jobs_processed.append( job_id )
[450]1801
[785]1802            queued_timestamp = self.getAttr( attrs, 'ctime' )
[243]1803
[691]1804            if status == 'R':
[133]1805
[785]1806                start_timestamp = self.getAttr( attrs, 'mtime' )
1807                nodes           = self.getAttr( attrs, 'exec_host' ).split( '+' )
[133]1808
[785]1809                nodeslist       = do_nodelist( nodes )
[354]1810
[691]1811                if DETECT_TIME_DIFFS:
[185]1812
[691]1813                    # If a job start if later than our current date,
1814                    # that must mean the Torque server's time is later
1815                    # than our local time.
1816               
1817                    if int( start_timestamp ) > int( int( self.cur_time ) + int( self.timeoffset ) ):
[185]1818
[785]1819                        self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
[185]1820
[691]1821            elif status == 'Q':
[95]1822
[691]1823                # 'mynodequest' can be a string in the following syntax according to the
1824                # Torque Administator's manual:
1825                #
1826                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1827                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1828                # etc
1829                #
[451]1830
[691]1831                #
1832                # For now we only count the amount of nodes request and ignore properties
1833                #
[451]1834
[785]1835                start_timestamp = ''
1836                count_mynodes   = 0
[354]1837
[691]1838                for node in mynoderequest.split( '+' ):
[67]1839
[691]1840                    # Just grab the {node_count|hostname} part and ignore properties
1841                    #
[785]1842                    nodepart     = node.split( ':' )[0]
[67]1843
[691]1844                    # Let's assume a node_count value
1845                    #
[785]1846                    numeric_node = 1
[451]1847
[691]1848                    # Chop the value up into characters
1849                    #
1850                    for letter in nodepart:
[67]1851
[691]1852                        # If this char is not a digit (0-9), this must be a hostname
1853                        #
1854                        if letter not in string.digits:
[133]1855
[785]1856                            numeric_node = 0
[133]1857
[691]1858                    # If this is a hostname, just count this as one (1) node
1859                    #
1860                    if not numeric_node:
[354]1861
[785]1862                        count_mynodes = count_mynodes + 1
[691]1863                    else:
[451]1864
[691]1865                        # If this a number, it must be the node_count
1866                        # and increase our count with it's value
1867                        #
1868                        try:
[785]1869                            count_mynodes = count_mynodes + int( nodepart )
[354]1870
[691]1871                        except ValueError, detail:
[354]1872
[691]1873                            # When we arrive here I must be bugged or very confused
1874                            # THIS SHOULD NOT HAPPEN!
1875                            #
1876                            debug_msg( 10, str( detail ) )
1877                            debug_msg( 10, "Encountered weird node in Resources_List?!" )
1878                            debug_msg( 10, 'nodepart = ' + str( nodepart ) )
1879                            debug_msg( 10, 'job = ' + str( name ) )
1880                            debug_msg( 10, 'attrs = ' + str( attrs ) )
1881                       
[785]1882                nodeslist       = str( count_mynodes )
[691]1883            else:
[785]1884                start_timestamp = ''
1885                nodeslist       = ''
[133]1886
[691]1887            myAttrs                = { }
[26]1888
[785]1889            myAttrs[ 'name' ]             = str( name )
1890            myAttrs[ 'queue' ]            = str( queue )
1891            myAttrs[ 'owner' ]            = str( owner )
1892            myAttrs[ 'requested_time' ]   = str( requested_time )
1893            myAttrs[ 'requested_memory' ] = str( requested_memory )
1894            myAttrs[ 'ppn' ]              = str( ppn )
1895            myAttrs[ 'status' ]           = str( status )
1896            myAttrs[ 'start_timestamp' ]  = str( start_timestamp )
1897            myAttrs[ 'queued_timestamp' ] = str( queued_timestamp )
1898            myAttrs[ 'reported' ]         = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1899            myAttrs[ 'nodes' ]            = nodeslist
1900            myAttrs[ 'domain' ]           = fqdn_parts( socket.getfqdn() )[1]
[691]1901            myAttrs[ 'poll_interval' ]    = str( BATCH_POLL_INTERVAL )
[354]1902
[691]1903            if self.jobDataChanged( self.jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
[61]1904
[785]1905                self.jobs[ job_id ] = myAttrs
[26]1906
[691]1907        for id, attrs in self.jobs.items():
[76]1908
[691]1909            if id not in jobs_processed:
[76]1910
[691]1911                # This one isn't there anymore; toedeledoki!
1912                #
1913                del self.jobs[ id ]
[76]1914
[362]1915GMETRIC_DEFAULT_TYPE    = 'string'
1916GMETRIC_DEFAULT_HOST    = '127.0.0.1'
1917GMETRIC_DEFAULT_PORT    = '8649'
[700]1918GMETRIC_DEFAULT_UNITS   = ''
[362]1919
1920class Gmetric:
1921
[691]1922    global GMETRIC_DEFAULT_HOST, GMETRIC_DEFAULT_PORT
[362]1923
[700]1924    slope           = { 'zero' : 0, 'positive' : 1, 'negative' : 2, 'both' : 3, 'unspecified' : 4 }
1925    type            = ( '', 'string', 'uint16', 'int16', 'uint32', 'int32', 'float', 'double', 'timestamp' )
1926    protocol        = ( 'udp', 'multicast' )
[362]1927
[691]1928    def __init__( self, host=GMETRIC_DEFAULT_HOST, port=GMETRIC_DEFAULT_PORT ):
[700]1929               
[691]1930        global GMETRIC_DEFAULT_TYPE
[362]1931
[691]1932        self.prot       = self.checkHostProtocol( host )
[700]1933        self.data_msg   = xdrlib.Packer()
1934        self.meta_msg   = xdrlib.Packer()
[691]1935        self.socket     = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
[362]1936
[691]1937        if self.prot not in self.protocol:
[362]1938
[691]1939            raise ValueError( "Protocol must be one of: " + str( self.protocol ) )
[362]1940
[691]1941        if self.prot == 'multicast':
[362]1942
[691]1943            # Set multicast options
1944            #
1945            self.socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20 )
[362]1946
[691]1947        self.hostport   = ( host, int( port ) )
1948        self.slopestr   = 'both'
1949        self.tmax       = 60
[362]1950
[691]1951    def checkHostProtocol( self, ip ):
[362]1952
[691]1953        """Detect if a ip adress is a multicast address"""
[471]1954
[691]1955        MULTICAST_ADDRESS_MIN   = ( "224", "0", "0", "0" )
1956        MULTICAST_ADDRESS_MAX   = ( "239", "255", "255", "255" )
[362]1957
[700]1958        ip_fields               = ip.split( '.' )
[362]1959
[691]1960        if ip_fields >= MULTICAST_ADDRESS_MIN and ip_fields <= MULTICAST_ADDRESS_MAX:
[362]1961
[691]1962            return 'multicast'
1963        else:
1964            return 'udp'
[362]1965
[691]1966    def send( self, name, value, dmax, typestr = '', units = '' ):
[362]1967
[691]1968        if len( units ) == 0:
[700]1969            units       = GMETRIC_DEFAULT_UNITS
[471]1970
[691]1971        if len( typestr ) == 0:
[700]1972            typestr     = GMETRIC_DEFAULT_TYPE
[362]1973
[700]1974        (meta_msg, data_msg) = self.makexdr( name, value, typestr, units, self.slopestr, self.tmax, dmax )
[409]1975
[700]1976        meta_rt = self.socket.sendto( meta_msg, self.hostport )
1977        data_rt = self.socket.sendto( data_msg, self.hostport )
[362]1978
[700]1979        return ( meta_rt, data_rt )
[362]1980
[700]1981    def makexdr( self, name, value, typestr, unitstr, slopestr, tmax, dmax, group=None, spoof=None ):
1982
1983        hostname = "unset"
1984
[691]1985        if slopestr not in self.slope:
[362]1986
[691]1987            raise ValueError( "Slope must be one of: " + str( self.slope.keys() ) )
[362]1988
[691]1989        if typestr not in self.type:
[362]1990
[691]1991            raise ValueError( "Type must be one of: " + str( self.type ) )
[362]1992
[691]1993        if len( name ) == 0:
[362]1994
[691]1995            raise ValueError( "Name must be non-empty" )
[362]1996
[700]1997        self.meta_msg.reset()
1998        self.meta_msg.pack_int( 128 )
[362]1999
[700]2000        if not spoof:
2001            self.meta_msg.pack_string( hostname )
2002        else:
2003            self.meta_msg.pack_string( spoof )
[362]2004
[700]2005        self.meta_msg.pack_string( name )
2006
2007        if not spoof:
2008            self.meta_msg.pack_int( 0 )
2009        else:
2010            self.meta_msg.pack_int( 1 )
2011           
2012        self.meta_msg.pack_string( typestr )
2013        self.meta_msg.pack_string( name )
2014        self.meta_msg.pack_string( unitstr )
2015        self.meta_msg.pack_int( self.slope[ slopestr ] )
2016        self.meta_msg.pack_uint( int( tmax ) )
2017        self.meta_msg.pack_uint( int( dmax ) )
2018
2019        if not group:
2020            self.meta_msg.pack_int( 0 )
2021        else:
2022            self.meta_msg.pack_int( 1 )
2023            self.meta_msg.pack_string( "GROUP" )
2024            self.meta_msg.pack_string( group )
2025
2026        self.data_msg.reset()
2027        self.data_msg.pack_int( 128+5 )
2028
2029        if not spoof:
2030            self.data_msg.pack_string( hostname )
2031        else:
2032            self.data_msg.pack_string( spoof )
2033
2034        self.data_msg.pack_string( name )
2035
2036        if not spoof:
2037            self.data_msg.pack_int( 0 )
2038        else:
2039            self.data_msg.pack_int( 1 )
2040
2041        self.data_msg.pack_string( "%s" )
2042        self.data_msg.pack_string( str( value ) )
2043
2044        return ( self.meta_msg.get_buffer(), self.data_msg.get_buffer() )
2045
[26]2046def printTime( ):
[354]2047
[691]2048    """Print current time/date in human readable format for log/debug"""
[26]2049
[691]2050    return time.strftime("%a, %d %b %Y %H:%M:%S")
[26]2051
2052def debug_msg( level, msg ):
[354]2053
[691]2054    """Print msg if at or above current debug level"""
[26]2055
[691]2056    global DAEMONIZE, DEBUG_LEVEL, SYSLOG_LEVEL
[377]2057
[691]2058    if (not DAEMONIZE and DEBUG_LEVEL >= level):
2059        sys.stderr.write( msg + '\n' )
[26]2060
[691]2061    if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
2062        syslog.syslog( msg )
[373]2063
[307]2064def write_pidfile():
2065
[691]2066    # Write pidfile if PIDFILE is set
2067    #
2068    if PIDFILE:
[307]2069
[691]2070        pid    = os.getpid()
[354]2071
[691]2072        pidfile    = open( PIDFILE, 'w' )
[354]2073
[691]2074        pidfile.write( str( pid ) )
2075        pidfile.close()
[307]2076
[23]2077def main():
[354]2078
[691]2079    """Application start"""
[23]2080
[837]2081    global PBSQuery, PBSError, lsfObject, pyslurm
[854]2082    global SYSLOG_FACILITY, USE_SYSLOG, BATCH_API, DAEMONIZE, BATCH_SERVER
[256]2083
[691]2084    if not processArgs( sys.argv[1:] ):
[354]2085
[691]2086        sys.exit( 1 )
[212]2087
[691]2088    # Load appropriate DataGatherer depending on which BATCH_API is set
2089    # and any required modules for the Gatherer
2090    #
2091    if BATCH_API == 'pbs':
[256]2092
[691]2093        try:
2094            from PBSQuery import PBSQuery, PBSError
[256]2095
[787]2096        except ImportError, details:
[256]2097
[854]2098            print "FATAL ERROR: BATCH_API set to 'pbs' but python module 'pbs_python' is not found or installed"
[787]2099            print details
[691]2100            sys.exit( 1 )
[256]2101
[691]2102        gather = PbsDataGatherer()
[256]2103
[691]2104    elif BATCH_API == 'sge':
[256]2105
[854]2106        if BATCH_SERVER != 'localhost':
2107
2108            # Print and log, but continue execution
2109            err_msg = "WARNING: BATCH_API 'sge' ignores BATCH_SERVER (can only be 'localhost')"
2110            print err_msg
2111            debug_msg( 0, err_msg )
2112
[691]2113        # Tested with SGE 6.0u11.
2114        #
2115        gather = SgeDataGatherer()
[368]2116
[691]2117    elif BATCH_API == 'lsf':
[368]2118
[854]2119        if BATCH_SERVER != 'localhost':
2120
2121            # Print and log, but continue execution
2122            err_msg = "WARNING: BATCH_API 'lsf' ignores BATCH_SERVER (can only be 'localhost')"
2123            print err_msg
2124            debug_msg( 0, err_msg )
2125
[691]2126        try:
2127            from lsfObject import lsfObject
2128        except:
[854]2129            print "FATAL ERROR: BATCH_API set to 'lsf' but python module 'lsfObject' is not found or installed"
2130            sys.exit( 1 )
[256]2131
[691]2132        gather = LsfDataGatherer()
[524]2133
[837]2134    elif BATCH_API == 'slurm':
2135
[854]2136        if BATCH_SERVER != 'localhost':
2137
2138            # Print and log, but continue execution
2139            err_msg = "WARNING: BATCH_API 'slurm' ignores BATCH_SERVER (can only be 'localhost')"
2140            print err_msg
2141            debug_msg( 0, err_msg )
2142
[837]2143        try:
2144            import pyslurm
2145        except:
2146            print "FATAL ERROR: BATCH_API set to 'slurm' but python module is not found or installed"
[854]2147            sys.exit( 1 )
[837]2148
2149        gather = SLURMDataGatherer()
2150
[691]2151    else:
[786]2152        print "FATAL ERROR: unknown BATCH_API '" + BATCH_API + "' is not supported"
[354]2153
[691]2154        sys.exit( 1 )
[256]2155
[691]2156    if( DAEMONIZE and USE_SYSLOG ):
[373]2157
[691]2158        syslog.openlog( 'jobmond', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
[373]2159
[691]2160    if DAEMONIZE:
[354]2161
[691]2162        gather.daemon()
2163    else:
2164        gather.run()
[23]2165
[256]2166# wh00t? someone started me! :)
[65]2167#
[23]2168if __name__ == '__main__':
[691]2169    main()
Note: See TracBrowser for help on using the repository browser.