source: trunk/jobmond/jobmond.py @ 219

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

TODO:

  • updated

AUTHORS:

  • updated

jobmond/jobmond.py,
web/addons/job_monarch/libtoga.php:

  • renamed metric internals from TOGA to MONARCH

web/addons/job_monarch/conf.php:

  • renamed comment from Toga to Job Monarch
File size: 13.2 KB
Line 
1#!/usr/bin/env python
2
3import sys, getopt, ConfigParser
4
5def processArgs( args ):
6
7        SHORT_L = 'c:'
8        LONG_L = 'config='
9
10        config_filename = None
11
12        try:
13
14                opts, args = getopt.getopt( args, SHORT_L, LONG_L )
15
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
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
67        cfg = ConfigParser.ConfigParser()
68
69        cfg.read( filename )
70
71        global DEBUG_LEVEL, DAEMONIZE, TORQUE_SERVER, TORQUE_POLL_INTERVAL, GMOND_CONF, DETECT_TIME_DIFFS, BATCH_HOST_TRANSLATE
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
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
116        return True
117
118from PBSQuery import PBSQuery
119
120import time, os, socket, string, re
121
122class DataProcessor:
123        """Class for processing of data"""
124
125        binary = '/usr/bin/gmetric'
126
127        def __init__( self, binary=None ):
128                """Remember alternate binary location if supplied"""
129
130                if binary:
131                        self.binary = binary
132
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.'
139
140                self.dmax = str( int( int( TORQUE_POLL_INTERVAL ) + 2 ) )
141
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
152                incompatible = self.checkGmetricVersion()
153
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 ):
159                """
160                Check version of gmetric is at least 3.0.1
161                for the syntax we use
162                """
163
164                for line in os.popen( self.binary + ' --version' ).readlines():
165
166                        line = line.split( ' ' )
167
168                        if len( line ) == 2 and str(line).find( 'gmetric' ) != -1:
169                       
170                                gmetric_version = line[1].split( '\n' )[0]
171
172                                version_major = int( gmetric_version.split( '.' )[0] )
173                                version_minor = int( gmetric_version.split( '.' )[1] )
174                                version_patch = int( gmetric_version.split( '.' )[2] )
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                                               
188                                                        incompatible = 1
189
190                return incompatible
191
192        def multicastGmetric( self, metricname, metricval, valtype='string' ):
193                """Call gmetric binary and multicast"""
194
195                cmd = self.binary
196
197                try:
198                        cmd = cmd + ' -c' + GMOND_CONF
199                except NameError:
200                        debug_msg( 10, 'Assuming /etc/gmond.conf for gmetric cmd (ommitting)' )
201
202                cmd = cmd + ' -n' + str( metricname )+ ' -v"' + str( metricval )+ '" -t' + str( valtype ) + ' -d' + str( self.dmax )
203
204                debug_msg( 10, printTime() + ' ' + cmd )
205                os.system( cmd )
206
207class DataGatherer:
208
209        jobs = { }
210
211        def __init__( self ):
212                """Setup appropriate variables"""
213
214                self.jobs = { }
215                self.timeoffset = 0
216                self.dp = DataProcessor()
217                self.initPbsQuery()
218
219        def initPbsQuery( self ):
220
221                self.pq = None
222                if( TORQUE_SERVER ):
223                        self.pq = PBSQuery( TORQUE_SERVER )
224                else:
225                        self.pq = PBSQuery()
226
227        def getAttr( self, attrs, name ):
228                """Return certain attribute from dictionary, if exists"""
229
230                if attrs.has_key( name ):
231                        return attrs[name]
232                else:
233                        return ''
234
235        def jobDataChanged( self, jobs, job_id, attrs ):
236                """Check if job with attrs and job_id in jobs has changed"""
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
256        def getJobData( self, known_jobs ):
257                """Gather all data on current jobs in Torque"""
258
259                if len( known_jobs ) > 0:
260                        jobs = known_jobs
261                else:
262                        jobs = { }
263
264                #self.initPbsQuery()
265       
266                #print self.pq.getnodes()
267       
268                joblist = self.pq.getjobs()
269
270                self.cur_time = time.time()
271
272                jobs_processed = [ ]
273
274                #self.printJobs( joblist )
275
276                for name, attrs in joblist.items():
277
278                        job_id = name.split( '.' )[0]
279
280                        jobs_processed.append( job_id )
281
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' )
287
288                        mynoderequest = self.getAttr( attrs, 'Resource_List.nodes' )
289
290                        if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
291                                ppn = mynoderequest.split( ':' )[1].split( 'ppn=' )[1]
292                        else:
293                                ppn = ''
294
295                        status = self.getAttr( attrs, 'job_state' )
296
297                        if status == 'R':
298                                start_timestamp = self.getAttr( attrs, 'mtime' )
299                                nodes = self.getAttr( attrs, 'exec_host' ).split( '+' )
300
301                                nodeslist = [ ]
302
303                                for node in nodes:
304                                        host = node.split( '/' )[0]
305
306                                        if nodeslist.count( host ) == 0:
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                               
315                                                if not host in nodeslist:
316                               
317                                                        nodeslist.append( host )
318
319                                if DETECT_TIME_DIFFS:
320
321                                        # If a job start if later than our current date,
322                                        # that must mean the Torque server's time is later
323                                        # than our local time.
324                               
325                                        if int(start_timestamp) > int( int(self.cur_time) + int(self.timeoffset) ):
326
327                                                self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
328
329                        elif status == 'Q':
330                                start_timestamp = ''
331                                count_mynodes = 0
332                                numeric_node = 1
333
334                                for node in mynoderequest.split( '+' ):
335
336                                        nodepart = node.split( ':' )[0]
337
338                                        for letter in nodepart:
339
340                                                if letter not in string.digits:
341
342                                                        numeric_node = 0
343
344                                        if not numeric_node:
345                                                count_mynodes = count_mynodes + 1
346                                        else:
347                                                count_mynodes = count_mynodes + int( nodepart )
348                                               
349                                nodeslist = count_mynodes
350                        else:
351                                start_timestamp = ''
352                                nodeslist = ''
353
354                        myAttrs = { }
355                        myAttrs['name'] = name
356                        myAttrs['queue'] = queue
357                        myAttrs['owner'] = owner
358                        myAttrs['requested_time'] = requested_time
359                        myAttrs['requested_memory'] = requested_memory
360                        myAttrs['ppn'] = ppn
361                        myAttrs['status'] = status
362                        myAttrs['start_timestamp'] = start_timestamp
363                        myAttrs['reported'] = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
364                        myAttrs['nodes'] = nodeslist
365                        myAttrs['domain'] = string.join( socket.getfqdn().split( '.' )[1:], '.' )
366                        myAttrs['poll_interval'] = TORQUE_POLL_INTERVAL
367
368                        if self.jobDataChanged( jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
369                                jobs[ job_id ] = myAttrs
370
371                                #debug_msg( 10, printTime() + ' job %s state changed' %(job_id) )
372
373                for id, attrs in jobs.items():
374
375                        if id not in jobs_processed:
376
377                                # This one isn't there anymore; toedeledoki!
378                                #
379                                del jobs[ id ]
380
381                return jobs
382
383        def submitJobData( self, jobs ):
384                """Submit job info list"""
385
386                self.dp.multicastGmetric( 'MONARCH-HEARTBEAT', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
387
388                # Now let's spread the knowledge
389                #
390                for jobid, jobattrs in jobs.items():
391
392                        gmetric_val = self.compileGmetricVal( jobid, jobattrs )
393
394                        for val in gmetric_val:
395                                self.dp.multicastGmetric( 'MONARCH-JOB-' + jobid, val )
396
397        def makeNodeString( self, nodelist ):
398                """Make one big string of all hosts"""
399
400                node_str = None
401
402                for node in nodelist:
403                        if not node_str:
404                                node_str = node
405                        else:
406                                node_str = node_str + ';' + node
407
408                return node_str
409
410        def compileGmetricVal( self, jobid, jobattrs ):
411                """Create a val string for gmetric of jobinfo"""
412
413                appendList = [ ]
414                appendList.append( 'name=' + jobattrs['name'] )
415                appendList.append( 'queue=' + jobattrs['queue'] )
416                appendList.append( 'owner=' + jobattrs['owner'] )
417                appendList.append( 'requested_time=' + jobattrs['requested_time'] )
418
419                if jobattrs['requested_memory'] != '':
420                        appendList.append( 'requested_memory=' + jobattrs['requested_memory'] )
421
422                if jobattrs['ppn'] != '':
423                        appendList.append( 'ppn=' + jobattrs['ppn'] )
424
425                appendList.append( 'status=' + jobattrs['status'] )
426
427                if jobattrs['start_timestamp'] != '':
428                        appendList.append( 'start_timestamp=' + jobattrs['start_timestamp'] )
429
430                appendList.append( 'reported=' + jobattrs['reported'] )
431                appendList.append( 'poll_interval=' + str( jobattrs['poll_interval'] ) )
432                appendList.append( 'domain=' + jobattrs['domain'] )
433
434                if jobattrs['status'] == 'R':
435                        if len( jobattrs['nodes'] ) > 0:
436                                appendList.append( 'nodes=' + self.makeNodeString( jobattrs['nodes'] ) )
437                elif jobattrs['status'] == 'Q':
438                        appendList.append( 'nodes=' + str(jobattrs['nodes']) )
439
440                return self.makeAppendLists( appendList )
441
442        def makeAppendLists( self, append_list ):
443                """
444                Divide all values from append_list over strings with a maximum
445                size of 1400
446                """
447
448                app_lists = [ ]
449
450                mystr = None
451
452                for val in append_list:
453
454                        if not mystr:
455                                mystr = val
456                        else:
457                                if not self.checkValAppendMaxSize( mystr, val ):
458                                        mystr = mystr + ' ' + val
459                                else:
460                                        # Too big, new appenlist
461                                        app_lists.append( mystr )
462                                        mystr = val
463
464                app_lists.append( mystr )
465
466                return app_lists
467
468        def checkValAppendMaxSize( self, val, text ):
469                """Check if val + text size is not above 1400 (max msg size)"""
470
471                # Max frame size of a udp datagram is 1500 bytes
472                # removing misc header and gmetric stuff leaves about 1300 bytes
473                #
474                if len( val + text ) > 900:
475                        return 1
476                else:
477                        return 0
478
479        def printJobs( self, jobs ):
480                """Print a jobinfo overview"""
481
482                for name, attrs in self.jobs.items():
483
484                        print 'job %s' %(name)
485
486                        for name, val in attrs.items():
487
488                                print '\t%s = %s' %( name, val )
489
490        def printJob( self, jobs, job_id ):
491                """Print job with job_id from jobs"""
492
493                print 'job %s' %(job_id)
494
495                for name, val in jobs[ job_id ].items():
496
497                        print '\t%s = %s' %( name, val )
498
499        def daemon( self ):
500                """Run as daemon forever"""
501
502                # Fork the first child
503                #
504                pid = os.fork()
505                if pid > 0:
506                        sys.exit(0)  # end parent
507
508                # creates a session and sets the process group ID
509                #
510                os.setsid()
511
512                # Fork the second child
513                #
514                pid = os.fork()
515                if pid > 0:
516                        sys.exit(0)  # end parent
517
518                # Go to the root directory and set the umask
519                #
520                os.chdir('/')
521                os.umask(0)
522
523                sys.stdin.close()
524                sys.stdout.close()
525                sys.stderr.close()
526
527                os.open('/dev/null', 0)
528                os.dup(0)
529                os.dup(0)
530
531                self.run()
532
533        def run( self ):
534                """Main thread"""
535
536                while ( 1 ):
537               
538                        self.jobs = self.getJobData( self.jobs )
539                        self.submitJobData( self.jobs )
540                        time.sleep( TORQUE_POLL_INTERVAL )     
541
542def printTime( ):
543        """Print current time/date in human readable format for log/debug"""
544
545        return time.strftime("%a, %d %b %Y %H:%M:%S")
546
547def debug_msg( level, msg ):
548        """Print msg if at or above current debug level"""
549
550        if (DEBUG_LEVEL >= level):
551                        sys.stderr.write( msg + '\n' )
552
553def main():
554        """Application start"""
555
556        if not processArgs( sys.argv[1:] ):
557                sys.exit( 1 )
558
559        gather = DataGatherer()
560        if DAEMONIZE:
561                gather.daemon()
562        else:
563                gather.run()
564
565# w00t someone started me
566#
567if __name__ == '__main__':
568        main()
Note: See TracBrowser for help on using the repository browser.