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

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