source: trunk/jobmond/jobmond.py @ 215

Last change on this file since 215 was 215, checked in by bastiaans, 18 years ago

jobmond/jobmond.conf:

  • added BATCH_HOST_TRANSLATE

jobmond/jobmond.py:

  • added translation of batch hostnames to ganglia hostnames
File size: 13.2 KB
RevLine 
[23]1#!/usr/bin/env python
2
[212]3import sys, getopt, ConfigParser
[26]4
[212]5def processArgs( args ):
[26]6
[212]7        SHORT_L = 'c:'
8        LONG_L = 'config='
[165]9
[212]10        config_filename = None
[61]11
[212]12        try:
[68]13
[212]14                opts, args = getopt.getopt( args, SHORT_L, LONG_L )
[185]15
[212]16        except getopt.error, detail:
17
18                print detail
19                sys.exit(1)
20
21        for opt, value in opts:
22
23                if opt in [ '--config', '-c' ]:
24               
25                        config_filename = value
26
27        if not config_filename:
28
29                config_filename = '/etc/jobmond.conf'
30
31        return loadConfig( config_filename )
32
33def loadConfig( filename ):
34
[215]35        def getlist( cfg_string ):
36
37                my_list = [ ]
38
39                for item_txt in cfg_string.split( ',' ):
40
41                        sep_char = None
42
43                        item_txt = item_txt.strip()
44
45                        for s_char in [ "'", '"' ]:
46
47                                if item_txt.find( s_char ) != -1:
48
49                                        if item_txt.count( s_char ) != 2:
50
51                                                print 'Missing quote: %s' %item_txt
52                                                sys.exit( 1 )
53
54                                        else:
55
56                                                sep_char = s_char
57                                                break
58
59                        if sep_char:
60
61                                item_txt = item_txt.split( sep_char )[1]
62
63                        my_list.append( item_txt )
64
65                return my_list
66
[212]67        cfg = ConfigParser.ConfigParser()
68
69        cfg.read( filename )
70
[215]71        global DEBUG_LEVEL, DAEMONIZE, TORQUE_SERVER, TORQUE_POLL_INTERVAL, GMOND_CONF, DETECT_TIME_DIFFS, BATCH_HOST_TRANSLATE
[212]72
73        # Specify debugging level here;
74        #
75        # 10 = gemtric cmd's
76        DEBUG_LEVEL = cfg.getint( 'DEFAULT', 'DEBUG_LEVEL' )
77
78        # Wether or not to run as a daemon in background
79        #
80        DAEMONIZE = cfg.getboolean( 'DEFAULT', 'DAEMONIZE' )
81
82        # Which Torque server to monitor
83        #
84        TORQUE_SERVER = cfg.get( 'DEFAULT', 'TORQUE_SERVER' )
85
86        # How many seconds interval for polling of jobs
87        #
88        # this will effect directly how accurate the
89        # end time of a job can be determined
90        #
91        TORQUE_POLL_INTERVAL = cfg.getint( 'DEFAULT', 'TORQUE_POLL_INTERVAL' )
92
93        # Alternate location of gmond.conf
94        #
95        # Default: /etc/gmond.conf
96        #
97        GMOND_CONF = cfg.get( 'DEFAULT', 'GMOND_CONF' )
98
99        # Wether or not to detect differences in
100        # time from Torque server and local time.
101        #
102        # Ideally both machines (if not the same)
103        # should have the same time (via ntp or whatever)
104        #
105        DETECT_TIME_DIFFS = cfg.getboolean( 'DEFAULT', 'DETECT_TIME_DIFFS' )
106
[215]107        # Regexp style hostname translation
108        #
109        # Usefull if your Torque hostnames are not the same as your
110        # Ganglia hostnames (different network interfaces)
111        #
112        # Syntax: /orig/new/
113        #
114        BATCH_HOST_TRANSLATE = getlist( cfg.get( 'DEFAULT', 'BATCH_HOST_TRANSLATE' ) )
115
[212]116        return True
117
[23]118from PBSQuery import PBSQuery
119
[215]120import time, os, socket, string, re
[212]121
[61]122class DataProcessor:
[68]123        """Class for processing of data"""
[61]124
125        binary = '/usr/bin/gmetric'
126
127        def __init__( self, binary=None ):
[68]128                """Remember alternate binary location if supplied"""
[61]129
130                if binary:
131                        self.binary = binary
132
[80]133                # Timeout for XML
134                #
135                # From ganglia's documentation:
136                #
137                # 'A metric will be deleted DMAX seconds after it is received, and
138                # DMAX=0 means eternal life.'
[61]139
[194]140                self.dmax = str( int( int( TORQUE_POLL_INTERVAL ) + 2 ) )
[80]141
[68]142                try:
143                        gmond_file = GMOND_CONF
144
145                except NameError:
146                        gmond_file = '/etc/gmond.conf'
147
148                if not os.path.exists( gmond_file ):
149                        debug_msg( 0, gmond_file + ' does not exist' )
150                        sys.exit( 1 )
151
[69]152                incompatible = self.checkGmetricVersion()
[61]153
[65]154                if incompatible:
155                        debug_msg( 0, 'Gmetric version not compatible, pls upgrade to at least 3.0.1' )
156                        sys.exit( 1 )
157
158        def checkGmetricVersion( self ):
[68]159                """
160                Check version of gmetric is at least 3.0.1
161                for the syntax we use
162                """
[65]163
164                for line in os.popen( self.binary + ' --version' ).readlines():
165
166                        line = line.split( ' ' )
167
[69]168                        if len( line ) == 2 and str(line).find( 'gmetric' ) != -1:
[65]169                       
[69]170                                gmetric_version = line[1].split( '\n' )[0]
[65]171
[69]172                                version_major = int( gmetric_version.split( '.' )[0] )
173                                version_minor = int( gmetric_version.split( '.' )[1] )
174                                version_patch = int( gmetric_version.split( '.' )[2] )
[65]175
176                                incompatible = 0
177
178                                if version_major < 3:
179
180                                        incompatible = 1
181                               
182                                elif version_major == 3:
183
184                                        if version_minor == 0:
185
186                                                if version_patch < 1:
187                                               
[91]188                                                        incompatible = 1
[65]189
190                return incompatible
191
[75]192        def multicastGmetric( self, metricname, metricval, valtype='string' ):
[68]193                """Call gmetric binary and multicast"""
[65]194
195                cmd = self.binary
196
[61]197                try:
198                        cmd = cmd + ' -c' + GMOND_CONF
199                except NameError:
[64]200                        debug_msg( 10, 'Assuming /etc/gmond.conf for gmetric cmd (ommitting)' )
[61]201
[168]202                cmd = cmd + ' -n' + str( metricname )+ ' -v"' + str( metricval )+ '" -t' + str( valtype ) + ' -d' + str( self.dmax )
[61]203
[101]204                debug_msg( 10, printTime() + ' ' + cmd )
[69]205                os.system( cmd )
[61]206
[174]207class DataGatherer:
[23]208
[61]209        jobs = { }
210
[23]211        def __init__( self ):
[68]212                """Setup appropriate variables"""
[23]213
[26]214                self.jobs = { }
[185]215                self.timeoffset = 0
[61]216                self.dp = DataProcessor()
[91]217                self.initPbsQuery()
[23]218
[91]219        def initPbsQuery( self ):
220
221                self.pq = None
[165]222                if( TORQUE_SERVER ):
223                        self.pq = PBSQuery( TORQUE_SERVER )
[174]224                else:
[165]225                        self.pq = PBSQuery()
[91]226
[26]227        def getAttr( self, attrs, name ):
[68]228                """Return certain attribute from dictionary, if exists"""
[26]229
230                if attrs.has_key( name ):
231                        return attrs[name]
232                else:
233                        return ''
234
235        def jobDataChanged( self, jobs, job_id, attrs ):
[68]236                """Check if job with attrs and job_id in jobs has changed"""
[26]237
238                if jobs.has_key( job_id ):
239                        oldData = jobs[ job_id ]       
240                else:
241                        return 1
242
243                for name, val in attrs.items():
244
245                        if oldData.has_key( name ):
246
247                                if oldData[ name ] != attrs[ name ]:
248
249                                        return 1
250
251                        else:
252                                return 1
253
254                return 0
255
[65]256        def getJobData( self, known_jobs ):
[68]257                """Gather all data on current jobs in Torque"""
[26]258
[65]259                if len( known_jobs ) > 0:
260                        jobs = known_jobs
261                else:
262                        jobs = { }
[26]263
[101]264                #self.initPbsQuery()
[125]265       
266                #print self.pq.getnodes()
267       
[26]268                joblist = self.pq.getjobs()
269
[69]270                self.cur_time = time.time()
[68]271
[26]272                jobs_processed = [ ]
273
[125]274                #self.printJobs( joblist )
275
[26]276                for name, attrs in joblist.items():
277
278                        job_id = name.split( '.' )[0]
279
280                        jobs_processed.append( job_id )
[61]281
[26]282                        name = self.getAttr( attrs, 'Job_Name' )
283                        queue = self.getAttr( attrs, 'queue' )
284                        owner = self.getAttr( attrs, 'Job_Owner' ).split( '@' )[0]
285                        requested_time = self.getAttr( attrs, 'Resource_List.walltime' )
286                        requested_memory = self.getAttr( attrs, 'Resource_List.mem' )
[95]287
[26]288                        mynoderequest = self.getAttr( attrs, 'Resource_List.nodes' )
[95]289
[26]290                        if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
291                                ppn = mynoderequest.split( ':' )[1].split( 'ppn=' )[1]
292                        else:
293                                ppn = ''
[95]294
[26]295                        status = self.getAttr( attrs, 'job_state' )
[25]296
[95]297                        if status == 'R':
298                                start_timestamp = self.getAttr( attrs, 'mtime' )
299                                nodes = self.getAttr( attrs, 'exec_host' ).split( '+' )
[133]300
301                                nodeslist = [ ]
302
303                                for node in nodes:
304                                        host = node.split( '/' )[0]
305
306                                        if nodeslist.count( host ) == 0:
[215]307
308                                                for translate_pattern in BATCH_HOST_TRANSLATE:
309
310                                                        translate_orig = translate_pattern.split( '/' )[1]
311                                                        translate_new = translate_pattern.split( '/' )[2]
312
313                                                        host = re.sub( translate_orig, translate_new, host )
314                                       
[133]315                                                nodeslist.append( host )
316
[185]317                                if DETECT_TIME_DIFFS:
318
319                                        # If a job start if later than our current date,
320                                        # that must mean the Torque server's time is later
321                                        # than our local time.
322                               
323                                        if int(start_timestamp) > int( int(self.cur_time) + int(self.timeoffset) ):
324
325                                                self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
326
[133]327                        elif status == 'Q':
[95]328                                start_timestamp = ''
[133]329                                count_mynodes = 0
330                                numeric_node = 1
[95]331
[133]332                                for node in mynoderequest.split( '+' ):
[67]333
[133]334                                        nodepart = node.split( ':' )[0]
[67]335
[133]336                                        for letter in nodepart:
[67]337
[133]338                                                if letter not in string.digits:
339
340                                                        numeric_node = 0
341
342                                        if not numeric_node:
343                                                count_mynodes = count_mynodes + 1
344                                        else:
345                                                count_mynodes = count_mynodes + int( nodepart )
346                                               
[134]347                                nodeslist = count_mynodes
[172]348                        else:
349                                start_timestamp = ''
[173]350                                nodeslist = ''
[133]351
[26]352                        myAttrs = { }
353                        myAttrs['name'] = name
354                        myAttrs['queue'] = queue
355                        myAttrs['owner'] = owner
356                        myAttrs['requested_time'] = requested_time
357                        myAttrs['requested_memory'] = requested_memory
358                        myAttrs['ppn'] = ppn
359                        myAttrs['status'] = status
360                        myAttrs['start_timestamp'] = start_timestamp
[185]361                        myAttrs['reported'] = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
[67]362                        myAttrs['nodes'] = nodeslist
363                        myAttrs['domain'] = string.join( socket.getfqdn().split( '.' )[1:], '.' )
[80]364                        myAttrs['poll_interval'] = TORQUE_POLL_INTERVAL
[26]365
[184]366                        if self.jobDataChanged( jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
[26]367                                jobs[ job_id ] = myAttrs
[61]368
[101]369                                #debug_msg( 10, printTime() + ' job %s state changed' %(job_id) )
[26]370
[76]371                for id, attrs in jobs.items():
372
373                        if id not in jobs_processed:
374
375                                # This one isn't there anymore; toedeledoki!
376                                #
377                                del jobs[ id ]
378
[65]379                return jobs
380
381        def submitJobData( self, jobs ):
382                """Submit job info list"""
383
[185]384                self.dp.multicastGmetric( 'TOGA-HEARTBEAT', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
[69]385
[61]386                # Now let's spread the knowledge
387                #
388                for jobid, jobattrs in jobs.items():
389
[95]390                        gmetric_val = self.compileGmetricVal( jobid, jobattrs )
[61]391
[95]392                        for val in gmetric_val:
393                                self.dp.multicastGmetric( 'TOGA-JOB-' + jobid, val )
[61]394
[67]395        def makeNodeString( self, nodelist ):
[68]396                """Make one big string of all hosts"""
[67]397
398                node_str = None
399
400                for node in nodelist:
401                        if not node_str:
402                                node_str = node
403                        else:
404                                node_str = node_str + ';' + node
405
406                return node_str
407
[65]408        def compileGmetricVal( self, jobid, jobattrs ):
409                """Create a val string for gmetric of jobinfo"""
[61]410
[80]411                appendList = [ ]
412                appendList.append( 'name=' + jobattrs['name'] )
413                appendList.append( 'queue=' + jobattrs['queue'] )
414                appendList.append( 'owner=' + jobattrs['owner'] )
415                appendList.append( 'requested_time=' + jobattrs['requested_time'] )
[95]416
417                if jobattrs['requested_memory'] != '':
418                        appendList.append( 'requested_memory=' + jobattrs['requested_memory'] )
419
420                if jobattrs['ppn'] != '':
421                        appendList.append( 'ppn=' + jobattrs['ppn'] )
422
[80]423                appendList.append( 'status=' + jobattrs['status'] )
[95]424
425                if jobattrs['start_timestamp'] != '':
426                        appendList.append( 'start_timestamp=' + jobattrs['start_timestamp'] )
427
[80]428                appendList.append( 'reported=' + jobattrs['reported'] )
[85]429                appendList.append( 'poll_interval=' + str( jobattrs['poll_interval'] ) )
[80]430                appendList.append( 'domain=' + jobattrs['domain'] )
[26]431
[134]432                if jobattrs['status'] == 'R':
433                        if len( jobattrs['nodes'] ) > 0:
434                                appendList.append( 'nodes=' + self.makeNodeString( jobattrs['nodes'] ) )
435                elif jobattrs['status'] == 'Q':
436                        appendList.append( 'nodes=' + str(jobattrs['nodes']) )
[95]437
[65]438                return self.makeAppendLists( appendList )
439
440        def makeAppendLists( self, append_list ):
[68]441                """
442                Divide all values from append_list over strings with a maximum
443                size of 1400
444                """
[65]445
446                app_lists = [ ]
447
448                mystr = None
449
450                for val in append_list:
451
452                        if not mystr:
453                                mystr = val
454                        else:
455                                if not self.checkValAppendMaxSize( mystr, val ):
456                                        mystr = mystr + ' ' + val
457                                else:
458                                        # Too big, new appenlist
459                                        app_lists.append( mystr )
460                                        mystr = val
461
462                app_lists.append( mystr )
463
464                return app_lists
465
466        def checkValAppendMaxSize( self, val, text ):
467                """Check if val + text size is not above 1400 (max msg size)"""
468
[69]469                # Max frame size of a udp datagram is 1500 bytes
470                # removing misc header and gmetric stuff leaves about 1400 bytes
471                #
[65]472                if len( val + text ) > 1400:
473                        return 1
474                else:
475                        return 0
476
[61]477        def printJobs( self, jobs ):
[65]478                """Print a jobinfo overview"""
479
[26]480                for name, attrs in self.jobs.items():
481
482                        print 'job %s' %(name)
483
484                        for name, val in attrs.items():
485
486                                print '\t%s = %s' %( name, val )
487
[61]488        def printJob( self, jobs, job_id ):
[65]489                """Print job with job_id from jobs"""
[26]490
491                print 'job %s' %(job_id)
492
[65]493                for name, val in jobs[ job_id ].items():
[26]494
495                        print '\t%s = %s' %( name, val )
496
497        def daemon( self ):
[65]498                """Run as daemon forever"""
[26]499
500                # Fork the first child
501                #
502                pid = os.fork()
503                if pid > 0:
[212]504                        sys.exit(0)  # end parent
[26]505
506                # creates a session and sets the process group ID
507                #
508                os.setsid()
509
510                # Fork the second child
511                #
512                pid = os.fork()
513                if pid > 0:
[212]514                        sys.exit(0)  # end parent
[26]515
516                # Go to the root directory and set the umask
517                #
518                os.chdir('/')
519                os.umask(0)
520
521                sys.stdin.close()
522                sys.stdout.close()
523                sys.stderr.close()
524
525                os.open('/dev/null', 0)
526                os.dup(0)
527                os.dup(0)
528
529                self.run()
530
531        def run( self ):
[65]532                """Main thread"""
[26]533
534                while ( 1 ):
535               
[65]536                        self.jobs = self.getJobData( self.jobs )
537                        self.submitJobData( self.jobs )
[64]538                        time.sleep( TORQUE_POLL_INTERVAL )     
[26]539
540def printTime( ):
[65]541        """Print current time/date in human readable format for log/debug"""
[26]542
543        return time.strftime("%a, %d %b %Y %H:%M:%S")
544
545def debug_msg( level, msg ):
[65]546        """Print msg if at or above current debug level"""
[26]547
548        if (DEBUG_LEVEL >= level):
549                        sys.stderr.write( msg + '\n' )
550
[23]551def main():
[65]552        """Application start"""
[23]553
[212]554        if not processArgs( sys.argv[1:] ):
555                sys.exit( 1 )
556
[174]557        gather = DataGatherer()
[26]558        if DAEMONIZE:
559                gather.daemon()
560        else:
561                gather.run()
[23]562
[65]563# w00t someone started me
564#
[23]565if __name__ == '__main__':
566        main()
Note: See TracBrowser for help on using the repository browser.