source: trunk/jobmond/jobmond.py @ 254

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

jobmond/jobmond.py:

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