source: trunk/jobmond/jobmond.py @ 243

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

jobmond/jobmond.py:

  • added queued_timestamp

web/addons/job_monarch/overview.php:

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