source: trunk/jobmond/jobmond.py @ 353

Last change on this file since 353 was 353, checked in by bastiaans, 17 years ago

jobmond/jobmond.conf:

  • added GMETRIC_TARGET

jobmond/gmetric.py:

  • checkin of native python gmetric support, thanks to Nick Galbreath

jobmond/jobmond.py:

  • added handling of GMETRIC_TARGET
  • GMOND_CONF is now deprecated (GMETRIC_TARGET should be used) but we are still backwards compatible
  • Property svn:keywords set to Id
File size: 19.7 KB
RevLine 
[23]1#!/usr/bin/env python
[225]2#
3# This file is part of Jobmonarch
4#
5# Copyright (C) 2006  Ramon Bastiaans
6#
7# Jobmonarch is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# Jobmonarch is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20#
[228]21# SVN $Id: jobmond.py 353 2007-05-03 10:13:52Z bastiaans $
[227]22#
[23]23
[212]24import sys, getopt, ConfigParser
[26]25
[318]26import xml, xml.sax
27from xml.sax import saxutils, make_parser
28from xml.sax import make_parser
29from xml.sax.handler import feature_namespaces
30
[307]31def usage():
32
33        print
34        print 'usage: jobmond [options]'
35        print 'options:'
36        print '      --config, -c      configuration file'
37        print '      --pidfile, -p     pid file'
38        print '      --help, -h        help'
39        print
40
41
[212]42def processArgs( args ):
[26]43
[212]44        SHORT_L = 'c:'
45        LONG_L = 'config='
[165]46
[307]47        global PIDFILE
48        PIDFILE = None
49        config_filename = '/etc/jobmond.conf'
[61]50
[212]51        try:
[68]52
[212]53                opts, args = getopt.getopt( args, SHORT_L, LONG_L )
[185]54
[307]55        except getopt.GetoptError, detail:
[212]56
57                print detail
[307]58                usage()
[212]59                sys.exit(1)
60
61        for opt, value in opts:
62
63                if opt in [ '--config', '-c' ]:
64               
65                        config_filename = value
66
[307]67                if opt in [ '--pidfile', '-p' ]:
[212]68
[307]69                        PIDFILE = value
70               
71                if opt in [ '--help', '-h' ]:
72 
73                        usage()
74                        sys.exit(1)
[212]75
76        return loadConfig( config_filename )
77
78def loadConfig( filename ):
79
[215]80        def getlist( cfg_string ):
81
82                my_list = [ ]
83
84                for item_txt in cfg_string.split( ',' ):
85
86                        sep_char = None
87
88                        item_txt = item_txt.strip()
89
90                        for s_char in [ "'", '"' ]:
91
92                                if item_txt.find( s_char ) != -1:
93
94                                        if item_txt.count( s_char ) != 2:
95
96                                                print 'Missing quote: %s' %item_txt
97                                                sys.exit( 1 )
98
99                                        else:
100
101                                                sep_char = s_char
102                                                break
103
104                        if sep_char:
105
106                                item_txt = item_txt.split( sep_char )[1]
107
108                        my_list.append( item_txt )
109
110                return my_list
111
[212]112        cfg = ConfigParser.ConfigParser()
113
114        cfg.read( filename )
115
[353]116        global DEBUG_LEVEL, DAEMONIZE, BATCH_SERVER, BATCH_POLL_INTERVAL, GMOND_CONF, DETECT_TIME_DIFFS, BATCH_HOST_TRANSLATE, BATCH_API, QUEUE, GMETRIC_TARGET
[212]117
118        DEBUG_LEVEL = cfg.getint( 'DEFAULT', 'DEBUG_LEVEL' )
119
120        DAEMONIZE = cfg.getboolean( 'DEFAULT', 'DAEMONIZE' )
121
[265]122        try:
[212]123
[265]124                BATCH_SERVER = cfg.get( 'DEFAULT', 'BATCH_SERVER' )
[212]125
[265]126        except ConfigParser.NoOptionError:
127
128                # Backwards compatibility for old configs
129                #
130
131                BATCH_SERVER = cfg.get( 'DEFAULT', 'TORQUE_SERVER' )
[266]132                api_guess = 'pbs'
[265]133       
134        try:
135       
136                BATCH_POLL_INTERVAL = cfg.getint( 'DEFAULT', 'BATCH_POLL_INTERVAL' )
137
138        except ConfigParser.NoOptionError:
139
140                # Backwards compatibility for old configs
141                #
142
143                BATCH_POLL_INTERVAL = cfg.getint( 'DEFAULT', 'TORQUE_POLL_INTERVAL' )
[266]144                api_guess = 'pbs'
[353]145       
146        try:
[212]147
[353]148                GMOND_CONF = cfg.get( 'DEFAULT', 'GMOND_CONF' )
149
150        except ConfigParser.NoOptionError:
151
152                GMOND_CONF = None
153
[212]154        DETECT_TIME_DIFFS = cfg.getboolean( 'DEFAULT', 'DETECT_TIME_DIFFS' )
155
[215]156        BATCH_HOST_TRANSLATE = getlist( cfg.get( 'DEFAULT', 'BATCH_HOST_TRANSLATE' ) )
157
[266]158        try:
[256]159
[266]160                BATCH_API = cfg.get( 'DEFAULT', 'BATCH_API' )
161
162        except ConfigParser.NoOptionError, detail:
163
164                if BATCH_SERVER and api_guess:
165                        BATCH_API = api_guess
166                else:
167                        debug_msg( 0, "fatal error: BATCH_API not set and can't make guess" )
168                        sys.exit( 1 )
[317]169
170        try:
171
[318]172                QUEUE = getlist( cfg.get( 'DEFAULT', 'QUEUE' ) )
[317]173
174        except ConfigParser.NoOptionError, detail:
175
176                QUEUE = None
[353]177
178        try:
179
180                GMETRIC_TARGET = cfg.get( 'DEFAULT', 'GMETRIC_TARGET' )
181
182        except ConfigParser.NoOptionError:
183
184                GMETRIC_TARGET = None
185
186                if not GMOND_CONF:
187
188                        debug_msg( 0, "fatal error: GMETRIC_TARGET or GMOND_CONF both not set!" )
189                        sys.exit( 1 )
190                else:
191
192                        debug_msg( 0, "error: GMETRIC_TARGET not set: internel Gmetric handling aborted. Failing back to DEPRECATED use of gmond.conf/gmetric binary. This will slow down jobmond significantly!" )
193
[212]194        return True
195
[23]196
[215]197import time, os, socket, string, re
[212]198
[253]199METRIC_MAX_VAL_LEN = 900
200
[61]201class DataProcessor:
[68]202        """Class for processing of data"""
[61]203
204        binary = '/usr/bin/gmetric'
205
206        def __init__( self, binary=None ):
[68]207                """Remember alternate binary location if supplied"""
[61]208
209                if binary:
210                        self.binary = binary
211
[80]212                # Timeout for XML
213                #
214                # From ganglia's documentation:
215                #
216                # 'A metric will be deleted DMAX seconds after it is received, and
217                # DMAX=0 means eternal life.'
[61]218
[256]219                self.dmax = str( int( int( BATCH_POLL_INTERVAL ) * 2 ) )
[80]220
[353]221                if GMOND_CONF:
222                        try:
223                                gmond_file = GMOND_CONF
[68]224
[353]225                        except NameError:
226                                gmond_file = '/etc/gmond.conf'
[68]227
[353]228                        if not os.path.exists( gmond_file ):
229                                debug_msg( 0, 'fatal error: ' + gmond_file + ' does not exist' )
230                                sys.exit( 1 )
[68]231
[353]232                        incompatible = self.checkGmetricVersion()
[61]233
[353]234                        if incompatible:
235                                debug_msg( 0, 'Gmetric version not compatible, pls upgrade to at least 3.0.1' )
236                                sys.exit( 1 )
[65]237
238        def checkGmetricVersion( self ):
[68]239                """
240                Check version of gmetric is at least 3.0.1
241                for the syntax we use
242                """
[65]243
[255]244                global METRIC_MAX_VAL_LEN
245
[341]246                incompatible    = 0
247
[65]248                for line in os.popen( self.binary + ' --version' ).readlines():
249
250                        line = line.split( ' ' )
251
[69]252                        if len( line ) == 2 and str(line).find( 'gmetric' ) != -1:
[65]253                       
[69]254                                gmetric_version = line[1].split( '\n' )[0]
[65]255
[69]256                                version_major = int( gmetric_version.split( '.' )[0] )
257                                version_minor = int( gmetric_version.split( '.' )[1] )
258                                version_patch = int( gmetric_version.split( '.' )[2] )
[65]259
260                                incompatible = 0
261
262                                if version_major < 3:
263
264                                        incompatible = 1
265                               
266                                elif version_major == 3:
267
268                                        if version_minor == 0:
269
270                                                if version_patch < 1:
271                                               
[91]272                                                        incompatible = 1
[65]273
[255]274                                                if version_patch < 3:
275
276                                                        METRIC_MAX_VAL_LEN = 900
277
278                                                elif version_patch >= 3:
279
280                                                        METRIC_MAX_VAL_LEN = 1400
281
[65]282                return incompatible
283
[75]284        def multicastGmetric( self, metricname, metricval, valtype='string' ):
[68]285                """Call gmetric binary and multicast"""
[65]286
287                cmd = self.binary
288
[353]289                if GMETRIC_TARGET:
[61]290
[353]291                        from gmetric import Gmetric
[61]292
[353]293                if GMETRIC_TARGET:
[61]294
[353]295                        GMETRIC_TARGET_HOST     = GMETRIC_TARGET.split( ':' )[0]
296                        GMETRIC_TARGET_PORT     = GMETRIC_TARGET.split( ':' )[1]
297
298                        metric_debug            = "[gmetric] name: %s - val: %s - dmax: %s" %( str( metricname ), str( metricval ), str( self.dmax ) )
299
300                        debug_msg( 10, printTime() + ' ' + metric_debug)
301
302                        gm = Gmetric( GMETRIC_TARGET_HOST, GMETRIC_TARGET_PORT )
303
304                        gm.send( str( metricname ), str( metricval ), str( self.dmax ) )
305
306                else:
307                        try:
308                                cmd = cmd + ' -c' + GMOND_CONF
309
310                        except NameError:
311
312                                debug_msg( 10, 'Assuming /etc/gmond.conf for gmetric cmd (ommitting)' )
313
314                        cmd = cmd + ' -n' + str( metricname )+ ' -v"' + str( metricval )+ '" -t' + str( valtype ) + ' -d' + str( self.dmax )
315
316                        debug_msg( 10, printTime() + ' ' + cmd )
317
318                        os.system( cmd )
319
[318]320class DataGatherer:
[23]321
[318]322        """Skeleton class for batch system DataGatherer"""
[256]323
[318]324        def printJobs( self, jobs ):
325                """Print a jobinfo overview"""
326
327                for name, attrs in self.jobs.items():
328
329                        print 'job %s' %(name)
330
331                        for name, val in attrs.items():
332
333                                print '\t%s = %s' %( name, val )
334
335        def printJob( self, jobs, job_id ):
336                """Print job with job_id from jobs"""
337
338                print 'job %s' %(job_id)
339
340                for name, val in jobs[ job_id ].items():
341
342                        print '\t%s = %s' %( name, val )
343
[256]344        def daemon( self ):
[318]345                """Run as daemon forever"""
[256]346
[318]347                # Fork the first child
348                #
349                pid = os.fork()
350                if pid > 0:
351                        sys.exit(0)  # end parent
[256]352
[318]353                # creates a session and sets the process group ID
354                #
355                os.setsid()
356
357                # Fork the second child
358                #
359                pid = os.fork()
360                if pid > 0:
361                        sys.exit(0)  # end parent
362
363                write_pidfile()
364
365                # Go to the root directory and set the umask
366                #
367                os.chdir('/')
368                os.umask(0)
369
370                sys.stdin.close()
371                sys.stdout.close()
372                sys.stderr.close()
373
374                os.open('/dev/null', os.O_RDWR)
375                os.dup2(0, 1)
376                os.dup2(0, 2)
377
378                self.run()
379
[256]380        def run( self ):
[318]381                """Main thread"""
[256]382
[318]383                while ( 1 ):
384               
[348]385                        self.getJobData()
386                        self.submitJobData()
[318]387                        time.sleep( BATCH_POLL_INTERVAL )       
[256]388
[318]389class SgeQstatXMLParser(xml.sax.handler.ContentHandler):
[256]390
[318]391        """Babu Sundaram's experimental SGE qstat XML parser"""
[256]392
[318]393        def __init__(self, qstatinxml):
394
395                self.qstatfile = qstatinxml
396                self.attribs = {}
397                self.value = ''
398                self.jobID = ''
399                self.currentJobInfo = ''
400                self.job_list = []
401                self.EOFFlag = 0
402                self.jobinfoCount = 0
403
404
405        def startElement(self, name, attrs):
406
407                if name == 'job_list':
408                        self.currentJobInfo = 'Status=' + attrs.get('state', None) + ' '
409                elif name == 'job_info':
410                        self.job_list = []
411                        self.jobinfoCount += 1
412
413        def characters(self, ch):
414
415                self.value = self.value + ch
416
417        def endElement(self, name):
418
419                if len(self.value.strip()) > 0 :
420
421                        self.currentJobInfo += name + '=' + self.value.strip() + ' '         
422                elif name != 'job_list':
423
424                        self.currentJobInfo += name + '=Unknown '
425
426                if name == 'JB_job_number':
427
428                        self.jobID = self.value.strip()
429                        self.job_list.append(self.jobID)         
430
431                if name == 'job_list':
432
433                        if self.attribs.has_key(self.jobID) == False:
434                                self.attribs[self.jobID] = self.currentJobInfo
435                        elif self.attribs.has_key(self.jobID) and self.attribs[self.jobID] != self.currentJobInfo:
436                                self.attribs[self.jobID] = self.currentJobInfo
437                        self.currentJobInfo = ''
438                        self.jobID = ''
439
440                elif name == 'job_info' and self.jobinfoCount == 2:
441
442                        deljobs = []
443                        for id in self.attribs:
444                                try:
445                                        self.job_list.index(str(id))
446                                except ValueError:
447                                        deljobs.append(id)
448                        for i in deljobs:
449                                del self.attribs[i]
450                        deljobs = []
451                        self.jobinfoCount = 0
452
453                self.value = ''
454
455class SgeDataGatherer(DataGatherer):
456
[61]457        jobs = { }
[347]458        SGE_QSTAT_XML_FILE      = '/tmp/.jobmonarch.sge.qstat'
[61]459
[318]460        def __init__( self ):
461                """Setup appropriate variables"""
462
463                self.jobs = { }
464                self.timeoffset = 0
465                self.dp = DataProcessor()
466                self.initSgeJobInfo()
467
468        def initSgeJobInfo( self ):
469                """This is outside the scope of DRMAA; Get the current jobs in SGE"""
470                """This is a hack because we cant get info about jobs beyond"""
471                """those in the current DRMAA session"""
472
[347]473                self.qstatparser = SgeQstatXMLParser( self.SGE_QSTAT_XML_FILE )
[318]474
475                # Obtain the qstat information from SGE in XML format
476                # This would change to DRMAA-specific calls from 6.0u9
477
478        def getJobData(self):
479                """Gather all data on current jobs in SGE"""
480
481                # Get the information about the current jobs in the SGE queue
482                info = os.popen("qstat -ext -xml").readlines()
[347]483                f = open(self.SGE_QSTAT_XML_FILE,'w')
[318]484                for lines in info:
485                        f.write(lines)
486                f.close()
487
488                # Parse the input
489                f = open(self.qstatparser.qstatfile, 'r')
490                xml.sax.parse(f, self.qstatparser)
491                f.close()
492
493                self.cur_time = time.time()
494
495                return self.qstatparser.attribs
496
497        def submitJobData(self):
498                """Submit job info list"""
499
500                self.dp.multicastGmetric( 'MONARCH-HEARTBEAT', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
501                # Now let's spread the knowledge
502                #
503                metric_increment = 0
504                for jobid, jobattrs in self.qstatparser.attribs.items():
505
506                        self.dp.multicastGmetric( 'MONARCH-JOB-' + jobid + '-' + str(metric_increment), jobattrs)
507
508class PbsDataGatherer(DataGatherer):
509
510        """This is the DataGatherer for PBS and Torque"""
511
[256]512        global PBSQuery
513
[23]514        def __init__( self ):
[68]515                """Setup appropriate variables"""
[23]516
[26]517                self.jobs = { }
[185]518                self.timeoffset = 0
[61]519                self.dp = DataProcessor()
[91]520                self.initPbsQuery()
[23]521
[91]522        def initPbsQuery( self ):
523
524                self.pq = None
[256]525                if( BATCH_SERVER ):
526                        self.pq = PBSQuery( BATCH_SERVER )
[174]527                else:
[165]528                        self.pq = PBSQuery()
[91]529
[26]530        def getAttr( self, attrs, name ):
[68]531                """Return certain attribute from dictionary, if exists"""
[26]532
533                if attrs.has_key( name ):
534                        return attrs[name]
535                else:
536                        return ''
537
538        def jobDataChanged( self, jobs, job_id, attrs ):
[68]539                """Check if job with attrs and job_id in jobs has changed"""
[26]540
541                if jobs.has_key( job_id ):
542                        oldData = jobs[ job_id ]       
543                else:
544                        return 1
545
546                for name, val in attrs.items():
547
548                        if oldData.has_key( name ):
549
550                                if oldData[ name ] != attrs[ name ]:
551
552                                        return 1
553
554                        else:
555                                return 1
556
557                return 0
558
[348]559        def getJobData( self ):
[68]560                """Gather all data on current jobs in Torque"""
[26]561
[101]562                #self.initPbsQuery()
[125]563       
564                #print self.pq.getnodes()
565       
[282]566                joblist = {}
[349]567
[282]568                while len(joblist) == 0:
569                        try:
570                                joblist = self.pq.getjobs()
[349]571                        except PBSError, detail:
572                                debug_msg( 10, "Caught PBS unavaible, skipping until next polling interval: " + str( detail ) )
573                                return None
[26]574
[69]575                self.cur_time = time.time()
[68]576
[26]577                jobs_processed = [ ]
578
[125]579                #self.printJobs( joblist )
580
[26]581                for name, attrs in joblist.items():
582
583                        job_id = name.split( '.' )[0]
584
585                        jobs_processed.append( job_id )
[61]586
[26]587                        name = self.getAttr( attrs, 'Job_Name' )
588                        queue = self.getAttr( attrs, 'queue' )
[317]589
590                        if QUEUE:
591
592                                if QUEUE != queue:
593
594                                        continue
595
[26]596                        owner = self.getAttr( attrs, 'Job_Owner' ).split( '@' )[0]
597                        requested_time = self.getAttr( attrs, 'Resource_List.walltime' )
598                        requested_memory = self.getAttr( attrs, 'Resource_List.mem' )
[95]599
[26]600                        mynoderequest = self.getAttr( attrs, 'Resource_List.nodes' )
[95]601
[281]602                        ppn = ''
603
[26]604                        if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
[95]605
[281]606                                mynoderequest_fields = mynoderequest.split( ':' )
607
608                                for mynoderequest_field in mynoderequest_fields:
609
610                                        if mynoderequest_field.find( 'ppn' ) != -1:
611
612                                                ppn = mynoderequest_field.split( 'ppn=' )[1]
613
[26]614                        status = self.getAttr( attrs, 'job_state' )
[25]615
[243]616                        queued_timestamp = self.getAttr( attrs, 'ctime' )
617
[95]618                        if status == 'R':
619                                start_timestamp = self.getAttr( attrs, 'mtime' )
620                                nodes = self.getAttr( attrs, 'exec_host' ).split( '+' )
[133]621
622                                nodeslist = [ ]
623
624                                for node in nodes:
625                                        host = node.split( '/' )[0]
626
627                                        if nodeslist.count( host ) == 0:
[215]628
629                                                for translate_pattern in BATCH_HOST_TRANSLATE:
630
[220]631                                                        if translate_pattern.find( '/' ) != -1:
[215]632
[220]633                                                                translate_orig = translate_pattern.split( '/' )[1]
634                                                                translate_new = translate_pattern.split( '/' )[2]
635
636                                                                host = re.sub( translate_orig, translate_new, host )
[216]637                               
[217]638                                                if not host in nodeslist:
[216]639                               
640                                                        nodeslist.append( host )
[133]641
[185]642                                if DETECT_TIME_DIFFS:
643
644                                        # If a job start if later than our current date,
645                                        # that must mean the Torque server's time is later
646                                        # than our local time.
647                               
648                                        if int(start_timestamp) > int( int(self.cur_time) + int(self.timeoffset) ):
649
650                                                self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
651
[133]652                        elif status == 'Q':
[95]653                                start_timestamp = ''
[133]654                                count_mynodes = 0
655                                numeric_node = 1
[95]656
[133]657                                for node in mynoderequest.split( '+' ):
[67]658
[133]659                                        nodepart = node.split( ':' )[0]
[67]660
[133]661                                        for letter in nodepart:
[67]662
[133]663                                                if letter not in string.digits:
664
665                                                        numeric_node = 0
666
667                                        if not numeric_node:
668                                                count_mynodes = count_mynodes + 1
669                                        else:
[327]670                                                try:
671                                                        count_mynodes = count_mynodes + int( nodepart )
672                                                except ValueError, detail:
673                                                        debug_msg( 10, str( detail ) )
674                                                        debug_msg( 10, "Encountered weird node in Resources_List?!" )
675                                                        debug_msg( 10, 'nodepart = ' + str( nodepart ) )
676                                                        debug_msg( 10, 'job = ' + str( name ) )
677                                                        debug_msg( 10, 'attrs = ' + str( attrs ) )
[133]678                                               
[254]679                                nodeslist = str( count_mynodes )
[172]680                        else:
681                                start_timestamp = ''
[173]682                                nodeslist = ''
[133]683
[26]684                        myAttrs = { }
[253]685                        myAttrs['name'] = str( name )
686                        myAttrs['queue'] = str( queue )
687                        myAttrs['owner'] = str( owner )
688                        myAttrs['requested_time'] = str( requested_time )
689                        myAttrs['requested_memory'] = str( requested_memory )
690                        myAttrs['ppn'] = str( ppn )
691                        myAttrs['status'] = str( status )
692                        myAttrs['start_timestamp'] = str( start_timestamp )
693                        myAttrs['queued_timestamp'] = str( queued_timestamp )
[185]694                        myAttrs['reported'] = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
[67]695                        myAttrs['nodes'] = nodeslist
696                        myAttrs['domain'] = string.join( socket.getfqdn().split( '.' )[1:], '.' )
[256]697                        myAttrs['poll_interval'] = str( BATCH_POLL_INTERVAL )
[26]698
[348]699                        if self.jobDataChanged( self.jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
700                                self.jobs[ job_id ] = myAttrs
[61]701
[101]702                                #debug_msg( 10, printTime() + ' job %s state changed' %(job_id) )
[26]703
[348]704                for id, attrs in self.jobs.items():
[76]705
706                        if id not in jobs_processed:
707
708                                # This one isn't there anymore; toedeledoki!
709                                #
[348]710                                del self.jobs[ id ]
[76]711
[348]712        def submitJobData( self ):
[65]713                """Submit job info list"""
714
[219]715                self.dp.multicastGmetric( 'MONARCH-HEARTBEAT', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
[69]716
[61]717                # Now let's spread the knowledge
718                #
[348]719                for jobid, jobattrs in self.jobs.items():
[61]720
[95]721                        gmetric_val = self.compileGmetricVal( jobid, jobattrs )
[61]722
[253]723                        metric_increment = 0
724
[95]725                        for val in gmetric_val:
[253]726                                self.dp.multicastGmetric( 'MONARCH-JOB-' + jobid + '-' + str(metric_increment), val )
727                                metric_increment = metric_increment + 1
[61]728
[253]729        def compileGmetricVal( self, jobid, jobattrs ):
730                """Create a val string for gmetric of jobinfo"""
[67]731
[253]732                gval_lists = [ ]
[67]733
[253]734                mystr = None
[67]735
[253]736                val_list = { }
[67]737
[253]738                for val_name, val_value in jobattrs.items():
[61]739
[253]740                        val_list_names_len      = len( string.join( val_list.keys() ) ) + len(val_list.keys())
741                        val_list_vals_len       = len( string.join( val_list.values() ) ) + len(val_list.values())
[95]742
[254]743                        if val_name == 'nodes' and jobattrs['status'] == 'R':
[95]744
[253]745                                node_str = None
[95]746
[253]747                                for node in val_value:
[65]748
[253]749                                        if node_str:
750                                                node_str = node_str + ';' + node
751                                        else:
752                                                node_str = node
[65]753
[253]754                                        if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(node_str) ) > METRIC_MAX_VAL_LEN:
[65]755
[253]756                                                val_list[ val_name ] = node_str
757                                                gval_lists.append( val_list )
758                                                val_list = { }
759                                                node_str = None
[65]760
[253]761                                val_list[ val_name ] = node_str
762                                gval_lists.append( val_list )
763                                val_list = { }
[65]764
[254]765                        elif val_value != '':
766
767                                if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(str(val_value)) ) > METRIC_MAX_VAL_LEN:
768
769                                        gval_lists.append( val_list )
770                                        val_list = { }
771
772                                val_list[ val_name ] = val_value
773
774                if len(val_list) > 0:
775                        gval_lists.append( val_list )
776
[253]777                str_list = [ ]
[65]778
[253]779                for val_list in gval_lists:
[65]780
[253]781                        my_val_str = None
[65]782
[253]783                        for val_name, val_value in val_list.items():
[65]784
[253]785                                if my_val_str:
[65]786
[253]787                                        my_val_str = my_val_str + ' ' + val_name + '=' + val_value
788                                else:
789                                        my_val_str = val_name + '=' + val_value
790
791                        str_list.append( my_val_str )
792
793                return str_list
794
[26]795def printTime( ):
[65]796        """Print current time/date in human readable format for log/debug"""
[26]797
798        return time.strftime("%a, %d %b %Y %H:%M:%S")
799
800def debug_msg( level, msg ):
[65]801        """Print msg if at or above current debug level"""
[26]802
803        if (DEBUG_LEVEL >= level):
804                        sys.stderr.write( msg + '\n' )
805
[307]806def write_pidfile():
807
808        # Write pidfile if PIDFILE exists
809        if PIDFILE:
810                pid = os.getpid()
811
812                pidfile = open(PIDFILE, 'w')
813                pidfile.write(str(pid))
814                pidfile.close()
815
[23]816def main():
[65]817        """Application start"""
[23]818
[352]819        global PBSQuery, PBSError
[256]820
[212]821        if not processArgs( sys.argv[1:] ):
822                sys.exit( 1 )
823
[256]824        if BATCH_API == 'pbs':
825
826                try:
[282]827                        from PBSQuery import PBSQuery, PBSError
[256]828
829                except ImportError:
830
831                        debug_msg( 0, "fatal error: BATCH_API set to 'pbs' but python module 'pbs_python' is not installed" )
832                        sys.exit( 1 )
833
834                gather = PbsDataGatherer()
835
836        elif BATCH_API == 'sge':
837
[347]838                gather = SgeDataGatherer()
[256]839
840        else:
841                debug_msg( 0, "fatal error: unknown BATCH_API '" + BATCH_API + "' is not supported" )
842                sys.exit( 1 )
843
[26]844        if DAEMONIZE:
845                gather.daemon()
846        else:
847                gather.run()
[23]848
[256]849# wh00t? someone started me! :)
[65]850#
[23]851if __name__ == '__main__':
852        main()
Note: See TracBrowser for help on using the repository browser.