source: trunk/jobmond/jobmond.py @ 265

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

jobmond/jobmond.py:

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