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

Last change on this file since 753 was 728, checked in by ramonb, 11 years ago
  • changed seperator to _
  • changed job-id-incr to job_incr_id
  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 57.5 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 728 2013-03-22 12:49:41Z 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
[728]826        self.dp.multicastGmetric( 'zplugin_monarch_heartbeat', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
[507]827
[724]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        #
[728]845        self.dp.multicastGmetric( 'zplugin_monarch_rj', str( running_jobs ), 'uint32', 'jobs' )
846        self.dp.multicastGmetric( 'zplugin_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
[728]854            downed_nodes  = list()
855            offline_nodes = list()
[691]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
[728]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 ) ) ) )
[728]874            self.dp.multicastGmetric( 'zplugin_monarch_down'   , down_str )
875            self.dp.multicastGmetric( 'zplugin_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
[728]891                metric_name = 'zplugin_monarch_job_%s_%s' %( str(metric_increment) , str( jobid ) )
892                self.dp.multicastGmetric( metric_name, val )
[507]893
[691]894                # Increase follow number if this jobinfo is split up amongst more than 1 gmetric
895                #
896                metric_increment    = metric_increment + 1
[507]897
[691]898    def compileGmetricVal( self, jobid, jobattrs ):
[507]899
[691]900        """Create a val string for gmetric of jobinfo"""
[507]901
[691]902        gval_lists    = [ ]
903        val_list    = { }
[507]904
[691]905        for val_name, val_value in jobattrs.items():
[507]906
[691]907            # These are our own metric names, i.e.: status, start_timestamp, etc
908            #
909            val_list_names_len    = len( string.join( val_list.keys() ) ) + len(val_list.keys())
[507]910
[691]911            # These are their corresponding values
912            #
913            val_list_vals_len    = len( string.join( val_list.values() ) ) + len(val_list.values())
[507]914
[691]915            if val_name == 'nodes' and jobattrs['status'] == 'R':
[507]916
[691]917                node_str = None
[507]918
[691]919                for node in val_value:
[507]920
[691]921                    if node_str:
[507]922
[691]923                        node_str = node_str + ';' + node
924                    else:
925                        node_str = node
[507]926
[691]927                    # Make sure if we add this new info, that the total metric's value length does not exceed METRIC_MAX_VAL_LEN
928                    #
929                    if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(node_str) ) > METRIC_MAX_VAL_LEN:
[507]930
[691]931                        # It's too big, we need to make a new gmetric for the additional info
932                        #
933                        val_list[ val_name ]    = node_str
[507]934
[691]935                        gval_lists.append( val_list )
[507]936
[691]937                        val_list        = { }
938                        node_str        = None
[507]939
[691]940                val_list[ val_name ]    = node_str
[507]941
[691]942                gval_lists.append( val_list )
[507]943
[691]944                val_list        = { }
[507]945
[691]946            elif val_value != '':
[507]947
[691]948                # Make sure if we add this new info, that the total metric's value length does not exceed METRIC_MAX_VAL_LEN
949                #
950                if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(str(val_value)) ) > METRIC_MAX_VAL_LEN:
[507]951
[691]952                    # It's too big, we need to make a new gmetric for the additional info
953                    #
954                    gval_lists.append( val_list )
[507]955
[691]956                    val_list        = { }
[507]957
[691]958                val_list[ val_name ]    = val_value
[507]959
[691]960        if len( val_list ) > 0:
[507]961
[691]962            gval_lists.append( val_list )
[507]963
[691]964        str_list    = [ ]
[507]965
[691]966        # Now append the value names and values together, i.e.: stop_timestamp=value, etc
967        #
968        for val_list in gval_lists:
[507]969
[691]970            my_val_str    = None
[507]971
[691]972            for val_name, val_value in val_list.items():
[507]973
[691]974                if type(val_value) == list:
[579]975
[691]976                    val_value    = val_value.join( ',' )
[579]977
[691]978                if my_val_str:
[507]979
[691]980                    try:
981                        # fixme: It's getting
982                        # ('nodes', None) items
983                        my_val_str = my_val_str + ' ' + val_name + '=' + val_value
984                    except:
985                        pass
[623]986
[691]987                else:
988                    my_val_str = val_name + '=' + val_value
[507]989
[691]990            str_list.append( my_val_str )
[507]991
[691]992        return str_list
[507]993
[691]994    def daemon( self ):
[355]995
[691]996        """Run as daemon forever"""
[256]997
[691]998        # Fork the first child
999        #
1000        pid = os.fork()
1001        if pid > 0:
1002            sys.exit(0)  # end parent
[256]1003
[691]1004        # creates a session and sets the process group ID
1005        #
1006        os.setsid()
[318]1007
[691]1008        # Fork the second child
1009        #
1010        pid = os.fork()
1011        if pid > 0:
1012            sys.exit(0)  # end parent
[318]1013
[691]1014        write_pidfile()
[318]1015
[691]1016        # Go to the root directory and set the umask
1017        #
1018        os.chdir('/')
1019        os.umask(0)
[318]1020
[691]1021        sys.stdin.close()
1022        sys.stdout.close()
1023        sys.stderr.close()
[318]1024
[691]1025        os.open('/dev/null', os.O_RDWR)
1026        os.dup2(0, 1)
1027        os.dup2(0, 2)
[318]1028
[691]1029        self.run()
[318]1030
[691]1031    def run( self ):
[355]1032
[691]1033        """Main thread"""
[256]1034
[691]1035        while ( 1 ):
1036       
1037            self.getJobData()
1038            self.submitJobData()
1039            time.sleep( BATCH_POLL_INTERVAL )   
[256]1040
[623]1041# SGE code by Dave Love <fx@gnu.org>.  Tested with SGE 6.0u8 and 6.0u11.  May
1042# work with SGE 6.1 (else should be easily fixable), but definitely doesn't
1043# with 6.2.  See also the fixmes.
[256]1044
[507]1045class NoJobs (Exception):
[691]1046    """Exception raised by empty job list in qstat output."""
1047    pass
[256]1048
[507]1049class SgeQstatXMLParser(xml.sax.handler.ContentHandler):
[691]1050    """SAX handler for XML output from Sun Grid Engine's `qstat'."""
[318]1051
[691]1052    def __init__(self):
1053        self.value = ""
1054        self.joblist = []
1055        self.job = {}
1056        self.queue = ""
1057        self.in_joblist = False
1058        self.lrequest = False
1059        self.eltq = deque()
1060        xml.sax.handler.ContentHandler.__init__(self)
[318]1061
[691]1062    # The structure of the output is as follows (for SGE 6.0).  It's
1063    # similar for 6.1, but radically different for 6.2, and is
1064    # undocumented generally.  Unfortunately it's voluminous, and probably
1065    # doesn't scale to large clusters/queues.
[318]1066
[691]1067    # <detailed_job_info  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
1068    #   <djob_info>
1069    #     <qmaster_response>  <!-- job -->
1070    #       ...
1071    #       <JB_ja_template> 
1072    #     <ulong_sublist>
1073    #     ...         <!-- start_time, state ... -->
1074    #     </ulong_sublist>
1075    #       </JB_ja_template> 
1076    #       <JB_ja_tasks>
1077    #     <ulong_sublist>
1078    #       ...       <!-- task info
1079    #     </ulong_sublist>
1080    #     ...
1081    #       </JB_ja_tasks>
1082    #       ...
1083    #     </qmaster_response>
1084    #   </djob_info>
1085    #   <messages>
1086    #   ...
[318]1087
[691]1088    # NB.  We might treat each task as a separate job, like
1089    # straight qstat output, but the web interface expects jobs to
1090    # be identified by integers, not, say, <job number>.<task>.
[318]1091
[691]1092    # So, I lied.  If the job list is empty, we get invalid XML
1093    # like this, which we need to defend against:
[318]1094
[691]1095    # <unknown_jobs  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
1096    #   <>
1097    #     <ST_name>*</ST_name>
1098    #   </>
1099    # </unknown_jobs>
[318]1100
[691]1101    def startElement(self, name, attrs):
1102        self.value = ""
1103        if name == "djob_info":    # job list
1104            self.in_joblist = True
1105        # The job container is "qmaster_response" in SGE 6.0
1106        # and 6.1, but "element" in 6.2.  This is only the very
1107        # start of what's necessary for 6.2, though (sigh).
1108        elif (name == "qmaster_response" or name == "element") \
1109                and self.eltq[-1] == "djob_info": # job
1110            self.job = {"job_state": "U", "slots": 0,
1111                    "nodes": [], "queued_timestamp": "",
1112                    "queued_timestamp": "", "queue": "",
1113                    "ppn": "0", "RN_max": 0,
1114                    # fixme in endElement
1115                    "requested_memory": 0, "requested_time": 0
1116                    }
1117            self.joblist.append(self.job)
1118        elif name == "qstat_l_requests": # resource request
1119            self.lrequest = True
1120        elif name == "unknown_jobs":
1121            raise NoJobs
1122        self.eltq.append (name)
[318]1123
[691]1124    def characters(self, ch):
1125        self.value += ch
[318]1126
[691]1127    def endElement(self, name): 
1128        """Snarf job elements contents into job dictionary.
1129           Translate keys if appropriate."""
[318]1130
[691]1131        name_trans = {
1132          "JB_job_number": "number",
1133          "JB_job_name": "name", "JB_owner": "owner",
1134          "queue_name": "queue", "JAT_start_time": "start_timestamp",
1135          "JB_submission_time": "queued_timestamp"
1136          }
1137        value = self.value
1138        self.eltq.pop ()
[318]1139
[691]1140        if name == "djob_info":
1141            self.in_joblist = False
1142            self.job = {}
1143        elif name == "JAT_master_queue":
1144            self.job["queue"] = value.split("@")[0]
1145        elif name == "JG_qhostname":
1146            if not (value in self.job["nodes"]):
1147                self.job["nodes"].append(value)
1148        elif name == "JG_slots": # slots in use
1149            self.job["slots"] += int(value)
1150        elif name == "RN_max": # requested slots (tasks or parallel)
1151            self.job["RN_max"] = max (self.job["RN_max"],
1152                          int(value))
1153        elif name == "JAT_state": # job state (bitwise or)
1154            value = int (value)
1155            # Status values from sge_jobL.h
1156            #define JIDLE           0x00000000
1157            #define JHELD           0x00000010
1158            #define JMIGRATING          0x00000020
1159            #define JQUEUED         0x00000040
1160            #define JRUNNING        0x00000080
1161            #define JSUSPENDED          0x00000100
1162            #define JTRANSFERING        0x00000200
1163            #define JDELETED        0x00000400
1164            #define JWAITING        0x00000800
1165            #define JEXITING        0x00001000
1166            #define JWRITTEN        0x00002000
1167            #define JSUSPENDED_ON_THRESHOLD 0x00010000
1168            #define JFINISHED           0x00010000
1169            if value & 0x80:
1170                self.job["status"] = "R"
1171            elif value & 0x40:
1172                self.job["status"] = "Q"
1173            else:
1174                self.job["status"] = "O" # `other'
1175        elif name == "CE_name" and self.lrequest and self.value in \
1176                ("h_cpu", "s_cpu", "cpu", "h_core", "s_core"):
1177            # We're in a container for an interesting resource
1178            # request; record which type.
1179            self.lrequest = self.value
1180        elif name == "CE_doubleval" and self.lrequest:
1181            # if we're in a container for an interesting
1182            # resource request, use the maxmimum of the hard
1183            # and soft requests to record the requested CPU
1184            # or core.  Fixme:  I'm not sure if this logic is
1185            # right.
1186            if self.lrequest in ("h_core", "s_core"):
1187                self.job["requested_memory"] = \
1188                    max (float (value),
1189                     self.job["requested_memory"])
1190            # Fixme:  Check what cpu means, c.f [hs]_cpu.
1191            elif self.lrequest in ("h_cpu", "s_cpu", "cpu"):
1192                self.job["requested_time"] = \
1193                    max (float (value),
1194                     self.job["requested_time"])
1195        elif name == "qstat_l_requests":
1196            self.lrequest = False
1197        elif self.job and self.in_joblist:
1198            if name in name_trans:
1199                name = name_trans[name]
1200                self.job[name] = value
[318]1201
[507]1202# Abstracted from PBS original.
1203# Fixme:  Is it worth (or appropriate for PBS) sorting the result?
[520]1204#
1205def do_nodelist( nodes ):
1206
[691]1207    """Translate node list as appropriate."""
[520]1208
[691]1209    nodeslist        = [ ]
1210    my_domain        = fqdn_parts( socket.getfqdn() )[1]
[520]1211
[691]1212    for node in nodes:
[520]1213
[691]1214        host        = node.split( '/' )[0] # not relevant for SGE
1215        h, host_domain    = fqdn_parts(host)
[520]1216
[691]1217        if host_domain == my_domain:
[520]1218
[691]1219            host    = h
[520]1220
[691]1221        if nodeslist.count( host ) == 0:
[520]1222
[691]1223            for translate_pattern in BATCH_HOST_TRANSLATE:
[520]1224
[691]1225                if translate_pattern.find( '/' ) != -1:
[520]1226
[691]1227                    translate_orig    = \
1228                        translate_pattern.split( '/' )[1]
1229                    translate_new    = \
1230                        translate_pattern.split( '/' )[2]
1231                    host = re.sub( translate_orig,
1232                               translate_new, host )
1233            if not host in nodeslist:
1234                nodeslist.append( host )
1235    return nodeslist
[318]1236
1237class SgeDataGatherer(DataGatherer):
1238
[691]1239    jobs = {}
[61]1240
[691]1241    def __init__( self ):
1242        self.jobs = {}
1243        self.timeoffset = 0
1244        self.dp = DataProcessor()
[318]1245
[691]1246    def getJobData( self ):
1247        """Gather all data on current jobs in SGE"""
[318]1248
[691]1249        import popen2
[318]1250
[691]1251        self.cur_time = 0
1252        queues = ""
1253        if QUEUE:    # only for specific queues
1254            # Fixme:  assumes queue names don't contain single
1255            # quote or comma.  Don't know what the SGE rules are.
1256            queues = " -q '" + string.join (QUEUE, ",") + "'"
1257        # Note the comment in SgeQstatXMLParser about scaling with
1258        # this method of getting data.  I haven't found better one.
1259        # Output with args `-xml -ext -f -r' is easier to parse
1260        # in some ways, harder in others, but it doesn't provide
1261        # the submission time (at least SGE 6.0).  The pipeline
1262        # into sed corrects bogus XML observed with a configuration
1263        # of SGE 6.0u8, which otherwise causes the parsing to hang.
1264        piping = popen2.Popen3("qstat -u '*' -j '*' -xml | \
[623]1265sed -e 's/reported usage>/reported_usage>/g' -e 's;<\/*JATASK:.*>;;'" \
[691]1266                           + queues, True)
1267        qstatparser = SgeQstatXMLParser()
1268        parse_err = 0
1269        try:
1270            xml.sax.parse(piping.fromchild, qstatparser)
1271        except NoJobs:
1272            pass
1273        except:
1274            parse_err = 1
[704]1275        if piping.wait():
1276            debug_msg(10, "qstat error, skipping until next polling interval: " + piping.childerr.readline())
[691]1277            return None
1278        elif parse_err:
1279            debug_msg(10, "Bad XML output from qstat"())
1280            exit (1)
1281        for f in piping.fromchild, piping.tochild, piping.childerr:
1282            f.close()
1283        self.cur_time = time.time()
1284        jobs_processed = []
1285        for job in qstatparser.joblist:
1286            job_id = job["number"]
1287            if job["status"] in [ 'Q', 'R' ]:
1288                jobs_processed.append(job_id)
1289            if job["status"] == "R":
1290                job["nodes"] = do_nodelist (job["nodes"])
1291                # Fixme: why is job["nodes"] sometimes null?
1292                try:
1293                    # Fixme: Is this sensible?  The
1294                    # PBS-type PPN isn't something you use
1295                    # with SGE.
[704]1296                    job["ppn"] = float(job["slots"]) / len(job["nodes"])
[691]1297                except:
1298                    job["ppn"] = 0
1299                if DETECT_TIME_DIFFS:
1300                    # If a job start is later than our
1301                    # current date, that must mean
1302                    # the SGE server's time is later
1303                    # than our local time.
[704]1304                    start_timestamp = int (job["start_timestamp"])
1305                    if start_timestamp > int(self.cur_time) + int(self.timeoffset):
[318]1306
[704]1307                        self.timeoffset    = start_timestamp - int(self.cur_time)
[691]1308            else:
1309                # fixme: Note sure what this should be:
1310                job["ppn"] = job["RN_max"]
1311                job["nodes"] = "1"
[318]1312
[691]1313            myAttrs = {}
1314            for attr in ["name", "queue", "owner",
1315                     "requested_time", "status",
1316                     "requested_memory", "ppn",
1317                     "start_timestamp", "queued_timestamp"]:
1318                myAttrs[attr] = str(job[attr])
1319            myAttrs["nodes"] = job["nodes"]
[704]1320            myAttrs["reported"] = str(int(self.cur_time) + int(self.timeoffset))
[691]1321            myAttrs["domain"] = fqdn_parts(socket.getfqdn())[1]
1322            myAttrs["poll_interval"] = str(BATCH_POLL_INTERVAL)
[318]1323
[704]1324            if self.jobDataChanged(self.jobs, job_id, myAttrs) and myAttrs["status"] in ["R", "Q"]:
[691]1325                self.jobs[job_id] = myAttrs
1326        for id, attrs in self.jobs.items():
1327            if id not in jobs_processed:
1328                del self.jobs[id]
[318]1329
[524]1330# LSF code by Mahmoud Hanafi <hanafim@users.sourceforge.nt>
1331# Requres LSFObject http://sourceforge.net/projects/lsfobject
1332#
1333class LsfDataGatherer(DataGatherer):
[525]1334
[691]1335    """This is the DataGatherer for LSf"""
[524]1336
[691]1337    global lsfObject
[524]1338
[691]1339    def __init__( self ):
[525]1340
[691]1341        self.jobs = { }
1342        self.timeoffset = 0
1343        self.dp = DataProcessor()
1344        self.initLsfQuery()
[524]1345
[691]1346    def _countDuplicatesInList( self, dupedList ):
[525]1347
[691]1348        countDupes    = { }
[525]1349
[691]1350        for item in dupedList:
[525]1351
[691]1352            if not countDupes.has_key( item ):
[525]1353
[691]1354                countDupes[ item ]    = 1
1355            else:
1356                countDupes[ item ]    = countDupes[ item ] + 1
[525]1357
[691]1358        dupeCountList    = [ ]
[525]1359
[691]1360        for item, count in countDupes.items():
[525]1361
[691]1362            dupeCountList.append( ( item, count ) )
[525]1363
[691]1364        return dupeCountList
[524]1365#
1366#lst = ['I1','I2','I1','I3','I4','I4','I7','I7','I7','I7','I7']
1367#print _countDuplicatesInList(lst)
1368#[('I1', 2), ('I3', 1), ('I2', 1), ('I4', 2), ('I7', 5)]
1369########################
1370
[691]1371    def initLsfQuery( self ):
1372        self.pq = None
1373        self.pq = lsfObject.jobInfoEntObject()
[524]1374
[691]1375    def getJobData( self, known_jobs="" ):
1376        """Gather all data on current jobs in LSF"""
1377        if len( known_jobs ) > 0:
1378            jobs = known_jobs
1379        else:
1380            jobs = { }
1381        joblist = {}
1382        joblist = self.pq.getJobInfo()
1383        nodelist = ''
[524]1384
[691]1385        self.cur_time = time.time()
[524]1386
[691]1387        jobs_processed = [ ]
[524]1388
[691]1389        for name, attrs in joblist.items():
1390            job_id = str(name)
1391            jobs_processed.append( job_id )
1392            name = self.getAttr( attrs, 'jobName' )
1393            queue = self.getAttr( self.getAttr( attrs, 'submit') , 'queue' )
1394            owner = self.getAttr( attrs, 'user' )
[524]1395
1396### THIS IS THE rLimit List index values
[691]1397#define LSF_RLIMIT_CPU      0        /* cpu time in milliseconds */
1398#define LSF_RLIMIT_FSIZE    1        /* maximum file size */
1399#define LSF_RLIMIT_DATA     2        /* data size */
1400#define LSF_RLIMIT_STACK    3        /* stack size */
1401#define LSF_RLIMIT_CORE     4        /* core file size */
1402#define LSF_RLIMIT_RSS      5        /* resident set size */
1403#define LSF_RLIMIT_NOFILE   6        /* open files */
1404#define LSF_RLIMIT_OPEN_MAX 7        /* (from HP-UX) */
1405#define LSF_RLIMIT_VMEM     8        /* maximum swap mem */
[524]1406#define LSF_RLIMIT_SWAP     8
[691]1407#define LSF_RLIMIT_RUN      9        /* max wall-clock time limit */
1408#define LSF_RLIMIT_PROCESS  10       /* process number limit */
1409#define LSF_RLIMIT_THREAD   11       /* thread number limit (introduced in LSF6.0) */
1410#define LSF_RLIM_NLIMITS    12       /* number of resource limits */
[524]1411
[691]1412            requested_time = self.getAttr( self.getAttr( attrs, 'submit') , 'rLimits' )[9]
1413            if requested_time == -1: 
1414                requested_time = ""
1415            requested_memory = self.getAttr( self.getAttr( attrs, 'submit') , 'rLimits' )[8]
1416            if requested_memory == -1: 
1417                requested_memory = ""
[524]1418# This tries to get proc per node. We don't support this right now
[691]1419            ppn = 0 #self.getAttr( self.getAttr( attrs, 'SubmitList') , 'numProessors' )
1420            requested_cpus = self.getAttr( self.getAttr( attrs, 'submit') , 'numProcessors' )
1421            if requested_cpus == None or requested_cpus == "":
1422                requested_cpus = 1
[524]1423
[691]1424            if QUEUE:
1425                for q in QUEUE:
1426                    if q == queue:
1427                        display_queue = 1
1428                        break
1429                    else:
1430                        display_queue = 0
1431                        continue
1432            if display_queue == 0:
1433                continue
[524]1434
[691]1435            runState = self.getAttr( attrs, 'status' )
1436            if runState == 4:
1437                status = 'R'
1438            else:
1439                status = 'Q'
1440            queued_timestamp = self.getAttr( attrs, 'submitTime' )
[524]1441
[691]1442            if status == 'R':
1443                start_timestamp = self.getAttr( attrs, 'startTime' )
1444                nodesCpu =  dict(self._countDuplicatesInList(self.getAttr( attrs, 'exHosts' )))
1445                nodelist = nodesCpu.keys()
[524]1446
[691]1447                if DETECT_TIME_DIFFS:
[524]1448
[691]1449                    # If a job start if later than our current date,
1450                    # that must mean the Torque server's time is later
1451                    # than our local time.
[524]1452
[691]1453                    if int(start_timestamp) > int( int(self.cur_time) + int(self.timeoffset) ):
[524]1454
[691]1455                        self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
[524]1456
[691]1457            elif status == 'Q':
1458                start_timestamp = ''
1459                count_mynodes = 0
1460                numeric_node = 1
1461                nodelist = ''
[524]1462
[691]1463            myAttrs = { }
1464            if name == "":
1465                myAttrs['name'] = "none"
1466            else:
1467                myAttrs['name'] = name
[524]1468
[691]1469            myAttrs[ 'owner' ]        = owner
1470            myAttrs[ 'requested_time' ]    = str(requested_time)
1471            myAttrs[ 'requested_memory' ]    = str(requested_memory)
1472            myAttrs[ 'requested_cpus' ]    = str(requested_cpus)
1473            myAttrs[ 'ppn' ]        = str( ppn )
1474            myAttrs[ 'status' ]        = status
1475            myAttrs[ 'start_timestamp' ]    = str(start_timestamp)
1476            myAttrs[ 'queue' ]        = str(queue)
1477            myAttrs[ 'queued_timestamp' ]    = str(queued_timestamp)
1478            myAttrs[ 'reported' ]        = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1479            myAttrs[ 'nodes' ]        = do_nodelist( nodelist )
1480            myAttrs[ 'domain' ]        = fqdn_parts( socket.getfqdn() )[1]
1481            myAttrs[ 'poll_interval' ]    = str(BATCH_POLL_INTERVAL)
[524]1482
[691]1483            if self.jobDataChanged( jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
1484                jobs[ job_id ] = myAttrs
[524]1485
[691]1486                debug_msg( 10, printTime() + ' job %s state changed' %(job_id) )
[524]1487
[691]1488        for id, attrs in jobs.items():
1489            if id not in jobs_processed:
1490                # This one isn't there anymore
1491                #
1492                del jobs[ id ]
1493        self.jobs=jobs
[524]1494
1495
[355]1496class PbsDataGatherer( DataGatherer ):
[318]1497
[691]1498    """This is the DataGatherer for PBS and Torque"""
[318]1499
[691]1500    global PBSQuery, PBSError
[256]1501
[691]1502    def __init__( self ):
[354]1503
[691]1504        """Setup appropriate variables"""
[23]1505
[691]1506        self.jobs    = { }
1507        self.timeoffset    = 0
1508        self.dp        = DataProcessor()
[354]1509
[691]1510        self.initPbsQuery()
[23]1511
[691]1512    def initPbsQuery( self ):
[91]1513
[691]1514        self.pq        = None
[354]1515
[691]1516        if( BATCH_SERVER ):
[354]1517
[691]1518            self.pq        = PBSQuery( BATCH_SERVER )
1519        else:
1520            self.pq        = PBSQuery()
[91]1521
[691]1522        try:
1523            self.pq.old_data_structure()
[656]1524
[691]1525        except AttributeError:
[656]1526
[691]1527            # pbs_query is older
1528            #
1529            pass
[656]1530
[691]1531    def getJobData( self ):
[354]1532
[691]1533        """Gather all data on current jobs in Torque"""
[26]1534
[691]1535        joblist        = {}
1536        self.cur_time    = 0
[349]1537
[691]1538        try:
1539            joblist        = self.pq.getjobs()
1540            self.cur_time    = time.time()
[354]1541
[691]1542        except PBSError, detail:
[354]1543
[691]1544            debug_msg( 10, "Caught PBS unavailable, skipping until next polling interval: " + str( detail ) )
1545            return None
[354]1546
[691]1547        jobs_processed    = [ ]
[26]1548
[691]1549        for name, attrs in joblist.items():
1550            display_queue        = 1
1551            job_id            = name.split( '.' )[0]
[26]1552
[691]1553            name            = self.getAttr( attrs, 'Job_Name' )
1554            queue            = self.getAttr( attrs, 'queue' )
[317]1555
[691]1556            if QUEUE:
1557                for q in QUEUE:
1558                    if q == queue:
1559                        display_queue = 1
1560                        break
1561                    else:
1562                        display_queue = 0
1563                        continue
1564            if display_queue == 0:
1565                continue
[317]1566
1567
[691]1568            owner            = self.getAttr( attrs, 'Job_Owner' ).split( '@' )[0]
1569            requested_time        = self.getAttr( attrs, 'Resource_List.walltime' )
1570            requested_memory    = self.getAttr( attrs, 'Resource_List.mem' )
[95]1571
[691]1572            mynoderequest        = self.getAttr( attrs, 'Resource_List.nodes' )
[95]1573
[691]1574            ppn            = ''
[281]1575
[691]1576            if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
[95]1577
[691]1578                mynoderequest_fields    = mynoderequest.split( ':' )
[281]1579
[691]1580                for mynoderequest_field in mynoderequest_fields:
[281]1581
[691]1582                    if mynoderequest_field.find( 'ppn' ) != -1:
[281]1583
[691]1584                        ppn    = mynoderequest_field.split( 'ppn=' )[1]
[281]1585
[691]1586            status            = self.getAttr( attrs, 'job_state' )
[25]1587
[691]1588            if status in [ 'Q', 'R' ]:
[450]1589
[691]1590                jobs_processed.append( job_id )
[450]1591
[691]1592            queued_timestamp    = self.getAttr( attrs, 'ctime' )
[243]1593
[691]1594            if status == 'R':
[133]1595
[691]1596                start_timestamp        = self.getAttr( attrs, 'mtime' )
1597                nodes            = self.getAttr( attrs, 'exec_host' ).split( '+' )
[133]1598
[691]1599                nodeslist        = do_nodelist( nodes )
[354]1600
[691]1601                if DETECT_TIME_DIFFS:
[185]1602
[691]1603                    # If a job start if later than our current date,
1604                    # that must mean the Torque server's time is later
1605                    # than our local time.
1606               
1607                    if int( start_timestamp ) > int( int( self.cur_time ) + int( self.timeoffset ) ):
[185]1608
[691]1609                        self.timeoffset    = int( int(start_timestamp) - int(self.cur_time) )
[185]1610
[691]1611            elif status == 'Q':
[95]1612
[691]1613                # 'mynodequest' can be a string in the following syntax according to the
1614                # Torque Administator's manual:
1615                #
1616                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1617                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1618                # etc
1619                #
[451]1620
[691]1621                #
1622                # For now we only count the amount of nodes request and ignore properties
1623                #
[451]1624
[691]1625                start_timestamp        = ''
1626                count_mynodes        = 0
[354]1627
[691]1628                for node in mynoderequest.split( '+' ):
[67]1629
[691]1630                    # Just grab the {node_count|hostname} part and ignore properties
1631                    #
1632                    nodepart    = node.split( ':' )[0]
[67]1633
[691]1634                    # Let's assume a node_count value
1635                    #
1636                    numeric_node    = 1
[451]1637
[691]1638                    # Chop the value up into characters
1639                    #
1640                    for letter in nodepart:
[67]1641
[691]1642                        # If this char is not a digit (0-9), this must be a hostname
1643                        #
1644                        if letter not in string.digits:
[133]1645
[691]1646                            numeric_node    = 0
[133]1647
[691]1648                    # If this is a hostname, just count this as one (1) node
1649                    #
1650                    if not numeric_node:
[354]1651
[691]1652                        count_mynodes    = count_mynodes + 1
1653                    else:
[451]1654
[691]1655                        # If this a number, it must be the node_count
1656                        # and increase our count with it's value
1657                        #
1658                        try:
1659                            count_mynodes    = count_mynodes + int( nodepart )
[354]1660
[691]1661                        except ValueError, detail:
[354]1662
[691]1663                            # When we arrive here I must be bugged or very confused
1664                            # THIS SHOULD NOT HAPPEN!
1665                            #
1666                            debug_msg( 10, str( detail ) )
1667                            debug_msg( 10, "Encountered weird node in Resources_List?!" )
1668                            debug_msg( 10, 'nodepart = ' + str( nodepart ) )
1669                            debug_msg( 10, 'job = ' + str( name ) )
1670                            debug_msg( 10, 'attrs = ' + str( attrs ) )
1671                       
1672                nodeslist    = str( count_mynodes )
1673            else:
1674                start_timestamp    = ''
1675                nodeslist    = ''
[133]1676
[691]1677            myAttrs                = { }
[26]1678
[691]1679            myAttrs[ 'name' ]        = str( name )
1680            myAttrs[ 'queue' ]        = str( queue )
1681            myAttrs[ 'owner' ]        = str( owner )
1682            myAttrs[ 'requested_time' ]    = str( requested_time )
1683            myAttrs[ 'requested_memory' ]    = str( requested_memory )
1684            myAttrs[ 'ppn' ]        = str( ppn )
1685            myAttrs[ 'status' ]        = str( status )
1686            myAttrs[ 'start_timestamp' ]    = str( start_timestamp )
1687            myAttrs[ 'queued_timestamp' ]    = str( queued_timestamp )
1688            myAttrs[ 'reported' ]        = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1689            myAttrs[ 'nodes' ]        = nodeslist
1690            myAttrs[ 'domain' ]        = fqdn_parts( socket.getfqdn() )[1]
1691            myAttrs[ 'poll_interval' ]    = str( BATCH_POLL_INTERVAL )
[354]1692
[691]1693            if self.jobDataChanged( self.jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
[61]1694
[691]1695                self.jobs[ job_id ]    = myAttrs
[26]1696
[691]1697        for id, attrs in self.jobs.items():
[76]1698
[691]1699            if id not in jobs_processed:
[76]1700
[691]1701                # This one isn't there anymore; toedeledoki!
1702                #
1703                del self.jobs[ id ]
[76]1704
[362]1705GMETRIC_DEFAULT_TYPE    = 'string'
1706GMETRIC_DEFAULT_HOST    = '127.0.0.1'
1707GMETRIC_DEFAULT_PORT    = '8649'
[700]1708GMETRIC_DEFAULT_UNITS   = ''
[362]1709
1710class Gmetric:
1711
[691]1712    global GMETRIC_DEFAULT_HOST, GMETRIC_DEFAULT_PORT
[362]1713
[700]1714    slope           = { 'zero' : 0, 'positive' : 1, 'negative' : 2, 'both' : 3, 'unspecified' : 4 }
1715    type            = ( '', 'string', 'uint16', 'int16', 'uint32', 'int32', 'float', 'double', 'timestamp' )
1716    protocol        = ( 'udp', 'multicast' )
[362]1717
[691]1718    def __init__( self, host=GMETRIC_DEFAULT_HOST, port=GMETRIC_DEFAULT_PORT ):
[700]1719               
[691]1720        global GMETRIC_DEFAULT_TYPE
[362]1721
[691]1722        self.prot       = self.checkHostProtocol( host )
[700]1723        self.data_msg   = xdrlib.Packer()
1724        self.meta_msg   = xdrlib.Packer()
[691]1725        self.socket     = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
[362]1726
[691]1727        if self.prot not in self.protocol:
[362]1728
[691]1729            raise ValueError( "Protocol must be one of: " + str( self.protocol ) )
[362]1730
[691]1731        if self.prot == 'multicast':
[362]1732
[691]1733            # Set multicast options
1734            #
1735            self.socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20 )
[362]1736
[691]1737        self.hostport   = ( host, int( port ) )
1738        self.slopestr   = 'both'
1739        self.tmax       = 60
[362]1740
[691]1741    def checkHostProtocol( self, ip ):
[362]1742
[691]1743        """Detect if a ip adress is a multicast address"""
[471]1744
[691]1745        MULTICAST_ADDRESS_MIN   = ( "224", "0", "0", "0" )
1746        MULTICAST_ADDRESS_MAX   = ( "239", "255", "255", "255" )
[362]1747
[700]1748        ip_fields               = ip.split( '.' )
[362]1749
[691]1750        if ip_fields >= MULTICAST_ADDRESS_MIN and ip_fields <= MULTICAST_ADDRESS_MAX:
[362]1751
[691]1752            return 'multicast'
1753        else:
1754            return 'udp'
[362]1755
[691]1756    def send( self, name, value, dmax, typestr = '', units = '' ):
[362]1757
[691]1758        if len( units ) == 0:
[700]1759            units       = GMETRIC_DEFAULT_UNITS
[471]1760
[691]1761        if len( typestr ) == 0:
[700]1762            typestr     = GMETRIC_DEFAULT_TYPE
[362]1763
[700]1764        (meta_msg, data_msg) = self.makexdr( name, value, typestr, units, self.slopestr, self.tmax, dmax )
[409]1765
[700]1766        meta_rt = self.socket.sendto( meta_msg, self.hostport )
1767        data_rt = self.socket.sendto( data_msg, self.hostport )
[362]1768
[700]1769        return ( meta_rt, data_rt )
[362]1770
[700]1771    def makexdr( self, name, value, typestr, unitstr, slopestr, tmax, dmax, group=None, spoof=None ):
1772
1773        hostname = "unset"
1774
[691]1775        if slopestr not in self.slope:
[362]1776
[691]1777            raise ValueError( "Slope must be one of: " + str( self.slope.keys() ) )
[362]1778
[691]1779        if typestr not in self.type:
[362]1780
[691]1781            raise ValueError( "Type must be one of: " + str( self.type ) )
[362]1782
[691]1783        if len( name ) == 0:
[362]1784
[691]1785            raise ValueError( "Name must be non-empty" )
[362]1786
[700]1787        self.meta_msg.reset()
1788        self.meta_msg.pack_int( 128 )
[362]1789
[700]1790        if not spoof:
1791            self.meta_msg.pack_string( hostname )
1792        else:
1793            self.meta_msg.pack_string( spoof )
[362]1794
[700]1795        self.meta_msg.pack_string( name )
1796
1797        if not spoof:
1798            self.meta_msg.pack_int( 0 )
1799        else:
1800            self.meta_msg.pack_int( 1 )
1801           
1802        self.meta_msg.pack_string( typestr )
1803        self.meta_msg.pack_string( name )
1804        self.meta_msg.pack_string( unitstr )
1805        self.meta_msg.pack_int( self.slope[ slopestr ] )
1806        self.meta_msg.pack_uint( int( tmax ) )
1807        self.meta_msg.pack_uint( int( dmax ) )
1808
1809        if not group:
1810            self.meta_msg.pack_int( 0 )
1811        else:
1812            self.meta_msg.pack_int( 1 )
1813            self.meta_msg.pack_string( "GROUP" )
1814            self.meta_msg.pack_string( group )
1815
1816        self.data_msg.reset()
1817        self.data_msg.pack_int( 128+5 )
1818
1819        if not spoof:
1820            self.data_msg.pack_string( hostname )
1821        else:
1822            self.data_msg.pack_string( spoof )
1823
1824        self.data_msg.pack_string( name )
1825
1826        if not spoof:
1827            self.data_msg.pack_int( 0 )
1828        else:
1829            self.data_msg.pack_int( 1 )
1830
1831        self.data_msg.pack_string( "%s" )
1832        self.data_msg.pack_string( str( value ) )
1833
1834        return ( self.meta_msg.get_buffer(), self.data_msg.get_buffer() )
1835
[26]1836def printTime( ):
[354]1837
[691]1838    """Print current time/date in human readable format for log/debug"""
[26]1839
[691]1840    return time.strftime("%a, %d %b %Y %H:%M:%S")
[26]1841
1842def debug_msg( level, msg ):
[354]1843
[691]1844    """Print msg if at or above current debug level"""
[26]1845
[691]1846    global DAEMONIZE, DEBUG_LEVEL, SYSLOG_LEVEL
[377]1847
[691]1848    if (not DAEMONIZE and DEBUG_LEVEL >= level):
1849        sys.stderr.write( msg + '\n' )
[26]1850
[691]1851    if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
1852        syslog.syslog( msg )
[373]1853
[307]1854def write_pidfile():
1855
[691]1856    # Write pidfile if PIDFILE is set
1857    #
1858    if PIDFILE:
[307]1859
[691]1860        pid    = os.getpid()
[354]1861
[691]1862        pidfile    = open( PIDFILE, 'w' )
[354]1863
[691]1864        pidfile.write( str( pid ) )
1865        pidfile.close()
[307]1866
[23]1867def main():
[354]1868
[691]1869    """Application start"""
[23]1870
[691]1871    global PBSQuery, PBSError, lsfObject
1872    global SYSLOG_FACILITY, USE_SYSLOG, BATCH_API, DAEMONIZE
[256]1873
[691]1874    if not processArgs( sys.argv[1:] ):
[354]1875
[691]1876        sys.exit( 1 )
[212]1877
[691]1878    # Load appropriate DataGatherer depending on which BATCH_API is set
1879    # and any required modules for the Gatherer
1880    #
1881    if BATCH_API == 'pbs':
[256]1882
[691]1883        try:
1884            from PBSQuery import PBSQuery, PBSError
[256]1885
[691]1886        except ImportError:
[256]1887
[691]1888            debug_msg( 0, "FATAL ERROR: BATCH_API set to 'pbs' but python module 'pbs_python' is not installed" )
1889            sys.exit( 1 )
[256]1890
[691]1891        gather = PbsDataGatherer()
[256]1892
[691]1893    elif BATCH_API == 'sge':
[256]1894
[691]1895        # Tested with SGE 6.0u11.
1896        #
1897        gather = SgeDataGatherer()
[368]1898
[691]1899    elif BATCH_API == 'lsf':
[368]1900
[691]1901        try:
1902            from lsfObject import lsfObject
1903        except:
1904            debug_msg(0, "fatal error: BATCH_API set to 'lsf' but python module is not found or installed")
1905            sys.exit( 1)
[256]1906
[691]1907        gather = LsfDataGatherer()
[524]1908
[691]1909    else:
1910        debug_msg( 0, "FATAL ERROR: unknown BATCH_API '" + BATCH_API + "' is not supported" )
[354]1911
[691]1912        sys.exit( 1 )
[256]1913
[691]1914    if( DAEMONIZE and USE_SYSLOG ):
[373]1915
[691]1916        syslog.openlog( 'jobmond', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
[373]1917
[691]1918    if DAEMONIZE:
[354]1919
[691]1920        gather.daemon()
1921    else:
1922        gather.run()
[23]1923
[256]1924# wh00t? someone started me! :)
[65]1925#
[23]1926if __name__ == '__main__':
[691]1927    main()
Note: See TracBrowser for help on using the repository browser.