source: trunk/jobmond/jobmond.py @ 255

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

jobmond/jobmond.py:

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