source: trunk/jobmond/jobmond.py @ 307

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

jobmond/jobmond.py:

  • added: pidfile support (thanks Michael Jeanson)
  • added: usage (thanks Michael Jeanson)
  • Property svn:keywords set to Id
File size: 15.3 KB
Line 
1#!/usr/bin/env python
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#
21# SVN $Id: jobmond.py 307 2007-04-17 15:02:55Z bastiaans $
22#
23
24import sys, getopt, ConfigParser
25
26def usage():
27
28        print
29        print 'usage: jobmond [options]'
30        print 'options:'
31        print '      --config, -c      configuration file'
32        print '      --pidfile, -p     pid file'
33        print '      --help, -h        help'
34        print
35
36
37def processArgs( args ):
38
39        SHORT_L = 'c:'
40        LONG_L = 'config='
41
42        global PIDFILE
43        PIDFILE = None
44        config_filename = '/etc/jobmond.conf'
45
46        try:
47
48                opts, args = getopt.getopt( args, SHORT_L, LONG_L )
49
50        except getopt.GetoptError, detail:
51
52                print detail
53                usage()
54                sys.exit(1)
55
56        for opt, value in opts:
57
58                if opt in [ '--config', '-c' ]:
59               
60                        config_filename = value
61
62                if opt in [ '--pidfile', '-p' ]:
63
64                        PIDFILE = value
65               
66                if opt in [ '--help', '-h' ]:
67 
68                        usage()
69                        sys.exit(1)
70
71        return loadConfig( config_filename )
72
73def loadConfig( filename ):
74
75        def getlist( cfg_string ):
76
77                my_list = [ ]
78
79                for item_txt in cfg_string.split( ',' ):
80
81                        sep_char = None
82
83                        item_txt = item_txt.strip()
84
85                        for s_char in [ "'", '"' ]:
86
87                                if item_txt.find( s_char ) != -1:
88
89                                        if item_txt.count( s_char ) != 2:
90
91                                                print 'Missing quote: %s' %item_txt
92                                                sys.exit( 1 )
93
94                                        else:
95
96                                                sep_char = s_char
97                                                break
98
99                        if sep_char:
100
101                                item_txt = item_txt.split( sep_char )[1]
102
103                        my_list.append( item_txt )
104
105                return my_list
106
107        cfg = ConfigParser.ConfigParser()
108
109        cfg.read( filename )
110
111        global DEBUG_LEVEL, DAEMONIZE, BATCH_SERVER, BATCH_POLL_INTERVAL, GMOND_CONF, DETECT_TIME_DIFFS, BATCH_HOST_TRANSLATE, BATCH_API
112
113        DEBUG_LEVEL = cfg.getint( 'DEFAULT', 'DEBUG_LEVEL' )
114
115        DAEMONIZE = cfg.getboolean( 'DEFAULT', 'DAEMONIZE' )
116
117        try:
118
119                BATCH_SERVER = cfg.get( 'DEFAULT', 'BATCH_SERVER' )
120
121        except ConfigParser.NoOptionError:
122
123                # Backwards compatibility for old configs
124                #
125
126                BATCH_SERVER = cfg.get( 'DEFAULT', 'TORQUE_SERVER' )
127                api_guess = 'pbs'
128       
129        try:
130       
131                BATCH_POLL_INTERVAL = cfg.getint( 'DEFAULT', 'BATCH_POLL_INTERVAL' )
132
133        except ConfigParser.NoOptionError:
134
135                # Backwards compatibility for old configs
136                #
137
138                BATCH_POLL_INTERVAL = cfg.getint( 'DEFAULT', 'TORQUE_POLL_INTERVAL' )
139                api_guess = 'pbs'
140               
141        GMOND_CONF = cfg.get( 'DEFAULT', 'GMOND_CONF' )
142
143        DETECT_TIME_DIFFS = cfg.getboolean( 'DEFAULT', 'DETECT_TIME_DIFFS' )
144
145        BATCH_HOST_TRANSLATE = getlist( cfg.get( 'DEFAULT', 'BATCH_HOST_TRANSLATE' ) )
146
147        try:
148
149                BATCH_API = cfg.get( 'DEFAULT', 'BATCH_API' )
150
151        except ConfigParser.NoOptionError, detail:
152
153                if BATCH_SERVER and api_guess:
154                        BATCH_API = api_guess
155                else:
156                        debug_msg( 0, "fatal error: BATCH_API not set and can't make guess" )
157                        sys.exit( 1 )
158       
159        return True
160
161
162import time, os, socket, string, re
163
164METRIC_MAX_VAL_LEN = 900
165
166class DataProcessor:
167        """Class for processing of data"""
168
169        binary = '/usr/bin/gmetric'
170
171        def __init__( self, binary=None ):
172                """Remember alternate binary location if supplied"""
173
174                if binary:
175                        self.binary = binary
176
177                # Timeout for XML
178                #
179                # From ganglia's documentation:
180                #
181                # 'A metric will be deleted DMAX seconds after it is received, and
182                # DMAX=0 means eternal life.'
183
184                self.dmax = str( int( int( BATCH_POLL_INTERVAL ) * 2 ) )
185
186                try:
187                        gmond_file = GMOND_CONF
188
189                except NameError:
190                        gmond_file = '/etc/gmond.conf'
191
192                if not os.path.exists( gmond_file ):
193                        debug_msg( 0, gmond_file + ' does not exist' )
194                        sys.exit( 1 )
195
196                incompatible = self.checkGmetricVersion()
197
198                if incompatible:
199                        debug_msg( 0, 'Gmetric version not compatible, pls upgrade to at least 3.0.1' )
200                        sys.exit( 1 )
201
202        def checkGmetricVersion( self ):
203                """
204                Check version of gmetric is at least 3.0.1
205                for the syntax we use
206                """
207
208                global METRIC_MAX_VAL_LEN
209
210                for line in os.popen( self.binary + ' --version' ).readlines():
211
212                        line = line.split( ' ' )
213
214                        if len( line ) == 2 and str(line).find( 'gmetric' ) != -1:
215                       
216                                gmetric_version = line[1].split( '\n' )[0]
217
218                                version_major = int( gmetric_version.split( '.' )[0] )
219                                version_minor = int( gmetric_version.split( '.' )[1] )
220                                version_patch = int( gmetric_version.split( '.' )[2] )
221
222                                incompatible = 0
223
224                                if version_major < 3:
225
226                                        incompatible = 1
227                               
228                                elif version_major == 3:
229
230                                        if version_minor == 0:
231
232                                                if version_patch < 1:
233                                               
234                                                        incompatible = 1
235
236                                                if version_patch < 3:
237
238                                                        METRIC_MAX_VAL_LEN = 900
239
240                                                elif version_patch >= 3:
241
242                                                        METRIC_MAX_VAL_LEN = 1400
243
244                return incompatible
245
246        def multicastGmetric( self, metricname, metricval, valtype='string' ):
247                """Call gmetric binary and multicast"""
248
249                cmd = self.binary
250
251                try:
252                        cmd = cmd + ' -c' + GMOND_CONF
253                except NameError:
254                        debug_msg( 10, 'Assuming /etc/gmond.conf for gmetric cmd (ommitting)' )
255
256                cmd = cmd + ' -n' + str( metricname )+ ' -v"' + str( metricval )+ '" -t' + str( valtype ) + ' -d' + str( self.dmax )
257
258                debug_msg( 10, printTime() + ' ' + cmd )
259                os.system( cmd )
260
261class SgeDataGatherer:
262
263        """Placeholder for Babu Sundaram's SGE implementation"""
264
265        def daemon( self ):
266
267                pass
268
269        def run( self ):
270
271                pass
272
273class PbsDataGatherer:
274
275        """This is the DataGatherer for PBS and Torque"""
276
277        jobs = { }
278
279        global PBSQuery
280
281        def __init__( self ):
282                """Setup appropriate variables"""
283
284                self.jobs = { }
285                self.timeoffset = 0
286                self.dp = DataProcessor()
287                self.initPbsQuery()
288
289        def initPbsQuery( self ):
290
291                self.pq = None
292                if( BATCH_SERVER ):
293                        self.pq = PBSQuery( BATCH_SERVER )
294                else:
295                        self.pq = PBSQuery()
296
297        def getAttr( self, attrs, name ):
298                """Return certain attribute from dictionary, if exists"""
299
300                if attrs.has_key( name ):
301                        return attrs[name]
302                else:
303                        return ''
304
305        def jobDataChanged( self, jobs, job_id, attrs ):
306                """Check if job with attrs and job_id in jobs has changed"""
307
308                if jobs.has_key( job_id ):
309                        oldData = jobs[ job_id ]       
310                else:
311                        return 1
312
313                for name, val in attrs.items():
314
315                        if oldData.has_key( name ):
316
317                                if oldData[ name ] != attrs[ name ]:
318
319                                        return 1
320
321                        else:
322                                return 1
323
324                return 0
325
326        def getJobData( self, known_jobs ):
327                """Gather all data on current jobs in Torque"""
328
329                if len( known_jobs ) > 0:
330                        jobs = known_jobs
331                else:
332                        jobs = { }
333
334                #self.initPbsQuery()
335       
336                #print self.pq.getnodes()
337       
338                joblist = {}
339                while len(joblist) == 0:
340                        try:
341                                joblist = self.pq.getjobs()
342                        except PBSError:
343                                time.sleep( TORQUE_POLL_INTERVAL )
344
345                self.cur_time = time.time()
346
347                jobs_processed = [ ]
348
349                #self.printJobs( joblist )
350
351                for name, attrs in joblist.items():
352
353                        job_id = name.split( '.' )[0]
354
355                        jobs_processed.append( job_id )
356
357                        name = self.getAttr( attrs, 'Job_Name' )
358                        queue = self.getAttr( attrs, 'queue' )
359                        owner = self.getAttr( attrs, 'Job_Owner' ).split( '@' )[0]
360                        requested_time = self.getAttr( attrs, 'Resource_List.walltime' )
361                        requested_memory = self.getAttr( attrs, 'Resource_List.mem' )
362
363                        mynoderequest = self.getAttr( attrs, 'Resource_List.nodes' )
364
365                        ppn = ''
366
367                        if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
368
369                                mynoderequest_fields = mynoderequest.split( ':' )
370
371                                for mynoderequest_field in mynoderequest_fields:
372
373                                        if mynoderequest_field.find( 'ppn' ) != -1:
374
375                                                ppn = mynoderequest_field.split( 'ppn=' )[1]
376
377                        status = self.getAttr( attrs, 'job_state' )
378
379                        queued_timestamp = self.getAttr( attrs, 'ctime' )
380
381                        if status == 'R':
382                                start_timestamp = self.getAttr( attrs, 'mtime' )
383                                nodes = self.getAttr( attrs, 'exec_host' ).split( '+' )
384
385                                nodeslist = [ ]
386
387                                for node in nodes:
388                                        host = node.split( '/' )[0]
389
390                                        if nodeslist.count( host ) == 0:
391
392                                                for translate_pattern in BATCH_HOST_TRANSLATE:
393
394                                                        if translate_pattern.find( '/' ) != -1:
395
396                                                                translate_orig = translate_pattern.split( '/' )[1]
397                                                                translate_new = translate_pattern.split( '/' )[2]
398
399                                                                host = re.sub( translate_orig, translate_new, host )
400                               
401                                                if not host in nodeslist:
402                               
403                                                        nodeslist.append( host )
404
405                                if DETECT_TIME_DIFFS:
406
407                                        # If a job start if later than our current date,
408                                        # that must mean the Torque server's time is later
409                                        # than our local time.
410                               
411                                        if int(start_timestamp) > int( int(self.cur_time) + int(self.timeoffset) ):
412
413                                                self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
414
415                        elif status == 'Q':
416                                start_timestamp = ''
417                                count_mynodes = 0
418                                numeric_node = 1
419
420                                for node in mynoderequest.split( '+' ):
421
422                                        nodepart = node.split( ':' )[0]
423
424                                        for letter in nodepart:
425
426                                                if letter not in string.digits:
427
428                                                        numeric_node = 0
429
430                                        if not numeric_node:
431                                                count_mynodes = count_mynodes + 1
432                                        else:
433                                                count_mynodes = count_mynodes + int( nodepart )
434                                               
435                                nodeslist = str( count_mynodes )
436                        else:
437                                start_timestamp = ''
438                                nodeslist = ''
439
440                        myAttrs = { }
441                        myAttrs['name'] = str( name )
442                        myAttrs['queue'] = str( queue )
443                        myAttrs['owner'] = str( owner )
444                        myAttrs['requested_time'] = str( requested_time )
445                        myAttrs['requested_memory'] = str( requested_memory )
446                        myAttrs['ppn'] = str( ppn )
447                        myAttrs['status'] = str( status )
448                        myAttrs['start_timestamp'] = str( start_timestamp )
449                        myAttrs['queued_timestamp'] = str( queued_timestamp )
450                        myAttrs['reported'] = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
451                        myAttrs['nodes'] = nodeslist
452                        myAttrs['domain'] = string.join( socket.getfqdn().split( '.' )[1:], '.' )
453                        myAttrs['poll_interval'] = str( BATCH_POLL_INTERVAL )
454
455                        if self.jobDataChanged( jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
456                                jobs[ job_id ] = myAttrs
457
458                                #debug_msg( 10, printTime() + ' job %s state changed' %(job_id) )
459
460                for id, attrs in jobs.items():
461
462                        if id not in jobs_processed:
463
464                                # This one isn't there anymore; toedeledoki!
465                                #
466                                del jobs[ id ]
467
468                return jobs
469
470        def submitJobData( self, jobs ):
471                """Submit job info list"""
472
473                self.dp.multicastGmetric( 'MONARCH-HEARTBEAT', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
474
475                # Now let's spread the knowledge
476                #
477                for jobid, jobattrs in jobs.items():
478
479                        gmetric_val = self.compileGmetricVal( jobid, jobattrs )
480
481                        metric_increment = 0
482
483                        for val in gmetric_val:
484                                self.dp.multicastGmetric( 'MONARCH-JOB-' + jobid + '-' + str(metric_increment), val )
485                                metric_increment = metric_increment + 1
486
487        def compileGmetricVal( self, jobid, jobattrs ):
488                """Create a val string for gmetric of jobinfo"""
489
490                gval_lists = [ ]
491
492                mystr = None
493
494                val_list = { }
495
496                for val_name, val_value in jobattrs.items():
497
498                        val_list_names_len      = len( string.join( val_list.keys() ) ) + len(val_list.keys())
499                        val_list_vals_len       = len( string.join( val_list.values() ) ) + len(val_list.values())
500
501                        if val_name == 'nodes' and jobattrs['status'] == 'R':
502
503                                node_str = None
504
505                                for node in val_value:
506
507                                        if node_str:
508                                                node_str = node_str + ';' + node
509                                        else:
510                                                node_str = node
511
512                                        if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(node_str) ) > METRIC_MAX_VAL_LEN:
513
514                                                val_list[ val_name ] = node_str
515                                                gval_lists.append( val_list )
516                                                val_list = { }
517                                                node_str = None
518
519                                val_list[ val_name ] = node_str
520                                gval_lists.append( val_list )
521                                val_list = { }
522
523                        elif val_value != '':
524
525                                if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(str(val_value)) ) > METRIC_MAX_VAL_LEN:
526
527                                        gval_lists.append( val_list )
528                                        val_list = { }
529
530                                val_list[ val_name ] = val_value
531
532                if len(val_list) > 0:
533                        gval_lists.append( val_list )
534
535                str_list = [ ]
536
537                for val_list in gval_lists:
538
539                        my_val_str = None
540
541                        for val_name, val_value in val_list.items():
542
543                                if my_val_str:
544
545                                        my_val_str = my_val_str + ' ' + val_name + '=' + val_value
546                                else:
547                                        my_val_str = val_name + '=' + val_value
548
549                        str_list.append( my_val_str )
550
551                return str_list
552
553        def printJobs( self, jobs ):
554                """Print a jobinfo overview"""
555
556                for name, attrs in self.jobs.items():
557
558                        print 'job %s' %(name)
559
560                        for name, val in attrs.items():
561
562                                print '\t%s = %s' %( name, val )
563
564        def printJob( self, jobs, job_id ):
565                """Print job with job_id from jobs"""
566
567                print 'job %s' %(job_id)
568
569                for name, val in jobs[ job_id ].items():
570
571                        print '\t%s = %s' %( name, val )
572
573        def daemon( self ):
574                """Run as daemon forever"""
575
576                # Fork the first child
577                #
578                pid = os.fork()
579                if pid > 0:
580                        sys.exit(0)  # end parent
581
582                # creates a session and sets the process group ID
583                #
584                os.setsid()
585
586                # Fork the second child
587                #
588                pid = os.fork()
589                if pid > 0:
590                        sys.exit(0)  # end parent
591
592                write_pidfile()
593
594                # Go to the root directory and set the umask
595                #
596                os.chdir('/')
597                os.umask(0)
598
599                sys.stdin.close()
600                sys.stdout.close()
601                sys.stderr.close()
602
603                os.open('/dev/null', os.O_RDWR)
604                os.dup2(0, 1)
605                os.dup2(0, 2)
606
607                self.run()
608
609        def run( self ):
610                """Main thread"""
611
612                while ( 1 ):
613               
614                        self.jobs = self.getJobData( self.jobs )
615                        self.submitJobData( self.jobs )
616                        time.sleep( BATCH_POLL_INTERVAL )       
617
618def printTime( ):
619        """Print current time/date in human readable format for log/debug"""
620
621        return time.strftime("%a, %d %b %Y %H:%M:%S")
622
623def debug_msg( level, msg ):
624        """Print msg if at or above current debug level"""
625
626        if (DEBUG_LEVEL >= level):
627                        sys.stderr.write( msg + '\n' )
628
629def write_pidfile():
630
631        # Write pidfile if PIDFILE exists
632        if PIDFILE:
633                pid = os.getpid()
634
635                pidfile = open(PIDFILE, 'w')
636                pidfile.write(str(pid))
637                pidfile.close()
638
639def main():
640        """Application start"""
641
642        global PBSQuery
643
644        if not processArgs( sys.argv[1:] ):
645                sys.exit( 1 )
646
647        if BATCH_API == 'pbs':
648
649                try:
650                        from PBSQuery import PBSQuery, PBSError
651
652                except ImportError:
653
654                        debug_msg( 0, "fatal error: BATCH_API set to 'pbs' but python module 'pbs_python' is not installed" )
655                        sys.exit( 1 )
656
657                gather = PbsDataGatherer()
658
659        elif BATCH_API == 'sge':
660
661                pass
662                # import Babu's code here
663                #
664                #try:
665                #       import sge_drmaa
666                #
667                #except ImportError:
668                #
669                #       debug_msg( 0, "fatal error: BATCH_API set to 'sge' but python module 'sge_drmaa' is not installed' )
670                #       sys.exit( 1 )
671                #
672                #gather = SgeDataGatherer()
673
674        else:
675                debug_msg( 0, "fatal error: unknown BATCH_API '" + BATCH_API + "' is not supported" )
676                sys.exit( 1 )
677
678        if DAEMONIZE:
679                gather.daemon()
680        else:
681                gather.run()
682
683# wh00t? someone started me! :)
684#
685if __name__ == '__main__':
686        main()
Note: See TracBrowser for help on using the repository browser.