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
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 254 2006-04-27 07:47:08Z bastiaans $
22#
23
24import sys, getopt, ConfigParser
25
26def processArgs( args ):
27
28        SHORT_L = 'c:'
29        LONG_L = 'config='
30
31        config_filename = None
32
33        try:
34
35                opts, args = getopt.getopt( args, SHORT_L, LONG_L )
36
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
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
88        cfg = ConfigParser.ConfigParser()
89
90        cfg.read( filename )
91
92        global DEBUG_LEVEL, DAEMONIZE, TORQUE_SERVER, TORQUE_POLL_INTERVAL, GMOND_CONF, DETECT_TIME_DIFFS, BATCH_HOST_TRANSLATE
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
106        BATCH_HOST_TRANSLATE = getlist( cfg.get( 'DEFAULT', 'BATCH_HOST_TRANSLATE' ) )
107
108        return True
109
110from PBSQuery import PBSQuery
111
112import time, os, socket, string, re
113
114METRIC_MAX_VAL_LEN = 900
115
116class DataProcessor:
117        """Class for processing of data"""
118
119        binary = '/usr/bin/gmetric'
120
121        def __init__( self, binary=None ):
122                """Remember alternate binary location if supplied"""
123
124                if binary:
125                        self.binary = binary
126
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.'
133
134                self.dmax = str( int( int( TORQUE_POLL_INTERVAL ) * 2 ) )
135
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
146                incompatible = self.checkGmetricVersion()
147
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 ):
153                """
154                Check version of gmetric is at least 3.0.1
155                for the syntax we use
156                """
157
158                for line in os.popen( self.binary + ' --version' ).readlines():
159
160                        line = line.split( ' ' )
161
162                        if len( line ) == 2 and str(line).find( 'gmetric' ) != -1:
163                       
164                                gmetric_version = line[1].split( '\n' )[0]
165
166                                version_major = int( gmetric_version.split( '.' )[0] )
167                                version_minor = int( gmetric_version.split( '.' )[1] )
168                                version_patch = int( gmetric_version.split( '.' )[2] )
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                                               
182                                                        incompatible = 1
183
184                return incompatible
185
186        def multicastGmetric( self, metricname, metricval, valtype='string' ):
187                """Call gmetric binary and multicast"""
188
189                cmd = self.binary
190
191                try:
192                        cmd = cmd + ' -c' + GMOND_CONF
193                except NameError:
194                        debug_msg( 10, 'Assuming /etc/gmond.conf for gmetric cmd (ommitting)' )
195
196                cmd = cmd + ' -n' + str( metricname )+ ' -v"' + str( metricval )+ '" -t' + str( valtype ) + ' -d' + str( self.dmax )
197
198                debug_msg( 10, printTime() + ' ' + cmd )
199                os.system( cmd )
200
201class DataGatherer:
202
203        jobs = { }
204
205        def __init__( self ):
206                """Setup appropriate variables"""
207
208                self.jobs = { }
209                self.timeoffset = 0
210                self.dp = DataProcessor()
211                self.initPbsQuery()
212
213        def initPbsQuery( self ):
214
215                self.pq = None
216                if( TORQUE_SERVER ):
217                        self.pq = PBSQuery( TORQUE_SERVER )
218                else:
219                        self.pq = PBSQuery()
220
221        def getAttr( self, attrs, name ):
222                """Return certain attribute from dictionary, if exists"""
223
224                if attrs.has_key( name ):
225                        return attrs[name]
226                else:
227                        return ''
228
229        def jobDataChanged( self, jobs, job_id, attrs ):
230                """Check if job with attrs and job_id in jobs has changed"""
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
250        def getJobData( self, known_jobs ):
251                """Gather all data on current jobs in Torque"""
252
253                if len( known_jobs ) > 0:
254                        jobs = known_jobs
255                else:
256                        jobs = { }
257
258                #self.initPbsQuery()
259       
260                #print self.pq.getnodes()
261       
262                joblist = self.pq.getjobs()
263
264                self.cur_time = time.time()
265
266                jobs_processed = [ ]
267
268                #self.printJobs( joblist )
269
270                for name, attrs in joblist.items():
271
272                        job_id = name.split( '.' )[0]
273
274                        jobs_processed.append( job_id )
275
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' )
281
282                        mynoderequest = self.getAttr( attrs, 'Resource_List.nodes' )
283
284                        if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
285                                ppn = mynoderequest.split( ':' )[1].split( 'ppn=' )[1]
286                        else:
287                                ppn = ''
288
289                        status = self.getAttr( attrs, 'job_state' )
290
291                        queued_timestamp = self.getAttr( attrs, 'ctime' )
292
293                        if status == 'R':
294                                start_timestamp = self.getAttr( attrs, 'mtime' )
295                                nodes = self.getAttr( attrs, 'exec_host' ).split( '+' )
296
297                                nodeslist = [ ]
298
299                                for node in nodes:
300                                        host = node.split( '/' )[0]
301
302                                        if nodeslist.count( host ) == 0:
303
304                                                for translate_pattern in BATCH_HOST_TRANSLATE:
305
306                                                        if translate_pattern.find( '/' ) != -1:
307
308                                                                translate_orig = translate_pattern.split( '/' )[1]
309                                                                translate_new = translate_pattern.split( '/' )[2]
310
311                                                                host = re.sub( translate_orig, translate_new, host )
312                               
313                                                if not host in nodeslist:
314                               
315                                                        nodeslist.append( host )
316
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
327                        elif status == 'Q':
328                                start_timestamp = ''
329                                count_mynodes = 0
330                                numeric_node = 1
331
332                                for node in mynoderequest.split( '+' ):
333
334                                        nodepart = node.split( ':' )[0]
335
336                                        for letter in nodepart:
337
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                                               
347                                nodeslist = str( count_mynodes )
348                        else:
349                                start_timestamp = ''
350                                nodeslist = ''
351
352                        myAttrs = { }
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 )
362                        myAttrs['reported'] = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
363                        myAttrs['nodes'] = nodeslist
364                        myAttrs['domain'] = string.join( socket.getfqdn().split( '.' )[1:], '.' )
365                        myAttrs['poll_interval'] = str( TORQUE_POLL_INTERVAL )
366
367                        if self.jobDataChanged( jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
368                                jobs[ job_id ] = myAttrs
369
370                                #debug_msg( 10, printTime() + ' job %s state changed' %(job_id) )
371
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
380                return jobs
381
382        def submitJobData( self, jobs ):
383                """Submit job info list"""
384
385                self.dp.multicastGmetric( 'MONARCH-HEARTBEAT', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
386
387                # Now let's spread the knowledge
388                #
389                for jobid, jobattrs in jobs.items():
390
391                        gmetric_val = self.compileGmetricVal( jobid, jobattrs )
392
393                        metric_increment = 0
394
395                        for val in gmetric_val:
396                                self.dp.multicastGmetric( 'MONARCH-JOB-' + jobid + '-' + str(metric_increment), val )
397                                metric_increment = metric_increment + 1
398
399        def compileGmetricVal( self, jobid, jobattrs ):
400                """Create a val string for gmetric of jobinfo"""
401
402                gval_lists = [ ]
403
404                mystr = None
405
406                val_list = { }
407
408                for val_name, val_value in jobattrs.items():
409
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())
412
413                        if val_name == 'nodes' and jobattrs['status'] == 'R':
414
415                                node_str = None
416
417                                for node in val_value:
418
419                                        if node_str:
420                                                node_str = node_str + ';' + node
421                                        else:
422                                                node_str = node
423
424                                        if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(node_str) ) > METRIC_MAX_VAL_LEN:
425
426                                                val_list[ val_name ] = node_str
427                                                gval_lists.append( val_list )
428                                                val_list = { }
429                                                node_str = None
430
431                                val_list[ val_name ] = node_str
432                                gval_lists.append( val_list )
433                                val_list = { }
434
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
447                str_list = [ ]
448
449                for val_list in gval_lists:
450
451                        my_val_str = None
452
453                        for val_name, val_value in val_list.items():
454
455                                if my_val_str:
456
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
465        def printJobs( self, jobs ):
466                """Print a jobinfo overview"""
467
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
476        def printJob( self, jobs, job_id ):
477                """Print job with job_id from jobs"""
478
479                print 'job %s' %(job_id)
480
481                for name, val in jobs[ job_id ].items():
482
483                        print '\t%s = %s' %( name, val )
484
485        def daemon( self ):
486                """Run as daemon forever"""
487
488                # Fork the first child
489                #
490                pid = os.fork()
491                if pid > 0:
492                        sys.exit(0)  # end parent
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:
502                        sys.exit(0)  # end parent
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 ):
520                """Main thread"""
521
522                while ( 1 ):
523               
524                        self.jobs = self.getJobData( self.jobs )
525                        self.submitJobData( self.jobs )
526                        time.sleep( TORQUE_POLL_INTERVAL )     
527
528def printTime( ):
529        """Print current time/date in human readable format for log/debug"""
530
531        return time.strftime("%a, %d %b %Y %H:%M:%S")
532
533def debug_msg( level, msg ):
534        """Print msg if at or above current debug level"""
535
536        if (DEBUG_LEVEL >= level):
537                        sys.stderr.write( msg + '\n' )
538
539def main():
540        """Application start"""
541
542        if not processArgs( sys.argv[1:] ):
543                sys.exit( 1 )
544
545        gather = DataGatherer()
546        if DAEMONIZE:
547                gather.daemon()
548        else:
549                gather.run()
550
551# w00t someone started me
552#
553if __name__ == '__main__':
554        main()
Note: See TracBrowser for help on using the repository browser.