source: trunk/jobmond/jobmond.py @ 228

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

jobmond/jobmond.py:

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