source: branches/0.4/jobmond/jobmond.py @ 705

Last change on this file since 705 was 705, checked in by ramonb, 11 years ago
  • fix to GangliaConfigParser?.getSectionLastOption
  • more fixes so that GMETRIC and GMOND_CONF is really optional last resort
  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 56.8 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 705 2013-03-21 16:13:30Z ramonb $
[227]23#
[23]24
[694]25# vi :set ts=4
26
[471]27import sys, getopt, ConfigParser, time, os, socket, string, re
[699]28import xdrlib, socket, syslog, xml, xml.sax, shlex
[318]29from xml.sax.handler import feature_namespaces
[623]30from collections import deque
[699]31from glob import glob
[318]32
[691]33VERSION='0.4+SVN'
[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
72        usage()
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        return self.conf_dict[ 'udp_send_channel' ]
356
357    def getSectionLastOption( self, section, option ):
358
359        """
360        Get last option set in a config section that could be set multiple times in multiple (include) files.
361
362        i.e.: getSectionLastOption( 'globals', 'send_metadata_interval' )
363        """
364
365        self.checkConfDict()
366        value = None
367
368        if not self.conf_dict.has_key( section ):
369
370            return None
371
372        # Could be set multiple times in multiple (include) files: get last one set
373        for c in self.conf_dict[ section ]:
374
375                if c.has_key( option ):
376
[705]377                    value = c[ option ][0]
[699]378
[705]379        return value
[699]380
381    def getClusterName( self ):
382
383        return self.getSectionLastOption( 'cluster', 'name' )
384
385    def getVal( self, section, option ):
386
387        return self.getSectionLastOption( section, option )
388
[691]389    def getInt( self, section, valname ):
[520]390
[691]391        value    = self.getVal( section, valname )
[520]392
[691]393        if not value:
[699]394            return None
[520]395
[691]396        return int( value )
[520]397
[691]398    def getStr( self, section, valname ):
[520]399
[691]400        value    = self.getVal( section, valname )
[520]401
[691]402        if not value:
[699]403            return None
[520]404
[691]405        return str( value )
[520]406
407def findGmetric():
408
[691]409    for dir in os.path.expandvars( '$PATH' ).split( ':' ):
[520]410
[691]411        guess    = '%s/%s' %( dir, 'gmetric' )
[520]412
[691]413        if os.path.exists( guess ):
[520]414
[691]415            return guess
[520]416
[691]417    return False
[520]418
[212]419def loadConfig( filename ):
420
[691]421    def getlist( cfg_string ):
[215]422
[691]423        my_list = [ ]
[215]424
[691]425        for item_txt in cfg_string.split( ',' ):
[215]426
[691]427            sep_char = None
[215]428
[691]429            item_txt = item_txt.strip()
[215]430
[691]431            for s_char in [ "'", '"' ]:
[215]432
[691]433                if item_txt.find( s_char ) != -1:
[215]434
[691]435                    if item_txt.count( s_char ) != 2:
[215]436
[691]437                        print 'Missing quote: %s' %item_txt
438                        sys.exit( 1 )
[215]439
[691]440                    else:
[215]441
[691]442                        sep_char = s_char
443                        break
[215]444
[691]445            if sep_char:
[215]446
[691]447                item_txt = item_txt.split( sep_char )[1]
[215]448
[691]449            my_list.append( item_txt )
[215]450
[691]451        return my_list
[215]452
[691]453    cfg        = ConfigParser.ConfigParser()
[212]454
[691]455    cfg.read( filename )
[212]456
[691]457    global DEBUG_LEVEL, DAEMONIZE, BATCH_SERVER, BATCH_POLL_INTERVAL
458    global GMOND_CONF, DETECT_TIME_DIFFS, BATCH_HOST_TRANSLATE
459    global BATCH_API, QUEUE, GMETRIC_TARGET, USE_SYSLOG
460    global SYSLOG_LEVEL, SYSLOG_FACILITY, GMETRIC_BINARY
[701]461    global METRIC_MAX_VAL_LEN
[212]462
[701]463    DEBUG_LEVEL = cfg.getint( 'DEFAULT', 'DEBUG_LEVEL' )
[212]464
[701]465    DAEMONIZE   = cfg.getboolean( 'DEFAULT', 'DAEMONIZE' )
[212]466
[691]467    SYSLOG_LEVEL    = -1
[701]468    SYSLOG_FACILITY = None
[377]469
[691]470    try:
[701]471        USE_SYSLOG  = cfg.getboolean( 'DEFAULT', 'USE_SYSLOG' )
[212]472
[691]473    except ConfigParser.NoOptionError:
[373]474
[701]475        USE_SYSLOG  = True
[373]476
[691]477        debug_msg( 0, 'ERROR: no option USE_SYSLOG found: assuming yes' )
[373]478
[691]479    if USE_SYSLOG:
[373]480
[691]481        try:
[701]482            SYSLOG_LEVEL = cfg.getint( 'DEFAULT', 'SYSLOG_LEVEL' )
[373]483
[691]484        except ConfigParser.NoOptionError:
[373]485
[691]486            debug_msg( 0, 'ERROR: no option SYSLOG_LEVEL found: assuming level 0' )
[701]487            SYSLOG_LEVEL = 0
[373]488
[691]489        try:
[373]490
[691]491            SYSLOG_FACILITY = eval( 'syslog.LOG_' + cfg.get( 'DEFAULT', 'SYSLOG_FACILITY' ) )
[373]492
[691]493        except ConfigParser.NoOptionError:
[373]494
[691]495            SYSLOG_FACILITY = syslog.LOG_DAEMON
[373]496
[691]497            debug_msg( 0, 'ERROR: no option SYSLOG_FACILITY found: assuming facility DAEMON' )
[373]498
[691]499    try:
[373]500
[701]501        BATCH_SERVER = cfg.get( 'DEFAULT', 'BATCH_SERVER' )
[212]502
[691]503    except ConfigParser.NoOptionError:
[265]504
[691]505        # Backwards compatibility for old configs
506        #
[265]507
[701]508        BATCH_SERVER = cfg.get( 'DEFAULT', 'TORQUE_SERVER' )
509        api_guess    = 'pbs'
[691]510   
511    try:
512   
[701]513        BATCH_POLL_INTERVAL = cfg.getint( 'DEFAULT', 'BATCH_POLL_INTERVAL' )
[265]514
[691]515    except ConfigParser.NoOptionError:
[265]516
[691]517        # Backwards compatibility for old configs
518        #
[265]519
[701]520        BATCH_POLL_INTERVAL = cfg.getint( 'DEFAULT', 'TORQUE_POLL_INTERVAL' )
521        api_guess           = 'pbs'
[691]522   
523    try:
[212]524
[701]525        GMOND_CONF          = cfg.get( 'DEFAULT', 'GMOND_CONF' )
[353]526
[691]527    except ConfigParser.NoOptionError:
[353]528
[703]529        # Not specified: assume /etc/ganglia/gmond.conf
[691]530        #
[703]531        GMOND_CONF          = '/etc/ganglia/gmond.conf'
[353]532
[701]533    ganglia_cfg     = GangliaConfigParser( GMOND_CONF )
[449]534
[691]535    # Let's try to find the GMETRIC_TARGET ourselves first from GMOND_CONF
536    #
[701]537    gmetric_dest_ip = ganglia_cfg.getStr( 'udp_send_channel', 'mcast_join' )
[449]538
[691]539    if not gmetric_dest_ip:
[449]540
[691]541        # Maybe unicast target then
542        #
[701]543        gmetric_dest_ip = ganglia_cfg.getStr( 'udp_send_channel', 'host' )
[449]544
[701]545    gmetric_dest_port   = ganglia_cfg.getStr( 'udp_send_channel', 'port' )
[520]546
[701]547    #TODO: use multiple udp send channels (if found)
[691]548    if gmetric_dest_ip and gmetric_dest_port:
[520]549
[701]550        GMETRIC_TARGET  = '%s:%s' %( gmetric_dest_ip, gmetric_dest_port )
[691]551    else:
[520]552
[701]553        debug_msg( 0, "WARNING: Can't parse udp_send_channel from: '%s' - Trying: %s" %( GMOND_CONF, JOBMOND_CONF ) )
[520]554
[691]555        # Couldn't figure it out: let's see if it's in our jobmond.conf
556        #
557        try:
[520]558
[691]559            GMETRIC_TARGET    = cfg.get( 'DEFAULT', 'GMETRIC_TARGET' )
[520]560
[691]561        # Guess not: now just give up
[701]562       
[691]563        except ConfigParser.NoOptionError:
[520]564
[691]565            GMETRIC_TARGET    = None
[520]566
[691]567            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]568
[701]569            gmetric_bin    = findGmetric()
[520]570
[701]571            if gmetric_bin:
[520]572
[701]573                GMETRIC_BINARY     = gmetric_bin
574            else:
575                debug_msg( 0, "WARNING: Can't find gmetric binary anywhere in $PATH" )
[520]576
[701]577                try:
[520]578
[701]579                    GMETRIC_BINARY = cfg.get( 'DEFAULT', 'GMETRIC_BINARY' )
[520]580
[701]581                except ConfigParser.NoOptionError:
[520]582
[701]583                    debug_msg( 0, "FATAL ERROR: GMETRIC_BINARY not set and not in $PATH" )
584                    sys.exit( 1 )
[520]585
[701]586    #TODO: is this really still needed or should be automatic
[691]587    DETECT_TIME_DIFFS    = cfg.getboolean( 'DEFAULT', 'DETECT_TIME_DIFFS' )
[212]588
[701]589    BATCH_HOST_TRANSLATE = getlist( cfg.get( 'DEFAULT', 'BATCH_HOST_TRANSLATE' ) )
[215]590
[691]591    try:
[256]592
[691]593        BATCH_API    = cfg.get( 'DEFAULT', 'BATCH_API' )
[266]594
[691]595    except ConfigParser.NoOptionError, detail:
[266]596
[691]597        if BATCH_SERVER and api_guess:
[354]598
[691]599            BATCH_API    = api_guess
600        else:
601            debug_msg( 0, "FATAL ERROR: BATCH_API not set and can't make guess" )
602            sys.exit( 1 )
[317]603
[691]604    try:
[317]605
[691]606        QUEUE        = getlist( cfg.get( 'DEFAULT', 'QUEUE' ) )
[317]607
[691]608    except ConfigParser.NoOptionError, detail:
[317]609
[691]610        QUEUE        = None
[353]611
[701]612    METRIC_MAX_VAL_LEN = ganglia_cfg.getInt( 'globals', 'max_udp_msg_len' )
613
[691]614    return True
[212]615
[507]616def fqdn_parts (fqdn):
[520]617
[691]618    """Return pair of host and domain for fully-qualified domain name arg."""
[520]619
[691]620    parts = fqdn.split (".")
[520]621
[691]622    return (parts[0], string.join(parts[1:], "."))
[507]623
[61]624class DataProcessor:
[355]625
[691]626    """Class for processing of data"""
[61]627
[691]628    binary = None
[61]629
[691]630    def __init__( self, binary=None ):
[355]631
[691]632        """Remember alternate binary location if supplied"""
[61]633
[691]634        global GMETRIC_BINARY, GMOND_CONF
[449]635
[691]636        if binary:
637            self.binary = binary
[61]638
[705]639        if not self.binary and not GMETRIC_TARGET:
[691]640            self.binary = GMETRIC_BINARY
[449]641
[691]642        # Timeout for XML
643        #
644        # From ganglia's documentation:
645        #
646        # 'A metric will be deleted DMAX seconds after it is received, and
647        # DMAX=0 means eternal life.'
[61]648
[691]649        self.dmax = str( int( int( BATCH_POLL_INTERVAL ) * 2 ) )
[80]650
[705]651        if GMOND_CONF and not GMETRIC_TARGET:
[354]652
[691]653            incompatible = self.checkGmetricVersion()
[61]654
[691]655            if incompatible:
[355]656
[692]657                debug_msg( 0, 'Gmetric version not compatible, please upgrade to at least 3.4.0' )
[691]658                sys.exit( 1 )
[65]659
[691]660    def checkGmetricVersion( self ):
[355]661
[691]662        """
[692]663        Check version of gmetric is at least 3.4.0
[691]664        for the syntax we use
665        """
[65]666
[691]667        global METRIC_MAX_VAL_LEN, GMETRIC_TARGET
[255]668
[691]669        incompatible    = 0
[341]670
[691]671        gfp        = os.popen( self.binary + ' --version' )
[692]672        lines      = gfp.readlines()
[65]673
[691]674        gfp.close()
[355]675
[691]676        for line in lines:
[355]677
[691]678            line = line.split( ' ' )
[65]679
[691]680            if len( line ) == 2 and str( line ).find( 'gmetric' ) != -1:
681           
682                gmetric_version    = line[1].split( '\n' )[0]
[65]683
[691]684                version_major    = int( gmetric_version.split( '.' )[0] )
685                version_minor    = int( gmetric_version.split( '.' )[1] )
686                version_patch    = int( gmetric_version.split( '.' )[2] )
[65]687
[691]688                incompatible    = 0
[65]689
[691]690                if version_major < 3:
[65]691
[691]692                    incompatible = 1
693               
694                elif version_major == 3:
[65]695
[692]696                    if version_minor < 4:
[65]697
[692]698                        incompatible = 1
[65]699
[691]700        return incompatible
[65]701
[691]702    def multicastGmetric( self, metricname, metricval, valtype='string', units='' ):
[355]703
[691]704        """Call gmetric binary and multicast"""
[65]705
[691]706        cmd = self.binary
[65]707
[691]708        if GMETRIC_TARGET:
[61]709
[691]710            GMETRIC_TARGET_HOST    = GMETRIC_TARGET.split( ':' )[0]
711            GMETRIC_TARGET_PORT    = GMETRIC_TARGET.split( ':' )[1]
[353]712
[691]713            metric_debug        = "[gmetric] name: %s - val: %s - dmax: %s" %( str( metricname ), str( metricval ), str( self.dmax ) )
[353]714
[691]715            debug_msg( 10, printTime() + ' ' + metric_debug)
[353]716
[691]717            gm = Gmetric( GMETRIC_TARGET_HOST, GMETRIC_TARGET_PORT )
[353]718
[691]719            gm.send( str( metricname ), str( metricval ), str( self.dmax ), valtype, units )
[353]720
[691]721        else:
722            try:
723                cmd = cmd + ' -c' + GMOND_CONF
[353]724
[691]725            except NameError:
[353]726
[705]727                debug_msg( 10, 'Assuming /etc/ganglia/gmond.conf for gmetric cmd' )
[353]728
[691]729            cmd = cmd + ' -n' + str( metricname )+ ' -v"' + str( metricval )+ '" -t' + str( valtype ) + ' -d' + str( self.dmax )
[353]730
[691]731            if len( units ) > 0:
[409]732
[691]733                cmd = cmd + ' -u"' + units + '"'
[409]734
[691]735            debug_msg( 10, printTime() + ' ' + cmd )
[353]736
[691]737            os.system( cmd )
[353]738
[318]739class DataGatherer:
[23]740
[691]741    """Skeleton class for batch system DataGatherer"""
[256]742
[691]743    def printJobs( self, jobs ):
[355]744
[691]745        """Print a jobinfo overview"""
[318]746
[691]747        for name, attrs in self.jobs.items():
[318]748
[691]749            print 'job %s' %(name)
[318]750
[691]751            for name, val in attrs.items():
[318]752
[691]753                print '\t%s = %s' %( name, val )
[318]754
[691]755    def printJob( self, jobs, job_id ):
[355]756
[691]757        """Print job with job_id from jobs"""
[318]758
[691]759        print 'job %s' %(job_id)
[318]760
[691]761        for name, val in jobs[ job_id ].items():
[318]762
[691]763            print '\t%s = %s' %( name, val )
[318]764
[691]765    def getAttr( self, attrs, name ):
[507]766
[691]767        """Return certain attribute from dictionary, if exists"""
[507]768
[691]769        if attrs.has_key( name ):
[507]770
[691]771            return attrs[ name ]
772        else:
773            return ''
[507]774
[691]775    def jobDataChanged( self, jobs, job_id, attrs ):
[507]776
[691]777        """Check if job with attrs and job_id in jobs has changed"""
[507]778
[691]779        if jobs.has_key( job_id ):
[507]780
[691]781            oldData = jobs[ job_id ]   
782        else:
783            return 1
[507]784
[691]785        for name, val in attrs.items():
[507]786
[691]787            if oldData.has_key( name ):
[507]788
[691]789                if oldData[ name ] != attrs[ name ]:
[507]790
[691]791                    return 1
[507]792
[691]793            else:
794                return 1
[507]795
[691]796        return 0
[507]797
[691]798    def submitJobData( self ):
[507]799
[691]800        """Submit job info list"""
[507]801
[691]802        global BATCH_API
[512]803
[691]804        self.dp.multicastGmetric( 'MONARCH-HEARTBEAT', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
[507]805
[691]806        running_jobs    = 0
807        queued_jobs    = 0
[507]808
[691]809        # Count how many running/queued jobs we found
810        #
811        for jobid, jobattrs in self.jobs.items():
[507]812
[691]813            if jobattrs[ 'status' ] == 'Q':
[507]814
[691]815                queued_jobs += 1
[507]816
[691]817            elif jobattrs[ 'status' ] == 'R':
[507]818
[691]819                running_jobs += 1
[507]820
[691]821        # Report running/queued jobs as seperate metric for a nice RRD graph
822        #
823        self.dp.multicastGmetric( 'MONARCH-RJ', str( running_jobs ), 'uint32', 'jobs' )
824        self.dp.multicastGmetric( 'MONARCH-QJ', str( queued_jobs ), 'uint32', 'jobs' )
[507]825
[691]826        # Report down/offline nodes in batch (PBS only ATM)
827        #
828        if BATCH_API == 'pbs':
[512]829
[691]830            domain        = fqdn_parts( socket.getfqdn() )[1]
[514]831
[691]832            downed_nodes    = list()
833            offline_nodes    = list()
834       
835            l        = ['state']
836       
837            for name, node in self.pq.getnodes().items():
[512]838
[691]839                if ( node[ 'state' ].find( "down" ) != -1 ):
[512]840
[691]841                    downed_nodes.append( name )
[512]842
[691]843                if ( node[ 'state' ].find( "offline" ) != -1 ):
[512]844
[691]845                    offline_nodes.append( name )
[512]846
[691]847            downnodeslist        = do_nodelist( downed_nodes )
848            offlinenodeslist    = do_nodelist( offline_nodes )
[512]849
[691]850            down_str    = 'nodes=%s domain=%s reported=%s' %( string.join( downnodeslist, ';' ), domain, str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
851            offl_str    = 'nodes=%s domain=%s reported=%s' %( string.join( offlinenodeslist, ';' ), domain, str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
852            self.dp.multicastGmetric( 'MONARCH-DOWN'   , down_str )
853            self.dp.multicastGmetric( 'MONARCH-OFFLINE', offl_str )
[514]854
[691]855        # Now let's spread the knowledge
856        #
857        for jobid, jobattrs in self.jobs.items():
[507]858
[691]859            # Make gmetric values for each job: respect max gmetric value length
860            #
861            gmetric_val        = self.compileGmetricVal( jobid, jobattrs )
862            metric_increment    = 0
[507]863
[691]864            # If we have more job info than max gmetric value length allows, split it up
865            # amongst multiple metrics
866            #
867            for val in gmetric_val:
[507]868
[691]869                self.dp.multicastGmetric( 'MONARCH-JOB-' + jobid + '-' + str(metric_increment), val )
[507]870
[691]871                # Increase follow number if this jobinfo is split up amongst more than 1 gmetric
872                #
873                metric_increment    = metric_increment + 1
[507]874
[691]875    def compileGmetricVal( self, jobid, jobattrs ):
[507]876
[691]877        """Create a val string for gmetric of jobinfo"""
[507]878
[691]879        gval_lists    = [ ]
880        val_list    = { }
[507]881
[691]882        for val_name, val_value in jobattrs.items():
[507]883
[691]884            # These are our own metric names, i.e.: status, start_timestamp, etc
885            #
886            val_list_names_len    = len( string.join( val_list.keys() ) ) + len(val_list.keys())
[507]887
[691]888            # These are their corresponding values
889            #
890            val_list_vals_len    = len( string.join( val_list.values() ) ) + len(val_list.values())
[507]891
[691]892            if val_name == 'nodes' and jobattrs['status'] == 'R':
[507]893
[691]894                node_str = None
[507]895
[691]896                for node in val_value:
[507]897
[691]898                    if node_str:
[507]899
[691]900                        node_str = node_str + ';' + node
901                    else:
902                        node_str = node
[507]903
[691]904                    # Make sure if we add this new info, that the total metric's value length does not exceed METRIC_MAX_VAL_LEN
905                    #
906                    if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(node_str) ) > METRIC_MAX_VAL_LEN:
[507]907
[691]908                        # It's too big, we need to make a new gmetric for the additional info
909                        #
910                        val_list[ val_name ]    = node_str
[507]911
[691]912                        gval_lists.append( val_list )
[507]913
[691]914                        val_list        = { }
915                        node_str        = None
[507]916
[691]917                val_list[ val_name ]    = node_str
[507]918
[691]919                gval_lists.append( val_list )
[507]920
[691]921                val_list        = { }
[507]922
[691]923            elif val_value != '':
[507]924
[691]925                # Make sure if we add this new info, that the total metric's value length does not exceed METRIC_MAX_VAL_LEN
926                #
927                if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(str(val_value)) ) > METRIC_MAX_VAL_LEN:
[507]928
[691]929                    # It's too big, we need to make a new gmetric for the additional info
930                    #
931                    gval_lists.append( val_list )
[507]932
[691]933                    val_list        = { }
[507]934
[691]935                val_list[ val_name ]    = val_value
[507]936
[691]937        if len( val_list ) > 0:
[507]938
[691]939            gval_lists.append( val_list )
[507]940
[691]941        str_list    = [ ]
[507]942
[691]943        # Now append the value names and values together, i.e.: stop_timestamp=value, etc
944        #
945        for val_list in gval_lists:
[507]946
[691]947            my_val_str    = None
[507]948
[691]949            for val_name, val_value in val_list.items():
[507]950
[691]951                if type(val_value) == list:
[579]952
[691]953                    val_value    = val_value.join( ',' )
[579]954
[691]955                if my_val_str:
[507]956
[691]957                    try:
958                        # fixme: It's getting
959                        # ('nodes', None) items
960                        my_val_str = my_val_str + ' ' + val_name + '=' + val_value
961                    except:
962                        pass
[623]963
[691]964                else:
965                    my_val_str = val_name + '=' + val_value
[507]966
[691]967            str_list.append( my_val_str )
[507]968
[691]969        return str_list
[507]970
[691]971    def daemon( self ):
[355]972
[691]973        """Run as daemon forever"""
[256]974
[691]975        # Fork the first child
976        #
977        pid = os.fork()
978        if pid > 0:
979            sys.exit(0)  # end parent
[256]980
[691]981        # creates a session and sets the process group ID
982        #
983        os.setsid()
[318]984
[691]985        # Fork the second child
986        #
987        pid = os.fork()
988        if pid > 0:
989            sys.exit(0)  # end parent
[318]990
[691]991        write_pidfile()
[318]992
[691]993        # Go to the root directory and set the umask
994        #
995        os.chdir('/')
996        os.umask(0)
[318]997
[691]998        sys.stdin.close()
999        sys.stdout.close()
1000        sys.stderr.close()
[318]1001
[691]1002        os.open('/dev/null', os.O_RDWR)
1003        os.dup2(0, 1)
1004        os.dup2(0, 2)
[318]1005
[691]1006        self.run()
[318]1007
[691]1008    def run( self ):
[355]1009
[691]1010        """Main thread"""
[256]1011
[691]1012        while ( 1 ):
1013       
1014            self.getJobData()
1015            self.submitJobData()
1016            time.sleep( BATCH_POLL_INTERVAL )   
[256]1017
[623]1018# SGE code by Dave Love <fx@gnu.org>.  Tested with SGE 6.0u8 and 6.0u11.  May
1019# work with SGE 6.1 (else should be easily fixable), but definitely doesn't
1020# with 6.2.  See also the fixmes.
[256]1021
[507]1022class NoJobs (Exception):
[691]1023    """Exception raised by empty job list in qstat output."""
1024    pass
[256]1025
[507]1026class SgeQstatXMLParser(xml.sax.handler.ContentHandler):
[691]1027    """SAX handler for XML output from Sun Grid Engine's `qstat'."""
[318]1028
[691]1029    def __init__(self):
1030        self.value = ""
1031        self.joblist = []
1032        self.job = {}
1033        self.queue = ""
1034        self.in_joblist = False
1035        self.lrequest = False
1036        self.eltq = deque()
1037        xml.sax.handler.ContentHandler.__init__(self)
[318]1038
[691]1039    # The structure of the output is as follows (for SGE 6.0).  It's
1040    # similar for 6.1, but radically different for 6.2, and is
1041    # undocumented generally.  Unfortunately it's voluminous, and probably
1042    # doesn't scale to large clusters/queues.
[318]1043
[691]1044    # <detailed_job_info  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
1045    #   <djob_info>
1046    #     <qmaster_response>  <!-- job -->
1047    #       ...
1048    #       <JB_ja_template> 
1049    #     <ulong_sublist>
1050    #     ...         <!-- start_time, state ... -->
1051    #     </ulong_sublist>
1052    #       </JB_ja_template> 
1053    #       <JB_ja_tasks>
1054    #     <ulong_sublist>
1055    #       ...       <!-- task info
1056    #     </ulong_sublist>
1057    #     ...
1058    #       </JB_ja_tasks>
1059    #       ...
1060    #     </qmaster_response>
1061    #   </djob_info>
1062    #   <messages>
1063    #   ...
[318]1064
[691]1065    # NB.  We might treat each task as a separate job, like
1066    # straight qstat output, but the web interface expects jobs to
1067    # be identified by integers, not, say, <job number>.<task>.
[318]1068
[691]1069    # So, I lied.  If the job list is empty, we get invalid XML
1070    # like this, which we need to defend against:
[318]1071
[691]1072    # <unknown_jobs  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
1073    #   <>
1074    #     <ST_name>*</ST_name>
1075    #   </>
1076    # </unknown_jobs>
[318]1077
[691]1078    def startElement(self, name, attrs):
1079        self.value = ""
1080        if name == "djob_info":    # job list
1081            self.in_joblist = True
1082        # The job container is "qmaster_response" in SGE 6.0
1083        # and 6.1, but "element" in 6.2.  This is only the very
1084        # start of what's necessary for 6.2, though (sigh).
1085        elif (name == "qmaster_response" or name == "element") \
1086                and self.eltq[-1] == "djob_info": # job
1087            self.job = {"job_state": "U", "slots": 0,
1088                    "nodes": [], "queued_timestamp": "",
1089                    "queued_timestamp": "", "queue": "",
1090                    "ppn": "0", "RN_max": 0,
1091                    # fixme in endElement
1092                    "requested_memory": 0, "requested_time": 0
1093                    }
1094            self.joblist.append(self.job)
1095        elif name == "qstat_l_requests": # resource request
1096            self.lrequest = True
1097        elif name == "unknown_jobs":
1098            raise NoJobs
1099        self.eltq.append (name)
[318]1100
[691]1101    def characters(self, ch):
1102        self.value += ch
[318]1103
[691]1104    def endElement(self, name): 
1105        """Snarf job elements contents into job dictionary.
1106           Translate keys if appropriate."""
[318]1107
[691]1108        name_trans = {
1109          "JB_job_number": "number",
1110          "JB_job_name": "name", "JB_owner": "owner",
1111          "queue_name": "queue", "JAT_start_time": "start_timestamp",
1112          "JB_submission_time": "queued_timestamp"
1113          }
1114        value = self.value
1115        self.eltq.pop ()
[318]1116
[691]1117        if name == "djob_info":
1118            self.in_joblist = False
1119            self.job = {}
1120        elif name == "JAT_master_queue":
1121            self.job["queue"] = value.split("@")[0]
1122        elif name == "JG_qhostname":
1123            if not (value in self.job["nodes"]):
1124                self.job["nodes"].append(value)
1125        elif name == "JG_slots": # slots in use
1126            self.job["slots"] += int(value)
1127        elif name == "RN_max": # requested slots (tasks or parallel)
1128            self.job["RN_max"] = max (self.job["RN_max"],
1129                          int(value))
1130        elif name == "JAT_state": # job state (bitwise or)
1131            value = int (value)
1132            # Status values from sge_jobL.h
1133            #define JIDLE           0x00000000
1134            #define JHELD           0x00000010
1135            #define JMIGRATING          0x00000020
1136            #define JQUEUED         0x00000040
1137            #define JRUNNING        0x00000080
1138            #define JSUSPENDED          0x00000100
1139            #define JTRANSFERING        0x00000200
1140            #define JDELETED        0x00000400
1141            #define JWAITING        0x00000800
1142            #define JEXITING        0x00001000
1143            #define JWRITTEN        0x00002000
1144            #define JSUSPENDED_ON_THRESHOLD 0x00010000
1145            #define JFINISHED           0x00010000
1146            if value & 0x80:
1147                self.job["status"] = "R"
1148            elif value & 0x40:
1149                self.job["status"] = "Q"
1150            else:
1151                self.job["status"] = "O" # `other'
1152        elif name == "CE_name" and self.lrequest and self.value in \
1153                ("h_cpu", "s_cpu", "cpu", "h_core", "s_core"):
1154            # We're in a container for an interesting resource
1155            # request; record which type.
1156            self.lrequest = self.value
1157        elif name == "CE_doubleval" and self.lrequest:
1158            # if we're in a container for an interesting
1159            # resource request, use the maxmimum of the hard
1160            # and soft requests to record the requested CPU
1161            # or core.  Fixme:  I'm not sure if this logic is
1162            # right.
1163            if self.lrequest in ("h_core", "s_core"):
1164                self.job["requested_memory"] = \
1165                    max (float (value),
1166                     self.job["requested_memory"])
1167            # Fixme:  Check what cpu means, c.f [hs]_cpu.
1168            elif self.lrequest in ("h_cpu", "s_cpu", "cpu"):
1169                self.job["requested_time"] = \
1170                    max (float (value),
1171                     self.job["requested_time"])
1172        elif name == "qstat_l_requests":
1173            self.lrequest = False
1174        elif self.job and self.in_joblist:
1175            if name in name_trans:
1176                name = name_trans[name]
1177                self.job[name] = value
[318]1178
[507]1179# Abstracted from PBS original.
1180# Fixme:  Is it worth (or appropriate for PBS) sorting the result?
[520]1181#
1182def do_nodelist( nodes ):
1183
[691]1184    """Translate node list as appropriate."""
[520]1185
[691]1186    nodeslist        = [ ]
1187    my_domain        = fqdn_parts( socket.getfqdn() )[1]
[520]1188
[691]1189    for node in nodes:
[520]1190
[691]1191        host        = node.split( '/' )[0] # not relevant for SGE
1192        h, host_domain    = fqdn_parts(host)
[520]1193
[691]1194        if host_domain == my_domain:
[520]1195
[691]1196            host    = h
[520]1197
[691]1198        if nodeslist.count( host ) == 0:
[520]1199
[691]1200            for translate_pattern in BATCH_HOST_TRANSLATE:
[520]1201
[691]1202                if translate_pattern.find( '/' ) != -1:
[520]1203
[691]1204                    translate_orig    = \
1205                        translate_pattern.split( '/' )[1]
1206                    translate_new    = \
1207                        translate_pattern.split( '/' )[2]
1208                    host = re.sub( translate_orig,
1209                               translate_new, host )
1210            if not host in nodeslist:
1211                nodeslist.append( host )
1212    return nodeslist
[318]1213
1214class SgeDataGatherer(DataGatherer):
1215
[691]1216    jobs = {}
[61]1217
[691]1218    def __init__( self ):
1219        self.jobs = {}
1220        self.timeoffset = 0
1221        self.dp = DataProcessor()
[318]1222
[691]1223    def getJobData( self ):
1224        """Gather all data on current jobs in SGE"""
[318]1225
[691]1226        import popen2
[318]1227
[691]1228        self.cur_time = 0
1229        queues = ""
1230        if QUEUE:    # only for specific queues
1231            # Fixme:  assumes queue names don't contain single
1232            # quote or comma.  Don't know what the SGE rules are.
1233            queues = " -q '" + string.join (QUEUE, ",") + "'"
1234        # Note the comment in SgeQstatXMLParser about scaling with
1235        # this method of getting data.  I haven't found better one.
1236        # Output with args `-xml -ext -f -r' is easier to parse
1237        # in some ways, harder in others, but it doesn't provide
1238        # the submission time (at least SGE 6.0).  The pipeline
1239        # into sed corrects bogus XML observed with a configuration
1240        # of SGE 6.0u8, which otherwise causes the parsing to hang.
1241        piping = popen2.Popen3("qstat -u '*' -j '*' -xml | \
[623]1242sed -e 's/reported usage>/reported_usage>/g' -e 's;<\/*JATASK:.*>;;'" \
[691]1243                           + queues, True)
1244        qstatparser = SgeQstatXMLParser()
1245        parse_err = 0
1246        try:
1247            xml.sax.parse(piping.fromchild, qstatparser)
1248        except NoJobs:
1249            pass
1250        except:
1251            parse_err = 1
[704]1252        if piping.wait():
1253            debug_msg(10, "qstat error, skipping until next polling interval: " + piping.childerr.readline())
[691]1254            return None
1255        elif parse_err:
1256            debug_msg(10, "Bad XML output from qstat"())
1257            exit (1)
1258        for f in piping.fromchild, piping.tochild, piping.childerr:
1259            f.close()
1260        self.cur_time = time.time()
1261        jobs_processed = []
1262        for job in qstatparser.joblist:
1263            job_id = job["number"]
1264            if job["status"] in [ 'Q', 'R' ]:
1265                jobs_processed.append(job_id)
1266            if job["status"] == "R":
1267                job["nodes"] = do_nodelist (job["nodes"])
1268                # Fixme: why is job["nodes"] sometimes null?
1269                try:
1270                    # Fixme: Is this sensible?  The
1271                    # PBS-type PPN isn't something you use
1272                    # with SGE.
[704]1273                    job["ppn"] = float(job["slots"]) / len(job["nodes"])
[691]1274                except:
1275                    job["ppn"] = 0
1276                if DETECT_TIME_DIFFS:
1277                    # If a job start is later than our
1278                    # current date, that must mean
1279                    # the SGE server's time is later
1280                    # than our local time.
[704]1281                    start_timestamp = int (job["start_timestamp"])
1282                    if start_timestamp > int(self.cur_time) + int(self.timeoffset):
[318]1283
[704]1284                        self.timeoffset    = start_timestamp - int(self.cur_time)
[691]1285            else:
1286                # fixme: Note sure what this should be:
1287                job["ppn"] = job["RN_max"]
1288                job["nodes"] = "1"
[318]1289
[691]1290            myAttrs = {}
1291            for attr in ["name", "queue", "owner",
1292                     "requested_time", "status",
1293                     "requested_memory", "ppn",
1294                     "start_timestamp", "queued_timestamp"]:
1295                myAttrs[attr] = str(job[attr])
1296            myAttrs["nodes"] = job["nodes"]
[704]1297            myAttrs["reported"] = str(int(self.cur_time) + int(self.timeoffset))
[691]1298            myAttrs["domain"] = fqdn_parts(socket.getfqdn())[1]
1299            myAttrs["poll_interval"] = str(BATCH_POLL_INTERVAL)
[318]1300
[704]1301            if self.jobDataChanged(self.jobs, job_id, myAttrs) and myAttrs["status"] in ["R", "Q"]:
[691]1302                self.jobs[job_id] = myAttrs
1303        for id, attrs in self.jobs.items():
1304            if id not in jobs_processed:
1305                del self.jobs[id]
[318]1306
[524]1307# LSF code by Mahmoud Hanafi <hanafim@users.sourceforge.nt>
1308# Requres LSFObject http://sourceforge.net/projects/lsfobject
1309#
1310class LsfDataGatherer(DataGatherer):
[525]1311
[691]1312    """This is the DataGatherer for LSf"""
[524]1313
[691]1314    global lsfObject
[524]1315
[691]1316    def __init__( self ):
[525]1317
[691]1318        self.jobs = { }
1319        self.timeoffset = 0
1320        self.dp = DataProcessor()
1321        self.initLsfQuery()
[524]1322
[691]1323    def _countDuplicatesInList( self, dupedList ):
[525]1324
[691]1325        countDupes    = { }
[525]1326
[691]1327        for item in dupedList:
[525]1328
[691]1329            if not countDupes.has_key( item ):
[525]1330
[691]1331                countDupes[ item ]    = 1
1332            else:
1333                countDupes[ item ]    = countDupes[ item ] + 1
[525]1334
[691]1335        dupeCountList    = [ ]
[525]1336
[691]1337        for item, count in countDupes.items():
[525]1338
[691]1339            dupeCountList.append( ( item, count ) )
[525]1340
[691]1341        return dupeCountList
[524]1342#
1343#lst = ['I1','I2','I1','I3','I4','I4','I7','I7','I7','I7','I7']
1344#print _countDuplicatesInList(lst)
1345#[('I1', 2), ('I3', 1), ('I2', 1), ('I4', 2), ('I7', 5)]
1346########################
1347
[691]1348    def initLsfQuery( self ):
1349        self.pq = None
1350        self.pq = lsfObject.jobInfoEntObject()
[524]1351
[691]1352    def getJobData( self, known_jobs="" ):
1353        """Gather all data on current jobs in LSF"""
1354        if len( known_jobs ) > 0:
1355            jobs = known_jobs
1356        else:
1357            jobs = { }
1358        joblist = {}
1359        joblist = self.pq.getJobInfo()
1360        nodelist = ''
[524]1361
[691]1362        self.cur_time = time.time()
[524]1363
[691]1364        jobs_processed = [ ]
[524]1365
[691]1366        for name, attrs in joblist.items():
1367            job_id = str(name)
1368            jobs_processed.append( job_id )
1369            name = self.getAttr( attrs, 'jobName' )
1370            queue = self.getAttr( self.getAttr( attrs, 'submit') , 'queue' )
1371            owner = self.getAttr( attrs, 'user' )
[524]1372
1373### THIS IS THE rLimit List index values
[691]1374#define LSF_RLIMIT_CPU      0        /* cpu time in milliseconds */
1375#define LSF_RLIMIT_FSIZE    1        /* maximum file size */
1376#define LSF_RLIMIT_DATA     2        /* data size */
1377#define LSF_RLIMIT_STACK    3        /* stack size */
1378#define LSF_RLIMIT_CORE     4        /* core file size */
1379#define LSF_RLIMIT_RSS      5        /* resident set size */
1380#define LSF_RLIMIT_NOFILE   6        /* open files */
1381#define LSF_RLIMIT_OPEN_MAX 7        /* (from HP-UX) */
1382#define LSF_RLIMIT_VMEM     8        /* maximum swap mem */
[524]1383#define LSF_RLIMIT_SWAP     8
[691]1384#define LSF_RLIMIT_RUN      9        /* max wall-clock time limit */
1385#define LSF_RLIMIT_PROCESS  10       /* process number limit */
1386#define LSF_RLIMIT_THREAD   11       /* thread number limit (introduced in LSF6.0) */
1387#define LSF_RLIM_NLIMITS    12       /* number of resource limits */
[524]1388
[691]1389            requested_time = self.getAttr( self.getAttr( attrs, 'submit') , 'rLimits' )[9]
1390            if requested_time == -1: 
1391                requested_time = ""
1392            requested_memory = self.getAttr( self.getAttr( attrs, 'submit') , 'rLimits' )[8]
1393            if requested_memory == -1: 
1394                requested_memory = ""
[524]1395# This tries to get proc per node. We don't support this right now
[691]1396            ppn = 0 #self.getAttr( self.getAttr( attrs, 'SubmitList') , 'numProessors' )
1397            requested_cpus = self.getAttr( self.getAttr( attrs, 'submit') , 'numProcessors' )
1398            if requested_cpus == None or requested_cpus == "":
1399                requested_cpus = 1
[524]1400
[691]1401            if QUEUE:
1402                for q in QUEUE:
1403                    if q == queue:
1404                        display_queue = 1
1405                        break
1406                    else:
1407                        display_queue = 0
1408                        continue
1409            if display_queue == 0:
1410                continue
[524]1411
[691]1412            runState = self.getAttr( attrs, 'status' )
1413            if runState == 4:
1414                status = 'R'
1415            else:
1416                status = 'Q'
1417            queued_timestamp = self.getAttr( attrs, 'submitTime' )
[524]1418
[691]1419            if status == 'R':
1420                start_timestamp = self.getAttr( attrs, 'startTime' )
1421                nodesCpu =  dict(self._countDuplicatesInList(self.getAttr( attrs, 'exHosts' )))
1422                nodelist = nodesCpu.keys()
[524]1423
[691]1424                if DETECT_TIME_DIFFS:
[524]1425
[691]1426                    # If a job start if later than our current date,
1427                    # that must mean the Torque server's time is later
1428                    # than our local time.
[524]1429
[691]1430                    if int(start_timestamp) > int( int(self.cur_time) + int(self.timeoffset) ):
[524]1431
[691]1432                        self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
[524]1433
[691]1434            elif status == 'Q':
1435                start_timestamp = ''
1436                count_mynodes = 0
1437                numeric_node = 1
1438                nodelist = ''
[524]1439
[691]1440            myAttrs = { }
1441            if name == "":
1442                myAttrs['name'] = "none"
1443            else:
1444                myAttrs['name'] = name
[524]1445
[691]1446            myAttrs[ 'owner' ]        = owner
1447            myAttrs[ 'requested_time' ]    = str(requested_time)
1448            myAttrs[ 'requested_memory' ]    = str(requested_memory)
1449            myAttrs[ 'requested_cpus' ]    = str(requested_cpus)
1450            myAttrs[ 'ppn' ]        = str( ppn )
1451            myAttrs[ 'status' ]        = status
1452            myAttrs[ 'start_timestamp' ]    = str(start_timestamp)
1453            myAttrs[ 'queue' ]        = str(queue)
1454            myAttrs[ 'queued_timestamp' ]    = str(queued_timestamp)
1455            myAttrs[ 'reported' ]        = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1456            myAttrs[ 'nodes' ]        = do_nodelist( nodelist )
1457            myAttrs[ 'domain' ]        = fqdn_parts( socket.getfqdn() )[1]
1458            myAttrs[ 'poll_interval' ]    = str(BATCH_POLL_INTERVAL)
[524]1459
[691]1460            if self.jobDataChanged( jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
1461                jobs[ job_id ] = myAttrs
[524]1462
[691]1463                debug_msg( 10, printTime() + ' job %s state changed' %(job_id) )
[524]1464
[691]1465        for id, attrs in jobs.items():
1466            if id not in jobs_processed:
1467                # This one isn't there anymore
1468                #
1469                del jobs[ id ]
1470        self.jobs=jobs
[524]1471
1472
[355]1473class PbsDataGatherer( DataGatherer ):
[318]1474
[691]1475    """This is the DataGatherer for PBS and Torque"""
[318]1476
[691]1477    global PBSQuery, PBSError
[256]1478
[691]1479    def __init__( self ):
[354]1480
[691]1481        """Setup appropriate variables"""
[23]1482
[691]1483        self.jobs    = { }
1484        self.timeoffset    = 0
1485        self.dp        = DataProcessor()
[354]1486
[691]1487        self.initPbsQuery()
[23]1488
[691]1489    def initPbsQuery( self ):
[91]1490
[691]1491        self.pq        = None
[354]1492
[691]1493        if( BATCH_SERVER ):
[354]1494
[691]1495            self.pq        = PBSQuery( BATCH_SERVER )
1496        else:
1497            self.pq        = PBSQuery()
[91]1498
[691]1499        try:
1500            self.pq.old_data_structure()
[656]1501
[691]1502        except AttributeError:
[656]1503
[691]1504            # pbs_query is older
1505            #
1506            pass
[656]1507
[691]1508    def getJobData( self ):
[354]1509
[691]1510        """Gather all data on current jobs in Torque"""
[26]1511
[691]1512        joblist        = {}
1513        self.cur_time    = 0
[349]1514
[691]1515        try:
1516            joblist        = self.pq.getjobs()
1517            self.cur_time    = time.time()
[354]1518
[691]1519        except PBSError, detail:
[354]1520
[691]1521            debug_msg( 10, "Caught PBS unavailable, skipping until next polling interval: " + str( detail ) )
1522            return None
[354]1523
[691]1524        jobs_processed    = [ ]
[26]1525
[691]1526        for name, attrs in joblist.items():
1527            display_queue        = 1
1528            job_id            = name.split( '.' )[0]
[26]1529
[691]1530            name            = self.getAttr( attrs, 'Job_Name' )
1531            queue            = self.getAttr( attrs, 'queue' )
[317]1532
[691]1533            if QUEUE:
1534                for q in QUEUE:
1535                    if q == queue:
1536                        display_queue = 1
1537                        break
1538                    else:
1539                        display_queue = 0
1540                        continue
1541            if display_queue == 0:
1542                continue
[317]1543
1544
[691]1545            owner            = self.getAttr( attrs, 'Job_Owner' ).split( '@' )[0]
1546            requested_time        = self.getAttr( attrs, 'Resource_List.walltime' )
1547            requested_memory    = self.getAttr( attrs, 'Resource_List.mem' )
[95]1548
[691]1549            mynoderequest        = self.getAttr( attrs, 'Resource_List.nodes' )
[95]1550
[691]1551            ppn            = ''
[281]1552
[691]1553            if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
[95]1554
[691]1555                mynoderequest_fields    = mynoderequest.split( ':' )
[281]1556
[691]1557                for mynoderequest_field in mynoderequest_fields:
[281]1558
[691]1559                    if mynoderequest_field.find( 'ppn' ) != -1:
[281]1560
[691]1561                        ppn    = mynoderequest_field.split( 'ppn=' )[1]
[281]1562
[691]1563            status            = self.getAttr( attrs, 'job_state' )
[25]1564
[691]1565            if status in [ 'Q', 'R' ]:
[450]1566
[691]1567                jobs_processed.append( job_id )
[450]1568
[691]1569            queued_timestamp    = self.getAttr( attrs, 'ctime' )
[243]1570
[691]1571            if status == 'R':
[133]1572
[691]1573                start_timestamp        = self.getAttr( attrs, 'mtime' )
1574                nodes            = self.getAttr( attrs, 'exec_host' ).split( '+' )
[133]1575
[691]1576                nodeslist        = do_nodelist( nodes )
[354]1577
[691]1578                if DETECT_TIME_DIFFS:
[185]1579
[691]1580                    # If a job start if later than our current date,
1581                    # that must mean the Torque server's time is later
1582                    # than our local time.
1583               
1584                    if int( start_timestamp ) > int( int( self.cur_time ) + int( self.timeoffset ) ):
[185]1585
[691]1586                        self.timeoffset    = int( int(start_timestamp) - int(self.cur_time) )
[185]1587
[691]1588            elif status == 'Q':
[95]1589
[691]1590                # 'mynodequest' can be a string in the following syntax according to the
1591                # Torque Administator's manual:
1592                #
1593                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1594                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1595                # etc
1596                #
[451]1597
[691]1598                #
1599                # For now we only count the amount of nodes request and ignore properties
1600                #
[451]1601
[691]1602                start_timestamp        = ''
1603                count_mynodes        = 0
[354]1604
[691]1605                for node in mynoderequest.split( '+' ):
[67]1606
[691]1607                    # Just grab the {node_count|hostname} part and ignore properties
1608                    #
1609                    nodepart    = node.split( ':' )[0]
[67]1610
[691]1611                    # Let's assume a node_count value
1612                    #
1613                    numeric_node    = 1
[451]1614
[691]1615                    # Chop the value up into characters
1616                    #
1617                    for letter in nodepart:
[67]1618
[691]1619                        # If this char is not a digit (0-9), this must be a hostname
1620                        #
1621                        if letter not in string.digits:
[133]1622
[691]1623                            numeric_node    = 0
[133]1624
[691]1625                    # If this is a hostname, just count this as one (1) node
1626                    #
1627                    if not numeric_node:
[354]1628
[691]1629                        count_mynodes    = count_mynodes + 1
1630                    else:
[451]1631
[691]1632                        # If this a number, it must be the node_count
1633                        # and increase our count with it's value
1634                        #
1635                        try:
1636                            count_mynodes    = count_mynodes + int( nodepart )
[354]1637
[691]1638                        except ValueError, detail:
[354]1639
[691]1640                            # When we arrive here I must be bugged or very confused
1641                            # THIS SHOULD NOT HAPPEN!
1642                            #
1643                            debug_msg( 10, str( detail ) )
1644                            debug_msg( 10, "Encountered weird node in Resources_List?!" )
1645                            debug_msg( 10, 'nodepart = ' + str( nodepart ) )
1646                            debug_msg( 10, 'job = ' + str( name ) )
1647                            debug_msg( 10, 'attrs = ' + str( attrs ) )
1648                       
1649                nodeslist    = str( count_mynodes )
1650            else:
1651                start_timestamp    = ''
1652                nodeslist    = ''
[133]1653
[691]1654            myAttrs                = { }
[26]1655
[691]1656            myAttrs[ 'name' ]        = str( name )
1657            myAttrs[ 'queue' ]        = str( queue )
1658            myAttrs[ 'owner' ]        = str( owner )
1659            myAttrs[ 'requested_time' ]    = str( requested_time )
1660            myAttrs[ 'requested_memory' ]    = str( requested_memory )
1661            myAttrs[ 'ppn' ]        = str( ppn )
1662            myAttrs[ 'status' ]        = str( status )
1663            myAttrs[ 'start_timestamp' ]    = str( start_timestamp )
1664            myAttrs[ 'queued_timestamp' ]    = str( queued_timestamp )
1665            myAttrs[ 'reported' ]        = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1666            myAttrs[ 'nodes' ]        = nodeslist
1667            myAttrs[ 'domain' ]        = fqdn_parts( socket.getfqdn() )[1]
1668            myAttrs[ 'poll_interval' ]    = str( BATCH_POLL_INTERVAL )
[354]1669
[691]1670            if self.jobDataChanged( self.jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
[61]1671
[691]1672                self.jobs[ job_id ]    = myAttrs
[26]1673
[691]1674        for id, attrs in self.jobs.items():
[76]1675
[691]1676            if id not in jobs_processed:
[76]1677
[691]1678                # This one isn't there anymore; toedeledoki!
1679                #
1680                del self.jobs[ id ]
[76]1681
[362]1682GMETRIC_DEFAULT_TYPE    = 'string'
1683GMETRIC_DEFAULT_HOST    = '127.0.0.1'
1684GMETRIC_DEFAULT_PORT    = '8649'
[700]1685GMETRIC_DEFAULT_UNITS   = ''
[362]1686
1687class Gmetric:
1688
[691]1689    global GMETRIC_DEFAULT_HOST, GMETRIC_DEFAULT_PORT
[362]1690
[700]1691    slope           = { 'zero' : 0, 'positive' : 1, 'negative' : 2, 'both' : 3, 'unspecified' : 4 }
1692    type            = ( '', 'string', 'uint16', 'int16', 'uint32', 'int32', 'float', 'double', 'timestamp' )
1693    protocol        = ( 'udp', 'multicast' )
[362]1694
[691]1695    def __init__( self, host=GMETRIC_DEFAULT_HOST, port=GMETRIC_DEFAULT_PORT ):
[700]1696               
[691]1697        global GMETRIC_DEFAULT_TYPE
[362]1698
[691]1699        self.prot       = self.checkHostProtocol( host )
[700]1700        self.data_msg   = xdrlib.Packer()
1701        self.meta_msg   = xdrlib.Packer()
[691]1702        self.socket     = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
[362]1703
[691]1704        if self.prot not in self.protocol:
[362]1705
[691]1706            raise ValueError( "Protocol must be one of: " + str( self.protocol ) )
[362]1707
[691]1708        if self.prot == 'multicast':
[362]1709
[691]1710            # Set multicast options
1711            #
1712            self.socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20 )
[362]1713
[691]1714        self.hostport   = ( host, int( port ) )
1715        self.slopestr   = 'both'
1716        self.tmax       = 60
[362]1717
[691]1718    def checkHostProtocol( self, ip ):
[362]1719
[691]1720        """Detect if a ip adress is a multicast address"""
[471]1721
[691]1722        MULTICAST_ADDRESS_MIN   = ( "224", "0", "0", "0" )
1723        MULTICAST_ADDRESS_MAX   = ( "239", "255", "255", "255" )
[362]1724
[700]1725        ip_fields               = ip.split( '.' )
[362]1726
[691]1727        if ip_fields >= MULTICAST_ADDRESS_MIN and ip_fields <= MULTICAST_ADDRESS_MAX:
[362]1728
[691]1729            return 'multicast'
1730        else:
1731            return 'udp'
[362]1732
[691]1733    def send( self, name, value, dmax, typestr = '', units = '' ):
[362]1734
[691]1735        if len( units ) == 0:
[700]1736            units       = GMETRIC_DEFAULT_UNITS
[471]1737
[691]1738        if len( typestr ) == 0:
[700]1739            typestr     = GMETRIC_DEFAULT_TYPE
[362]1740
[700]1741        (meta_msg, data_msg) = self.makexdr( name, value, typestr, units, self.slopestr, self.tmax, dmax )
[409]1742
[700]1743        meta_rt = self.socket.sendto( meta_msg, self.hostport )
1744        data_rt = self.socket.sendto( data_msg, self.hostport )
[362]1745
[700]1746        return ( meta_rt, data_rt )
[362]1747
[700]1748    def makexdr( self, name, value, typestr, unitstr, slopestr, tmax, dmax, group=None, spoof=None ):
1749
1750        hostname = "unset"
1751
[691]1752        if slopestr not in self.slope:
[362]1753
[691]1754            raise ValueError( "Slope must be one of: " + str( self.slope.keys() ) )
[362]1755
[691]1756        if typestr not in self.type:
[362]1757
[691]1758            raise ValueError( "Type must be one of: " + str( self.type ) )
[362]1759
[691]1760        if len( name ) == 0:
[362]1761
[691]1762            raise ValueError( "Name must be non-empty" )
[362]1763
[700]1764        self.meta_msg.reset()
1765        self.meta_msg.pack_int( 128 )
[362]1766
[700]1767        if not spoof:
1768            self.meta_msg.pack_string( hostname )
1769        else:
1770            self.meta_msg.pack_string( spoof )
[362]1771
[700]1772        self.meta_msg.pack_string( name )
1773
1774        if not spoof:
1775            self.meta_msg.pack_int( 0 )
1776        else:
1777            self.meta_msg.pack_int( 1 )
1778           
1779        self.meta_msg.pack_string( typestr )
1780        self.meta_msg.pack_string( name )
1781        self.meta_msg.pack_string( unitstr )
1782        self.meta_msg.pack_int( self.slope[ slopestr ] )
1783        self.meta_msg.pack_uint( int( tmax ) )
1784        self.meta_msg.pack_uint( int( dmax ) )
1785
1786        if not group:
1787            self.meta_msg.pack_int( 0 )
1788        else:
1789            self.meta_msg.pack_int( 1 )
1790            self.meta_msg.pack_string( "GROUP" )
1791            self.meta_msg.pack_string( group )
1792
1793        self.data_msg.reset()
1794        self.data_msg.pack_int( 128+5 )
1795
1796        if not spoof:
1797            self.data_msg.pack_string( hostname )
1798        else:
1799            self.data_msg.pack_string( spoof )
1800
1801        self.data_msg.pack_string( name )
1802
1803        if not spoof:
1804            self.data_msg.pack_int( 0 )
1805        else:
1806            self.data_msg.pack_int( 1 )
1807
1808        self.data_msg.pack_string( "%s" )
1809        self.data_msg.pack_string( str( value ) )
1810
1811        return ( self.meta_msg.get_buffer(), self.data_msg.get_buffer() )
1812
[26]1813def printTime( ):
[354]1814
[691]1815    """Print current time/date in human readable format for log/debug"""
[26]1816
[691]1817    return time.strftime("%a, %d %b %Y %H:%M:%S")
[26]1818
1819def debug_msg( level, msg ):
[354]1820
[691]1821    """Print msg if at or above current debug level"""
[26]1822
[691]1823    global DAEMONIZE, DEBUG_LEVEL, SYSLOG_LEVEL
[377]1824
[691]1825    if (not DAEMONIZE and DEBUG_LEVEL >= level):
1826        sys.stderr.write( msg + '\n' )
[26]1827
[691]1828    if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
1829        syslog.syslog( msg )
[373]1830
[307]1831def write_pidfile():
1832
[691]1833    # Write pidfile if PIDFILE is set
1834    #
1835    if PIDFILE:
[307]1836
[691]1837        pid    = os.getpid()
[354]1838
[691]1839        pidfile    = open( PIDFILE, 'w' )
[354]1840
[691]1841        pidfile.write( str( pid ) )
1842        pidfile.close()
[307]1843
[23]1844def main():
[354]1845
[691]1846    """Application start"""
[23]1847
[691]1848    global PBSQuery, PBSError, lsfObject
1849    global SYSLOG_FACILITY, USE_SYSLOG, BATCH_API, DAEMONIZE
[256]1850
[691]1851    if not processArgs( sys.argv[1:] ):
[354]1852
[691]1853        sys.exit( 1 )
[212]1854
[691]1855    # Load appropriate DataGatherer depending on which BATCH_API is set
1856    # and any required modules for the Gatherer
1857    #
1858    if BATCH_API == 'pbs':
[256]1859
[691]1860        try:
1861            from PBSQuery import PBSQuery, PBSError
[256]1862
[691]1863        except ImportError:
[256]1864
[691]1865            debug_msg( 0, "FATAL ERROR: BATCH_API set to 'pbs' but python module 'pbs_python' is not installed" )
1866            sys.exit( 1 )
[256]1867
[691]1868        gather = PbsDataGatherer()
[256]1869
[691]1870    elif BATCH_API == 'sge':
[256]1871
[691]1872        # Tested with SGE 6.0u11.
1873        #
1874        gather = SgeDataGatherer()
[368]1875
[691]1876    elif BATCH_API == 'lsf':
[368]1877
[691]1878        try:
1879            from lsfObject import lsfObject
1880        except:
1881            debug_msg(0, "fatal error: BATCH_API set to 'lsf' but python module is not found or installed")
1882            sys.exit( 1)
[256]1883
[691]1884        gather = LsfDataGatherer()
[524]1885
[691]1886    else:
1887        debug_msg( 0, "FATAL ERROR: unknown BATCH_API '" + BATCH_API + "' is not supported" )
[354]1888
[691]1889        sys.exit( 1 )
[256]1890
[691]1891    if( DAEMONIZE and USE_SYSLOG ):
[373]1892
[691]1893        syslog.openlog( 'jobmond', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
[373]1894
[691]1895    if DAEMONIZE:
[354]1896
[691]1897        gather.daemon()
1898    else:
1899        gather.run()
[23]1900
[256]1901# wh00t? someone started me! :)
[65]1902#
[23]1903if __name__ == '__main__':
[691]1904    main()
Note: See TracBrowser for help on using the repository browser.