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

Last change on this file since 702 was 702, checked in by ramonb, 11 years ago
  • METRIC_MAX_VAL_LEN is now determined from gmond.conf
  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 57.0 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 702 2013-03-21 15:55:35Z 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
[701]60    global PIDFILE JOBMOND_CONF
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
377                    cluster_name = c[ option ][0]
378
379        return cluster_name
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
[691]529        # Not specified: assume /etc/gmond.conf
530        #
[701]531        GMOND_CONF          = '/etc/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
[691]639        if not self.binary:
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
[691]651        if GMOND_CONF:
[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
[691]727                debug_msg( 10, 'Assuming /etc/gmond.conf for gmetric cmd (omitting)' )
[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
1252               if piping.wait():
1253            debug_msg(10,
1254                  "qstat error, skipping until next polling interval: "
1255                  + piping.childerr.readline())
1256            return None
1257        elif parse_err:
1258            debug_msg(10, "Bad XML output from qstat"())
1259            exit (1)
1260        for f in piping.fromchild, piping.tochild, piping.childerr:
1261            f.close()
1262        self.cur_time = time.time()
1263        jobs_processed = []
1264        for job in qstatparser.joblist:
1265            job_id = job["number"]
1266            if job["status"] in [ 'Q', 'R' ]:
1267                jobs_processed.append(job_id)
1268            if job["status"] == "R":
1269                job["nodes"] = do_nodelist (job["nodes"])
1270                # Fixme: why is job["nodes"] sometimes null?
1271                try:
1272                    # Fixme: Is this sensible?  The
1273                    # PBS-type PPN isn't something you use
1274                    # with SGE.
1275                    job["ppn"] = float(job["slots"]) / \
1276                        len(job["nodes"])
1277                except:
1278                    job["ppn"] = 0
1279                if DETECT_TIME_DIFFS:
1280                    # If a job start is later than our
1281                    # current date, that must mean
1282                    # the SGE server's time is later
1283                    # than our local time.
1284                    start_timestamp = \
1285                        int (job["start_timestamp"])
1286                    if start_timestamp > \
1287                            int(self.cur_time) + \
1288                            int(self.timeoffset):
[318]1289
[691]1290                        self.timeoffset    = \
1291                            start_timestamp - \
1292                            int(self.cur_time)
1293            else:
1294                # fixme: Note sure what this should be:
1295                job["ppn"] = job["RN_max"]
1296                job["nodes"] = "1"
[318]1297
[691]1298            myAttrs = {}
1299            for attr in ["name", "queue", "owner",
1300                     "requested_time", "status",
1301                     "requested_memory", "ppn",
1302                     "start_timestamp", "queued_timestamp"]:
1303                myAttrs[attr] = str(job[attr])
1304            myAttrs["nodes"] = job["nodes"]
1305            myAttrs["reported"] = str(int(self.cur_time) + \
1306                          int(self.timeoffset))
1307            myAttrs["domain"] = fqdn_parts(socket.getfqdn())[1]
1308            myAttrs["poll_interval"] = str(BATCH_POLL_INTERVAL)
[318]1309
[691]1310            if self.jobDataChanged(self.jobs, job_id, myAttrs) \
1311                    and myAttrs["status"] in ["R", "Q"]:
1312                self.jobs[job_id] = myAttrs
1313        for id, attrs in self.jobs.items():
1314            if id not in jobs_processed:
1315                del self.jobs[id]
[318]1316
[524]1317# LSF code by Mahmoud Hanafi <hanafim@users.sourceforge.nt>
1318# Requres LSFObject http://sourceforge.net/projects/lsfobject
1319#
1320class LsfDataGatherer(DataGatherer):
[525]1321
[691]1322    """This is the DataGatherer for LSf"""
[524]1323
[691]1324    global lsfObject
[524]1325
[691]1326    def __init__( self ):
[525]1327
[691]1328        self.jobs = { }
1329        self.timeoffset = 0
1330        self.dp = DataProcessor()
1331        self.initLsfQuery()
[524]1332
[691]1333    def _countDuplicatesInList( self, dupedList ):
[525]1334
[691]1335        countDupes    = { }
[525]1336
[691]1337        for item in dupedList:
[525]1338
[691]1339            if not countDupes.has_key( item ):
[525]1340
[691]1341                countDupes[ item ]    = 1
1342            else:
1343                countDupes[ item ]    = countDupes[ item ] + 1
[525]1344
[691]1345        dupeCountList    = [ ]
[525]1346
[691]1347        for item, count in countDupes.items():
[525]1348
[691]1349            dupeCountList.append( ( item, count ) )
[525]1350
[691]1351        return dupeCountList
[524]1352#
1353#lst = ['I1','I2','I1','I3','I4','I4','I7','I7','I7','I7','I7']
1354#print _countDuplicatesInList(lst)
1355#[('I1', 2), ('I3', 1), ('I2', 1), ('I4', 2), ('I7', 5)]
1356########################
1357
[691]1358    def initLsfQuery( self ):
1359        self.pq = None
1360        self.pq = lsfObject.jobInfoEntObject()
[524]1361
[691]1362    def getJobData( self, known_jobs="" ):
1363        """Gather all data on current jobs in LSF"""
1364        if len( known_jobs ) > 0:
1365            jobs = known_jobs
1366        else:
1367            jobs = { }
1368        joblist = {}
1369        joblist = self.pq.getJobInfo()
1370        nodelist = ''
[524]1371
[691]1372        self.cur_time = time.time()
[524]1373
[691]1374        jobs_processed = [ ]
[524]1375
[691]1376        for name, attrs in joblist.items():
1377            job_id = str(name)
1378            jobs_processed.append( job_id )
1379            name = self.getAttr( attrs, 'jobName' )
1380            queue = self.getAttr( self.getAttr( attrs, 'submit') , 'queue' )
1381            owner = self.getAttr( attrs, 'user' )
[524]1382
1383### THIS IS THE rLimit List index values
[691]1384#define LSF_RLIMIT_CPU      0        /* cpu time in milliseconds */
1385#define LSF_RLIMIT_FSIZE    1        /* maximum file size */
1386#define LSF_RLIMIT_DATA     2        /* data size */
1387#define LSF_RLIMIT_STACK    3        /* stack size */
1388#define LSF_RLIMIT_CORE     4        /* core file size */
1389#define LSF_RLIMIT_RSS      5        /* resident set size */
1390#define LSF_RLIMIT_NOFILE   6        /* open files */
1391#define LSF_RLIMIT_OPEN_MAX 7        /* (from HP-UX) */
1392#define LSF_RLIMIT_VMEM     8        /* maximum swap mem */
[524]1393#define LSF_RLIMIT_SWAP     8
[691]1394#define LSF_RLIMIT_RUN      9        /* max wall-clock time limit */
1395#define LSF_RLIMIT_PROCESS  10       /* process number limit */
1396#define LSF_RLIMIT_THREAD   11       /* thread number limit (introduced in LSF6.0) */
1397#define LSF_RLIM_NLIMITS    12       /* number of resource limits */
[524]1398
[691]1399            requested_time = self.getAttr( self.getAttr( attrs, 'submit') , 'rLimits' )[9]
1400            if requested_time == -1: 
1401                requested_time = ""
1402            requested_memory = self.getAttr( self.getAttr( attrs, 'submit') , 'rLimits' )[8]
1403            if requested_memory == -1: 
1404                requested_memory = ""
[524]1405# This tries to get proc per node. We don't support this right now
[691]1406            ppn = 0 #self.getAttr( self.getAttr( attrs, 'SubmitList') , 'numProessors' )
1407            requested_cpus = self.getAttr( self.getAttr( attrs, 'submit') , 'numProcessors' )
1408            if requested_cpus == None or requested_cpus == "":
1409                requested_cpus = 1
[524]1410
[691]1411            if QUEUE:
1412                for q in QUEUE:
1413                    if q == queue:
1414                        display_queue = 1
1415                        break
1416                    else:
1417                        display_queue = 0
1418                        continue
1419            if display_queue == 0:
1420                continue
[524]1421
[691]1422            runState = self.getAttr( attrs, 'status' )
1423            if runState == 4:
1424                status = 'R'
1425            else:
1426                status = 'Q'
1427            queued_timestamp = self.getAttr( attrs, 'submitTime' )
[524]1428
[691]1429            if status == 'R':
1430                start_timestamp = self.getAttr( attrs, 'startTime' )
1431                nodesCpu =  dict(self._countDuplicatesInList(self.getAttr( attrs, 'exHosts' )))
1432                nodelist = nodesCpu.keys()
[524]1433
[691]1434                if DETECT_TIME_DIFFS:
[524]1435
[691]1436                    # If a job start if later than our current date,
1437                    # that must mean the Torque server's time is later
1438                    # than our local time.
[524]1439
[691]1440                    if int(start_timestamp) > int( int(self.cur_time) + int(self.timeoffset) ):
[524]1441
[691]1442                        self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
[524]1443
[691]1444            elif status == 'Q':
1445                start_timestamp = ''
1446                count_mynodes = 0
1447                numeric_node = 1
1448                nodelist = ''
[524]1449
[691]1450            myAttrs = { }
1451            if name == "":
1452                myAttrs['name'] = "none"
1453            else:
1454                myAttrs['name'] = name
[524]1455
[691]1456            myAttrs[ 'owner' ]        = owner
1457            myAttrs[ 'requested_time' ]    = str(requested_time)
1458            myAttrs[ 'requested_memory' ]    = str(requested_memory)
1459            myAttrs[ 'requested_cpus' ]    = str(requested_cpus)
1460            myAttrs[ 'ppn' ]        = str( ppn )
1461            myAttrs[ 'status' ]        = status
1462            myAttrs[ 'start_timestamp' ]    = str(start_timestamp)
1463            myAttrs[ 'queue' ]        = str(queue)
1464            myAttrs[ 'queued_timestamp' ]    = str(queued_timestamp)
1465            myAttrs[ 'reported' ]        = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1466            myAttrs[ 'nodes' ]        = do_nodelist( nodelist )
1467            myAttrs[ 'domain' ]        = fqdn_parts( socket.getfqdn() )[1]
1468            myAttrs[ 'poll_interval' ]    = str(BATCH_POLL_INTERVAL)
[524]1469
[691]1470            if self.jobDataChanged( jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
1471                jobs[ job_id ] = myAttrs
[524]1472
[691]1473                debug_msg( 10, printTime() + ' job %s state changed' %(job_id) )
[524]1474
[691]1475        for id, attrs in jobs.items():
1476            if id not in jobs_processed:
1477                # This one isn't there anymore
1478                #
1479                del jobs[ id ]
1480        self.jobs=jobs
[524]1481
1482
[355]1483class PbsDataGatherer( DataGatherer ):
[318]1484
[691]1485    """This is the DataGatherer for PBS and Torque"""
[318]1486
[691]1487    global PBSQuery, PBSError
[256]1488
[691]1489    def __init__( self ):
[354]1490
[691]1491        """Setup appropriate variables"""
[23]1492
[691]1493        self.jobs    = { }
1494        self.timeoffset    = 0
1495        self.dp        = DataProcessor()
[354]1496
[691]1497        self.initPbsQuery()
[23]1498
[691]1499    def initPbsQuery( self ):
[91]1500
[691]1501        self.pq        = None
[354]1502
[691]1503        if( BATCH_SERVER ):
[354]1504
[691]1505            self.pq        = PBSQuery( BATCH_SERVER )
1506        else:
1507            self.pq        = PBSQuery()
[91]1508
[691]1509        try:
1510            self.pq.old_data_structure()
[656]1511
[691]1512        except AttributeError:
[656]1513
[691]1514            # pbs_query is older
1515            #
1516            pass
[656]1517
[691]1518    def getJobData( self ):
[354]1519
[691]1520        """Gather all data on current jobs in Torque"""
[26]1521
[691]1522        joblist        = {}
1523        self.cur_time    = 0
[349]1524
[691]1525        try:
1526            joblist        = self.pq.getjobs()
1527            self.cur_time    = time.time()
[354]1528
[691]1529        except PBSError, detail:
[354]1530
[691]1531            debug_msg( 10, "Caught PBS unavailable, skipping until next polling interval: " + str( detail ) )
1532            return None
[354]1533
[691]1534        jobs_processed    = [ ]
[26]1535
[691]1536        for name, attrs in joblist.items():
1537            display_queue        = 1
1538            job_id            = name.split( '.' )[0]
[26]1539
[691]1540            name            = self.getAttr( attrs, 'Job_Name' )
1541            queue            = self.getAttr( attrs, 'queue' )
[317]1542
[691]1543            if QUEUE:
1544                for q in QUEUE:
1545                    if q == queue:
1546                        display_queue = 1
1547                        break
1548                    else:
1549                        display_queue = 0
1550                        continue
1551            if display_queue == 0:
1552                continue
[317]1553
1554
[691]1555            owner            = self.getAttr( attrs, 'Job_Owner' ).split( '@' )[0]
1556            requested_time        = self.getAttr( attrs, 'Resource_List.walltime' )
1557            requested_memory    = self.getAttr( attrs, 'Resource_List.mem' )
[95]1558
[691]1559            mynoderequest        = self.getAttr( attrs, 'Resource_List.nodes' )
[95]1560
[691]1561            ppn            = ''
[281]1562
[691]1563            if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
[95]1564
[691]1565                mynoderequest_fields    = mynoderequest.split( ':' )
[281]1566
[691]1567                for mynoderequest_field in mynoderequest_fields:
[281]1568
[691]1569                    if mynoderequest_field.find( 'ppn' ) != -1:
[281]1570
[691]1571                        ppn    = mynoderequest_field.split( 'ppn=' )[1]
[281]1572
[691]1573            status            = self.getAttr( attrs, 'job_state' )
[25]1574
[691]1575            if status in [ 'Q', 'R' ]:
[450]1576
[691]1577                jobs_processed.append( job_id )
[450]1578
[691]1579            queued_timestamp    = self.getAttr( attrs, 'ctime' )
[243]1580
[691]1581            if status == 'R':
[133]1582
[691]1583                start_timestamp        = self.getAttr( attrs, 'mtime' )
1584                nodes            = self.getAttr( attrs, 'exec_host' ).split( '+' )
[133]1585
[691]1586                nodeslist        = do_nodelist( nodes )
[354]1587
[691]1588                if DETECT_TIME_DIFFS:
[185]1589
[691]1590                    # If a job start if later than our current date,
1591                    # that must mean the Torque server's time is later
1592                    # than our local time.
1593               
1594                    if int( start_timestamp ) > int( int( self.cur_time ) + int( self.timeoffset ) ):
[185]1595
[691]1596                        self.timeoffset    = int( int(start_timestamp) - int(self.cur_time) )
[185]1597
[691]1598            elif status == 'Q':
[95]1599
[691]1600                # 'mynodequest' can be a string in the following syntax according to the
1601                # Torque Administator's manual:
1602                #
1603                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1604                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1605                # etc
1606                #
[451]1607
[691]1608                #
1609                # For now we only count the amount of nodes request and ignore properties
1610                #
[451]1611
[691]1612                start_timestamp        = ''
1613                count_mynodes        = 0
[354]1614
[691]1615                for node in mynoderequest.split( '+' ):
[67]1616
[691]1617                    # Just grab the {node_count|hostname} part and ignore properties
1618                    #
1619                    nodepart    = node.split( ':' )[0]
[67]1620
[691]1621                    # Let's assume a node_count value
1622                    #
1623                    numeric_node    = 1
[451]1624
[691]1625                    # Chop the value up into characters
1626                    #
1627                    for letter in nodepart:
[67]1628
[691]1629                        # If this char is not a digit (0-9), this must be a hostname
1630                        #
1631                        if letter not in string.digits:
[133]1632
[691]1633                            numeric_node    = 0
[133]1634
[691]1635                    # If this is a hostname, just count this as one (1) node
1636                    #
1637                    if not numeric_node:
[354]1638
[691]1639                        count_mynodes    = count_mynodes + 1
1640                    else:
[451]1641
[691]1642                        # If this a number, it must be the node_count
1643                        # and increase our count with it's value
1644                        #
1645                        try:
1646                            count_mynodes    = count_mynodes + int( nodepart )
[354]1647
[691]1648                        except ValueError, detail:
[354]1649
[691]1650                            # When we arrive here I must be bugged or very confused
1651                            # THIS SHOULD NOT HAPPEN!
1652                            #
1653                            debug_msg( 10, str( detail ) )
1654                            debug_msg( 10, "Encountered weird node in Resources_List?!" )
1655                            debug_msg( 10, 'nodepart = ' + str( nodepart ) )
1656                            debug_msg( 10, 'job = ' + str( name ) )
1657                            debug_msg( 10, 'attrs = ' + str( attrs ) )
1658                       
1659                nodeslist    = str( count_mynodes )
1660            else:
1661                start_timestamp    = ''
1662                nodeslist    = ''
[133]1663
[691]1664            myAttrs                = { }
[26]1665
[691]1666            myAttrs[ 'name' ]        = str( name )
1667            myAttrs[ 'queue' ]        = str( queue )
1668            myAttrs[ 'owner' ]        = str( owner )
1669            myAttrs[ 'requested_time' ]    = str( requested_time )
1670            myAttrs[ 'requested_memory' ]    = str( requested_memory )
1671            myAttrs[ 'ppn' ]        = str( ppn )
1672            myAttrs[ 'status' ]        = str( status )
1673            myAttrs[ 'start_timestamp' ]    = str( start_timestamp )
1674            myAttrs[ 'queued_timestamp' ]    = str( queued_timestamp )
1675            myAttrs[ 'reported' ]        = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1676            myAttrs[ 'nodes' ]        = nodeslist
1677            myAttrs[ 'domain' ]        = fqdn_parts( socket.getfqdn() )[1]
1678            myAttrs[ 'poll_interval' ]    = str( BATCH_POLL_INTERVAL )
[354]1679
[691]1680            if self.jobDataChanged( self.jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
[61]1681
[691]1682                self.jobs[ job_id ]    = myAttrs
[26]1683
[691]1684        for id, attrs in self.jobs.items():
[76]1685
[691]1686            if id not in jobs_processed:
[76]1687
[691]1688                # This one isn't there anymore; toedeledoki!
1689                #
1690                del self.jobs[ id ]
[76]1691
[362]1692GMETRIC_DEFAULT_TYPE    = 'string'
1693GMETRIC_DEFAULT_HOST    = '127.0.0.1'
1694GMETRIC_DEFAULT_PORT    = '8649'
[700]1695GMETRIC_DEFAULT_UNITS   = ''
[362]1696
1697class Gmetric:
1698
[691]1699    global GMETRIC_DEFAULT_HOST, GMETRIC_DEFAULT_PORT
[362]1700
[700]1701    slope           = { 'zero' : 0, 'positive' : 1, 'negative' : 2, 'both' : 3, 'unspecified' : 4 }
1702    type            = ( '', 'string', 'uint16', 'int16', 'uint32', 'int32', 'float', 'double', 'timestamp' )
1703    protocol        = ( 'udp', 'multicast' )
[362]1704
[691]1705    def __init__( self, host=GMETRIC_DEFAULT_HOST, port=GMETRIC_DEFAULT_PORT ):
[700]1706               
[691]1707        global GMETRIC_DEFAULT_TYPE
[362]1708
[691]1709        self.prot       = self.checkHostProtocol( host )
[700]1710        self.data_msg   = xdrlib.Packer()
1711        self.meta_msg   = xdrlib.Packer()
[691]1712        self.socket     = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
[362]1713
[691]1714        if self.prot not in self.protocol:
[362]1715
[691]1716            raise ValueError( "Protocol must be one of: " + str( self.protocol ) )
[362]1717
[691]1718        if self.prot == 'multicast':
[362]1719
[691]1720            # Set multicast options
1721            #
1722            self.socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20 )
[362]1723
[691]1724        self.hostport   = ( host, int( port ) )
1725        self.slopestr   = 'both'
1726        self.tmax       = 60
[362]1727
[691]1728    def checkHostProtocol( self, ip ):
[362]1729
[691]1730        """Detect if a ip adress is a multicast address"""
[471]1731
[691]1732        MULTICAST_ADDRESS_MIN   = ( "224", "0", "0", "0" )
1733        MULTICAST_ADDRESS_MAX   = ( "239", "255", "255", "255" )
[362]1734
[700]1735        ip_fields               = ip.split( '.' )
[362]1736
[691]1737        if ip_fields >= MULTICAST_ADDRESS_MIN and ip_fields <= MULTICAST_ADDRESS_MAX:
[362]1738
[691]1739            return 'multicast'
1740        else:
1741            return 'udp'
[362]1742
[691]1743    def send( self, name, value, dmax, typestr = '', units = '' ):
[362]1744
[691]1745        if len( units ) == 0:
[700]1746            units       = GMETRIC_DEFAULT_UNITS
[471]1747
[691]1748        if len( typestr ) == 0:
[700]1749            typestr     = GMETRIC_DEFAULT_TYPE
[362]1750
[700]1751        (meta_msg, data_msg) = self.makexdr( name, value, typestr, units, self.slopestr, self.tmax, dmax )
[409]1752
[700]1753        meta_rt = self.socket.sendto( meta_msg, self.hostport )
1754        data_rt = self.socket.sendto( data_msg, self.hostport )
[362]1755
[700]1756        return ( meta_rt, data_rt )
[362]1757
[700]1758    def makexdr( self, name, value, typestr, unitstr, slopestr, tmax, dmax, group=None, spoof=None ):
1759
1760        hostname = "unset"
1761
[691]1762        if slopestr not in self.slope:
[362]1763
[691]1764            raise ValueError( "Slope must be one of: " + str( self.slope.keys() ) )
[362]1765
[691]1766        if typestr not in self.type:
[362]1767
[691]1768            raise ValueError( "Type must be one of: " + str( self.type ) )
[362]1769
[691]1770        if len( name ) == 0:
[362]1771
[691]1772            raise ValueError( "Name must be non-empty" )
[362]1773
[700]1774        self.meta_msg.reset()
1775        self.meta_msg.pack_int( 128 )
[362]1776
[700]1777        if not spoof:
1778            self.meta_msg.pack_string( hostname )
1779        else:
1780            self.meta_msg.pack_string( spoof )
[362]1781
[700]1782        self.meta_msg.pack_string( name )
1783
1784        if not spoof:
1785            self.meta_msg.pack_int( 0 )
1786        else:
1787            self.meta_msg.pack_int( 1 )
1788           
1789        self.meta_msg.pack_string( typestr )
1790        self.meta_msg.pack_string( name )
1791        self.meta_msg.pack_string( unitstr )
1792        self.meta_msg.pack_int( self.slope[ slopestr ] )
1793        self.meta_msg.pack_uint( int( tmax ) )
1794        self.meta_msg.pack_uint( int( dmax ) )
1795
1796        if not group:
1797            self.meta_msg.pack_int( 0 )
1798        else:
1799            self.meta_msg.pack_int( 1 )
1800            self.meta_msg.pack_string( "GROUP" )
1801            self.meta_msg.pack_string( group )
1802
1803        self.data_msg.reset()
1804        self.data_msg.pack_int( 128+5 )
1805
1806        if not spoof:
1807            self.data_msg.pack_string( hostname )
1808        else:
1809            self.data_msg.pack_string( spoof )
1810
1811        self.data_msg.pack_string( name )
1812
1813        if not spoof:
1814            self.data_msg.pack_int( 0 )
1815        else:
1816            self.data_msg.pack_int( 1 )
1817
1818        self.data_msg.pack_string( "%s" )
1819        self.data_msg.pack_string( str( value ) )
1820
1821        return ( self.meta_msg.get_buffer(), self.data_msg.get_buffer() )
1822
[26]1823def printTime( ):
[354]1824
[691]1825    """Print current time/date in human readable format for log/debug"""
[26]1826
[691]1827    return time.strftime("%a, %d %b %Y %H:%M:%S")
[26]1828
1829def debug_msg( level, msg ):
[354]1830
[691]1831    """Print msg if at or above current debug level"""
[26]1832
[691]1833    global DAEMONIZE, DEBUG_LEVEL, SYSLOG_LEVEL
[377]1834
[691]1835    if (not DAEMONIZE and DEBUG_LEVEL >= level):
1836        sys.stderr.write( msg + '\n' )
[26]1837
[691]1838    if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
1839        syslog.syslog( msg )
[373]1840
[307]1841def write_pidfile():
1842
[691]1843    # Write pidfile if PIDFILE is set
1844    #
1845    if PIDFILE:
[307]1846
[691]1847        pid    = os.getpid()
[354]1848
[691]1849        pidfile    = open( PIDFILE, 'w' )
[354]1850
[691]1851        pidfile.write( str( pid ) )
1852        pidfile.close()
[307]1853
[23]1854def main():
[354]1855
[691]1856    """Application start"""
[23]1857
[691]1858    global PBSQuery, PBSError, lsfObject
1859    global SYSLOG_FACILITY, USE_SYSLOG, BATCH_API, DAEMONIZE
[256]1860
[691]1861    if not processArgs( sys.argv[1:] ):
[354]1862
[691]1863        sys.exit( 1 )
[212]1864
[691]1865    # Load appropriate DataGatherer depending on which BATCH_API is set
1866    # and any required modules for the Gatherer
1867    #
1868    if BATCH_API == 'pbs':
[256]1869
[691]1870        try:
1871            from PBSQuery import PBSQuery, PBSError
[256]1872
[691]1873        except ImportError:
[256]1874
[691]1875            debug_msg( 0, "FATAL ERROR: BATCH_API set to 'pbs' but python module 'pbs_python' is not installed" )
1876            sys.exit( 1 )
[256]1877
[691]1878        gather = PbsDataGatherer()
[256]1879
[691]1880    elif BATCH_API == 'sge':
[256]1881
[691]1882        # Tested with SGE 6.0u11.
1883        #
1884        gather = SgeDataGatherer()
[368]1885
[691]1886    elif BATCH_API == 'lsf':
[368]1887
[691]1888        try:
1889            from lsfObject import lsfObject
1890        except:
1891            debug_msg(0, "fatal error: BATCH_API set to 'lsf' but python module is not found or installed")
1892            sys.exit( 1)
[256]1893
[691]1894        gather = LsfDataGatherer()
[524]1895
[691]1896    else:
1897        debug_msg( 0, "FATAL ERROR: unknown BATCH_API '" + BATCH_API + "' is not supported" )
[354]1898
[691]1899        sys.exit( 1 )
[256]1900
[691]1901    if( DAEMONIZE and USE_SYSLOG ):
[373]1902
[691]1903        syslog.openlog( 'jobmond', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
[373]1904
[691]1905    if DAEMONIZE:
[354]1906
[691]1907        gather.daemon()
1908    else:
1909        gather.run()
[23]1910
[256]1911# wh00t? someone started me! :)
[65]1912#
[23]1913if __name__ == '__main__':
[691]1914    main()
Note: See TracBrowser for help on using the repository browser.