source: trunk/jobmond/jobmond.py @ 523

Last change on this file since 523 was 520, checked in by bastiaans, 16 years ago

jobmond/jobmond.py:

  • added: gmond config parsing: ticket #48
  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 35.7 KB
Line 
1#!/usr/bin/env python
2#
3# This file is part of Jobmonarch
4#
5# Copyright (C) 2006-2007  Ramon Bastiaans
6# Copyright (C) 2007  Dave Love  (SGE code)
7#
8# Jobmonarch is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or
11# (at your option) any later version.
12#
13# Jobmonarch is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with this program; if not, write to the Free Software
20# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21#
22# SVN $Id: jobmond.py 520 2008-03-12 17:22:46Z bastiaans $
23#
24
25import sys, getopt, ConfigParser, time, os, socket, string, re
26import xdrlib, socket, syslog, xml, xml.sax
27from xml.sax.handler import feature_namespaces
28
29VERSION='0.3.1'
30
31def usage( ver ):
32
33        print 'jobmond %s' %VERSION
34
35        if ver:
36                return 0
37
38        print
39        print 'Purpose:'
40        print '  The Job Monitoring Daemon (jobmond) reports batch jobs information and statistics'
41        print '  to Ganglia, which can be viewed with Job Monarch web frontend'
42        print
43        print 'Usage:   jobmond [OPTIONS]'
44        print
45        print '  -c, --config=FILE      The configuration file to use (default: /etc/jobmond.conf)'
46        print '  -p, --pidfile=FILE     Use pid file to store the process id'
47        print '  -h, --help             Print help and exit'
48        print '  -v, --version          Print version and exit'
49        print
50
51def processArgs( args ):
52
53        SHORT_L         = 'p:hvc:'
54        LONG_L          = [ 'help', 'config=', 'pidfile=', 'version' ]
55
56        global PIDFILE
57        PIDFILE         = None
58
59        config_filename = '/etc/jobmond.conf'
60
61        try:
62
63                opts, args      = getopt.getopt( args, SHORT_L, LONG_L )
64
65        except getopt.GetoptError, detail:
66
67                print detail
68                usage()
69                sys.exit( 1 )
70
71        for opt, value in opts:
72
73                if opt in [ '--config', '-c' ]:
74               
75                        config_filename = value
76
77                if opt in [ '--pidfile', '-p' ]:
78
79                        PIDFILE         = value
80               
81                if opt in [ '--help', '-h' ]:
82 
83                        usage( False )
84                        sys.exit( 0 )
85
86                if opt in [ '--version', '-v' ]:
87
88                        usage( True )
89                        sys.exit( 0 )
90
91        return loadConfig( config_filename )
92
93class GangliaConfigParser:
94
95        def __init__( self, config_file ):
96
97                self.config_file        = config_file
98
99                if not os.path.exists( self.config_file ):
100
101                        debug_msg( 0, "FATAL ERROR: gmond config '" + self.config_file + "' not found!" )
102                        sys.exit( 1 )
103
104        def removeQuotes( self, value ):
105
106                clean_value     = value
107                clean_value     = clean_value.replace( "'", "" )
108                clean_value     = clean_value.replace( '"', '' )
109                clean_value     = clean_value.strip()
110
111                return clean_value
112
113        def getVal( self, section, valname ):
114
115                cfg_fp          = open( self.config_file )
116                section_start   = False
117                section_found   = False
118                value           = None
119
120                for line in cfg_fp.readlines():
121
122                        if line.find( section ) != -1:
123
124                                section_found   = True
125
126                        if line.find( '{' ) != -1 and section_found:
127
128                                section_start   = True
129
130                        if line.find( '}' ) != -1 and section_found:
131
132                                section_start   = False
133                                section_found   = False
134
135                        if line.find( valname ) != -1 and section_start:
136
137                                value           = string.join( line.split( '=' )[1:], '' ).strip()
138
139                cfg_fp.close()
140
141                return value
142
143        def getInt( self, section, valname ):
144
145                value   = self.getVal( section, valname )
146
147                if not value:
148                        return False
149
150                value   = self.removeQuotes( value )
151
152                return int( value )
153
154        def getStr( self, section, valname ):
155
156                value   = self.getVal( section, valname )
157
158                if not value:
159                        return False
160
161                value   = self.removeQuotes( value )
162
163                return str( value )
164
165def findGmetric():
166
167        for dir in os.path.expandvars( '$PATH' ).split( ':' ):
168
169                guess   = '%s/%s' %( dir, 'gmetric' )
170
171                if os.path.exists( guess ):
172
173                        return guess
174
175        return False
176
177def loadConfig( filename ):
178
179        def getlist( cfg_string ):
180
181                my_list = [ ]
182
183                for item_txt in cfg_string.split( ',' ):
184
185                        sep_char = None
186
187                        item_txt = item_txt.strip()
188
189                        for s_char in [ "'", '"' ]:
190
191                                if item_txt.find( s_char ) != -1:
192
193                                        if item_txt.count( s_char ) != 2:
194
195                                                print 'Missing quote: %s' %item_txt
196                                                sys.exit( 1 )
197
198                                        else:
199
200                                                sep_char = s_char
201                                                break
202
203                        if sep_char:
204
205                                item_txt = item_txt.split( sep_char )[1]
206
207                        my_list.append( item_txt )
208
209                return my_list
210
211        cfg             = ConfigParser.ConfigParser()
212
213        cfg.read( filename )
214
215        global DEBUG_LEVEL, DAEMONIZE, BATCH_SERVER, BATCH_POLL_INTERVAL
216        global GMOND_CONF, DETECT_TIME_DIFFS, BATCH_HOST_TRANSLATE
217        global BATCH_API, QUEUE, GMETRIC_TARGET, USE_SYSLOG
218        global SYSLOG_LEVEL, SYSLOG_FACILITY, GMETRIC_BINARY
219
220        DEBUG_LEVEL     = cfg.getint( 'DEFAULT', 'DEBUG_LEVEL' )
221
222        DAEMONIZE       = cfg.getboolean( 'DEFAULT', 'DAEMONIZE' )
223
224        SYSLOG_LEVEL    = -1
225        SYSLOG_FACILITY = None
226
227        try:
228                USE_SYSLOG      = cfg.getboolean( 'DEFAULT', 'USE_SYSLOG' )
229
230        except ConfigParser.NoOptionError:
231
232                USE_SYSLOG      = True
233
234                debug_msg( 0, 'ERROR: no option USE_SYSLOG found: assuming yes' )
235
236        if USE_SYSLOG:
237
238                try:
239                        SYSLOG_LEVEL    = cfg.getint( 'DEFAULT', 'SYSLOG_LEVEL' )
240
241                except ConfigParser.NoOptionError:
242
243                        debug_msg( 0, 'ERROR: no option SYSLOG_LEVEL found: assuming level 0' )
244                        SYSLOG_LEVEL    = 0
245
246                try:
247
248                        SYSLOG_FACILITY = eval( 'syslog.LOG_' + cfg.get( 'DEFAULT', 'SYSLOG_FACILITY' ) )
249
250                except ConfigParser.NoOptionError:
251
252                        SYSLOG_FACILITY = syslog.LOG_DAEMON
253
254                        debug_msg( 0, 'ERROR: no option SYSLOG_FACILITY found: assuming facility DAEMON' )
255
256        try:
257
258                BATCH_SERVER            = cfg.get( 'DEFAULT', 'BATCH_SERVER' )
259
260        except ConfigParser.NoOptionError:
261
262                # Backwards compatibility for old configs
263                #
264
265                BATCH_SERVER            = cfg.get( 'DEFAULT', 'TORQUE_SERVER' )
266                api_guess               = 'pbs'
267       
268        try:
269       
270                BATCH_POLL_INTERVAL     = cfg.getint( 'DEFAULT', 'BATCH_POLL_INTERVAL' )
271
272        except ConfigParser.NoOptionError:
273
274                # Backwards compatibility for old configs
275                #
276
277                BATCH_POLL_INTERVAL     = cfg.getint( 'DEFAULT', 'TORQUE_POLL_INTERVAL' )
278                api_guess               = 'pbs'
279       
280        try:
281
282                GMOND_CONF              = cfg.get( 'DEFAULT', 'GMOND_CONF' )
283
284        except ConfigParser.NoOptionError:
285
286                # Not specified: assume /etc/gmond.conf
287                #
288                GMOND_CONF              = '/etc/gmond.conf'
289
290        ganglia_cfg             = GangliaConfigParser( GMOND_CONF )
291
292        # Let's try to find the GMETRIC_TARGET ourselves first from GMOND_CONF
293        #
294        gmetric_dest_ip         = ganglia_cfg.getStr( 'udp_send_channel', 'mcast_join' )
295
296        if not gmetric_dest_ip:
297
298                # Maybe unicast target then
299                #
300                gmetric_dest_ip         = ganglia_cfg.getStr( 'udp_send_channel', 'host' )
301
302        gmetric_dest_port       = gcp.getStr( 'udp_send_channel', 'port' )
303
304        if gmetric_dest_ip and gmetric_dest_port:
305
306                GMETRIC_TARGET  = '%s:%s' %( gmetric_dest_ip, gmetric_dest_port )
307        else:
308
309                debug_msg( 0, "WARNING: Can't parse udp_send_channel from: '%s'" %GMOND_CONF )
310
311                # Couldn't figure it out: let's see if it's in our jobmond.conf
312                #
313                try:
314
315                        GMETRIC_TARGET  = cfg.get( 'DEFAULT', 'GMETRIC_TARGET' )
316
317                # Guess not: now just give up
318                #
319                except ConfigParser.NoOptionError:
320
321                        GMETRIC_TARGET  = None
322
323                        debug_msg( 0, "ERROR: GMETRIC_TARGET not set: internal Gmetric handling aborted. Failing back to DEPRECATED use of gmond.conf/gmetric binary. This will slow down jobmond significantly!" )
324
325        gmetric_bin     = findGmetric()
326
327        if gmetric_bin:
328
329                GMETRIC_BINARY          = gmetric_bin
330        else:
331                debug_msg( 0, "WARNING: Can't find gmetric binary anywhere in $PATH" )
332
333                try:
334
335                        GMETRIC_BINARY          = cfg.get( 'DEFAULT', 'GMETRIC_BINARY' )
336
337                except ConfigParser.NoOptionError:
338
339                        debug_msg( 0, "FATAL ERROR: GMETRIC_BINARY not set and not in $PATH" )
340                        sys.exit( 1 )
341
342        DETECT_TIME_DIFFS       = cfg.getboolean( 'DEFAULT', 'DETECT_TIME_DIFFS' )
343
344        BATCH_HOST_TRANSLATE    = getlist( cfg.get( 'DEFAULT', 'BATCH_HOST_TRANSLATE' ) )
345
346        try:
347
348                BATCH_API       = cfg.get( 'DEFAULT', 'BATCH_API' )
349
350        except ConfigParser.NoOptionError, detail:
351
352                if BATCH_SERVER and api_guess:
353
354                        BATCH_API       = api_guess
355                else:
356                        debug_msg( 0, "FATAL ERROR: BATCH_API not set and can't make guess" )
357                        sys.exit( 1 )
358
359        try:
360
361                QUEUE           = getlist( cfg.get( 'DEFAULT', 'QUEUE' ) )
362
363        except ConfigParser.NoOptionError, detail:
364
365                QUEUE           = None
366
367        return True
368
369def fqdn_parts (fqdn):
370
371        """Return pair of host and domain for fully-qualified domain name arg."""
372
373        parts = fqdn.split (".")
374
375        return (parts[0], string.join(parts[1:], "."))
376
377METRIC_MAX_VAL_LEN = 900
378
379class DataProcessor:
380
381        """Class for processing of data"""
382
383        binary = None
384
385        def __init__( self, binary=None ):
386
387                """Remember alternate binary location if supplied"""
388
389                global GMETRIC_BINARY
390
391                if binary:
392                        self.binary = binary
393
394                if not self.binary:
395                        self.binary = GMETRIC_BINARY
396
397                # Timeout for XML
398                #
399                # From ganglia's documentation:
400                #
401                # 'A metric will be deleted DMAX seconds after it is received, and
402                # DMAX=0 means eternal life.'
403
404                self.dmax = str( int( int( BATCH_POLL_INTERVAL ) * 2 ) )
405
406                if GMOND_CONF:
407
408                        incompatible = self.checkGmetricVersion()
409
410                        if incompatible:
411
412                                debug_msg( 0, 'Gmetric version not compatible, please upgrade to at least 3.0.1' )
413                                sys.exit( 1 )
414
415        def checkGmetricVersion( self ):
416
417                """
418                Check version of gmetric is at least 3.0.1
419                for the syntax we use
420                """
421
422                global METRIC_MAX_VAL_LEN
423
424                incompatible    = 0
425
426                gfp             = os.popen( self.binary + ' --version' )
427                lines           = gfp.readlines()
428
429                gfp.close()
430
431                for line in lines:
432
433                        line = line.split( ' ' )
434
435                        if len( line ) == 2 and str( line ).find( 'gmetric' ) != -1:
436                       
437                                gmetric_version = line[1].split( '\n' )[0]
438
439                                version_major   = int( gmetric_version.split( '.' )[0] )
440                                version_minor   = int( gmetric_version.split( '.' )[1] )
441                                version_patch   = int( gmetric_version.split( '.' )[2] )
442
443                                incompatible    = 0
444
445                                if version_major < 3:
446
447                                        incompatible = 1
448                               
449                                elif version_major == 3:
450
451                                        if version_minor == 0:
452
453                                                if version_patch < 1:
454                                               
455                                                        incompatible = 1
456
457                                                # Gmetric 3.0.1 >< 3.0.3 had a bug in the max metric length
458                                                #
459                                                if version_patch < 3:
460
461                                                        METRIC_MAX_VAL_LEN = 900
462
463                                                elif version_patch >= 3:
464
465                                                        METRIC_MAX_VAL_LEN = 1400
466
467                return incompatible
468
469        def multicastGmetric( self, metricname, metricval, valtype='string', units='' ):
470
471                """Call gmetric binary and multicast"""
472
473                cmd = self.binary
474
475                if GMETRIC_TARGET:
476
477                        GMETRIC_TARGET_HOST     = GMETRIC_TARGET.split( ':' )[0]
478                        GMETRIC_TARGET_PORT     = GMETRIC_TARGET.split( ':' )[1]
479
480                        metric_debug            = "[gmetric] name: %s - val: %s - dmax: %s" %( str( metricname ), str( metricval ), str( self.dmax ) )
481
482                        debug_msg( 10, printTime() + ' ' + metric_debug)
483
484                        gm = Gmetric( GMETRIC_TARGET_HOST, GMETRIC_TARGET_PORT )
485
486                        gm.send( str( metricname ), str( metricval ), str( self.dmax ), valtype, units )
487
488                else:
489                        try:
490                                cmd = cmd + ' -c' + GMOND_CONF
491
492                        except NameError:
493
494                                debug_msg( 10, 'Assuming /etc/gmond.conf for gmetric cmd (omitting)' )
495
496                        cmd = cmd + ' -n' + str( metricname )+ ' -v"' + str( metricval )+ '" -t' + str( valtype ) + ' -d' + str( self.dmax )
497
498                        if len( units ) > 0:
499
500                                cmd = cmd + ' -u"' + units + '"'
501
502                        debug_msg( 10, printTime() + ' ' + cmd )
503
504                        os.system( cmd )
505
506class DataGatherer:
507
508        """Skeleton class for batch system DataGatherer"""
509
510        def printJobs( self, jobs ):
511
512                """Print a jobinfo overview"""
513
514                for name, attrs in self.jobs.items():
515
516                        print 'job %s' %(name)
517
518                        for name, val in attrs.items():
519
520                                print '\t%s = %s' %( name, val )
521
522        def printJob( self, jobs, job_id ):
523
524                """Print job with job_id from jobs"""
525
526                print 'job %s' %(job_id)
527
528                for name, val in jobs[ job_id ].items():
529
530                        print '\t%s = %s' %( name, val )
531
532        def getAttr( self, attrs, name ):
533
534                """Return certain attribute from dictionary, if exists"""
535
536                if attrs.has_key( name ):
537
538                        return attrs[ name ]
539                else:
540                        return ''
541
542        def jobDataChanged( self, jobs, job_id, attrs ):
543
544                """Check if job with attrs and job_id in jobs has changed"""
545
546                if jobs.has_key( job_id ):
547
548                        oldData = jobs[ job_id ]       
549                else:
550                        return 1
551
552                for name, val in attrs.items():
553
554                        if oldData.has_key( name ):
555
556                                if oldData[ name ] != attrs[ name ]:
557
558                                        return 1
559
560                        else:
561                                return 1
562
563                return 0
564
565        def submitJobData( self ):
566
567                """Submit job info list"""
568
569                global BATCH_API
570
571                self.dp.multicastGmetric( 'MONARCH-HEARTBEAT', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
572
573                running_jobs    = 0
574                queued_jobs     = 0
575
576                # Count how many running/queued jobs we found
577                #
578                for jobid, jobattrs in self.jobs.items():
579
580                        if jobattrs[ 'status' ] == 'Q':
581
582                                queued_jobs += 1
583
584                        elif jobattrs[ 'status' ] == 'R':
585
586                                running_jobs += 1
587
588                # Report running/queued jobs as seperate metric for a nice RRD graph
589                #
590                self.dp.multicastGmetric( 'MONARCH-RJ', str( running_jobs ), 'uint32', 'jobs' )
591                self.dp.multicastGmetric( 'MONARCH-QJ', str( queued_jobs ), 'uint32', 'jobs' )
592
593                # Report down/offline nodes in batch (PBS only ATM)
594                #
595                if BATCH_API == 'pbs':
596
597                        domain          = fqdn_parts( socket.getfqdn() )[1]
598
599                        downed_nodes    = list()
600                        offline_nodes   = list()
601               
602                        l               = ['state']
603               
604                        for name, node in self.pq.getnodes().items():
605
606                                if ( node[ 'state' ].find( "down" ) != -1 ):
607
608                                        downed_nodes.append( name )
609
610                                if ( node[ 'state' ].find( "offline" ) != -1 ):
611
612                                        offline_nodes.append( name )
613
614                        downnodeslist           = do_nodelist( downed_nodes )
615                        offlinenodeslist        = do_nodelist( offline_nodes )
616
617                        down_str        = 'nodes=%s domain=%s reported=%s' %( string.join( downnodeslist, ';' ), domain, str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
618                        offl_str        = 'nodes=%s domain=%s reported=%s' %( string.join( offlinenodeslist, ';' ), domain, str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
619                        self.dp.multicastGmetric( 'MONARCH-DOWN'   , down_str )
620                        self.dp.multicastGmetric( 'MONARCH-OFFLINE', offl_str )
621
622                # Now let's spread the knowledge
623                #
624                for jobid, jobattrs in self.jobs.items():
625
626                        # Make gmetric values for each job: respect max gmetric value length
627                        #
628                        gmetric_val             = self.compileGmetricVal( jobid, jobattrs )
629                        metric_increment        = 0
630
631                        # If we have more job info than max gmetric value length allows, split it up
632                        # amongst multiple metrics
633                        #
634                        for val in gmetric_val:
635
636                                self.dp.multicastGmetric( 'MONARCH-JOB-' + jobid + '-' + str(metric_increment), val )
637
638                                # Increase follow number if this jobinfo is split up amongst more than 1 gmetric
639                                #
640                                metric_increment        = metric_increment + 1
641
642        def compileGmetricVal( self, jobid, jobattrs ):
643
644                """Create a val string for gmetric of jobinfo"""
645
646                gval_lists      = [ ]
647                val_list        = { }
648
649                for val_name, val_value in jobattrs.items():
650
651                        # These are our own metric names, i.e.: status, start_timestamp, etc
652                        #
653                        val_list_names_len      = len( string.join( val_list.keys() ) ) + len(val_list.keys())
654
655                        # These are their corresponding values
656                        #
657                        val_list_vals_len       = len( string.join( val_list.values() ) ) + len(val_list.values())
658
659                        if val_name == 'nodes' and jobattrs['status'] == 'R':
660
661                                node_str = None
662
663                                for node in val_value:
664
665                                        if node_str:
666
667                                                node_str = node_str + ';' + node
668                                        else:
669                                                node_str = node
670
671                                        # Make sure if we add this new info, that the total metric's value length does not exceed METRIC_MAX_VAL_LEN
672                                        #
673                                        if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(node_str) ) > METRIC_MAX_VAL_LEN:
674
675                                                # It's too big, we need to make a new gmetric for the additional info
676                                                #
677                                                val_list[ val_name ]    = node_str
678
679                                                gval_lists.append( val_list )
680
681                                                val_list                = { }
682                                                node_str                = None
683
684                                val_list[ val_name ]    = node_str
685
686                                gval_lists.append( val_list )
687
688                                val_list                = { }
689
690                        elif val_value != '':
691
692                                # Make sure if we add this new info, that the total metric's value length does not exceed METRIC_MAX_VAL_LEN
693                                #
694                                if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(str(val_value)) ) > METRIC_MAX_VAL_LEN:
695
696                                        # It's too big, we need to make a new gmetric for the additional info
697                                        #
698                                        gval_lists.append( val_list )
699
700                                        val_list                = { }
701
702                                val_list[ val_name ]    = val_value
703
704                if len( val_list ) > 0:
705
706                        gval_lists.append( val_list )
707
708                str_list        = [ ]
709
710                # Now append the value names and values together, i.e.: stop_timestamp=value, etc
711                #
712                for val_list in gval_lists:
713
714                        my_val_str      = None
715
716                        for val_name, val_value in val_list.items():
717
718                                if my_val_str:
719
720                                        my_val_str = my_val_str + ' ' + val_name + '=' + val_value
721                                else:
722                                        my_val_str = val_name + '=' + val_value
723
724                        str_list.append( my_val_str )
725
726                return str_list
727
728        def daemon( self ):
729
730                """Run as daemon forever"""
731
732                # Fork the first child
733                #
734                pid = os.fork()
735                if pid > 0:
736                        sys.exit(0)  # end parent
737
738                # creates a session and sets the process group ID
739                #
740                os.setsid()
741
742                # Fork the second child
743                #
744                pid = os.fork()
745                if pid > 0:
746                        sys.exit(0)  # end parent
747
748                write_pidfile()
749
750                # Go to the root directory and set the umask
751                #
752                os.chdir('/')
753                os.umask(0)
754
755                sys.stdin.close()
756                sys.stdout.close()
757                sys.stderr.close()
758
759                os.open('/dev/null', os.O_RDWR)
760                os.dup2(0, 1)
761                os.dup2(0, 2)
762
763                self.run()
764
765        def run( self ):
766
767                """Main thread"""
768
769                while ( 1 ):
770               
771                        self.getJobData()
772                        self.submitJobData()
773                        time.sleep( BATCH_POLL_INTERVAL )       
774
775# SGE code by Dave Love <fx@gnu.org>.  Tested with SGE 6.0u8 and 6.0u11.
776# Probably needs modification for SGE 6.1.  See also the fixmes.
777
778class NoJobs (Exception):
779        """Exception raised by empty job list in qstat output."""
780        pass
781
782class SgeQstatXMLParser(xml.sax.handler.ContentHandler):
783        """SAX handler for XML output from Sun Grid Engine's `qstat'."""
784
785        def __init__(self):
786                self.value = ""
787                self.joblist = []
788                self.job = {}
789                self.queue = ""
790                self.in_joblist = False
791                self.lrequest = False
792                xml.sax.handler.ContentHandler.__init__(self)
793
794        # The structure of the output is as follows.  Unfortunately
795        # it's voluminous, and probably doesn't scale to large
796        # clusters/queues.
797
798        # <detailed_job_info  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
799        #   <djob_info>
800        #     <qmaster_response>  <!-- job -->
801        #       ...
802        #       <JB_ja_template> 
803        #         <ulong_sublist>
804        #         ...             <!-- start_time, state ... -->
805        #         </ulong_sublist>
806        #       </JB_ja_template> 
807        #       <JB_ja_tasks>
808        #         <ulong_sublist>
809        #           ...           <!-- task info
810        #         </ulong_sublist>
811        #         ...
812        #       </JB_ja_tasks>
813        #       ...
814        #     </qmaster_response>
815        #   </djob_info>
816        #   <messages>
817        #   ...
818
819        # NB.  We might treat each task as a separate job, like
820        # straight qstat output, but the web interface expects jobs to
821        # be identified by integers, not, say, <job number>.<task>.
822
823        # So, I lied.  If the job list is empty, we get invalid XML
824        # like this, which we need to defend against:
825
826        # <unknown_jobs  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
827        #   <>
828        #     <ST_name>*</ST_name>
829        #   </>
830        # </unknown_jobs>
831
832        def startElement(self, name, attrs):
833                self.value = ""
834                if name == "djob_info": # job list
835                        self.in_joblist = True
836                elif name == "qmaster_response" and self.in_joblist: # job
837                        self.job = {"job_state": "U", "slots": 0,
838                                    "nodes": [], "queued_timestamp": "",
839                                    "queued_timestamp": "", "queue": "",
840                                    "ppn": "0", "RN_max": 0,
841                                    # fixme in endElement
842                                    "requested_memory": 0, "requested_time": 0
843                                    }
844                        self.joblist.append(self.job)
845                elif name == "qstat_l_requests": # resource request
846                        self.lrequest = True
847                elif name == "unknown_jobs":
848                        raise NoJobs
849
850        def characters(self, ch):
851                self.value += ch
852
853        def endElement(self, name): 
854                """Snarf job elements contents into job dictionary.
855                   Translate keys if appropriate."""
856
857                name_trans = {
858                  "JB_job_number": "number",
859                  "JB_job_name": "name", "JB_owner": "owner",
860                  "queue_name": "queue", "JAT_start_time": "start_timestamp",
861                  "JB_submission_time": "queued_timestamp"
862                  }
863                value = self.value
864
865                if name == "djob_info":
866                        self.in_joblist = False
867                        self.job = {}
868                elif name == "JAT_master_queue":
869                        self.job["queue"] = value.split("@")[0]
870                elif name == "JG_qhostname":
871                        if not (value in self.job["nodes"]):
872                                self.job["nodes"].append(value)
873                elif name == "JG_slots": # slots in use
874                        self.job["slots"] += int(value)
875                elif name == "RN_max": # requested slots (tasks or parallel)
876                        self.job["RN_max"] = max (self.job["RN_max"],
877                                                  int(value))
878                elif name == "JAT_state": # job state (bitwise or)
879                        value = int (value)
880                        # Status values from sge_jobL.h
881                        #define JIDLE                   0x00000000
882                        #define JHELD                   0x00000010
883                        #define JMIGRATING              0x00000020
884                        #define JQUEUED                 0x00000040
885                        #define JRUNNING                0x00000080
886                        #define JSUSPENDED              0x00000100
887                        #define JTRANSFERING            0x00000200
888                        #define JDELETED                0x00000400
889                        #define JWAITING                0x00000800
890                        #define JEXITING                0x00001000
891                        #define JWRITTEN                0x00002000
892                        #define JSUSPENDED_ON_THRESHOLD 0x00010000
893                        #define JFINISHED               0x00010000
894                        if value & 0x80:
895                                self.job["status"] = "R"
896                        elif value & 0x40:
897                                self.job["status"] = "Q"
898                        else:
899                                self.job["status"] = "O" # `other'
900                elif name == "CE_name" and self.lrequest and self.value in \
901                            ("h_cpu", "s_cpu", "cpu", "h_core", "s_core"):
902                        # We're in a container for an interesting resource
903                        # request; record which type.
904                        self.lrequest = self.value
905                elif name == "CE_doubleval" and self.lrequest:
906                        # if we're in a container for an interesting
907                        # resource request, use the maxmimum of the hard
908                        # and soft requests to record the requested CPU
909                        # or core.  Fixme:  I'm not sure if this logic is
910                        # right.
911                        if self.lrequest in ("h_core", "s_core"):
912                                self.job["requested_memory"] = \
913                                    max (float (value),
914                                         self.job["requested_memory"])
915                        # Fixme:  Check what cpu means, c.f [hs]_cpu.
916                        elif self.lrequest in ("h_cpu", "s_cpu", "cpu"):
917                                self.job["requested_time"] = \
918                                    max (float (value),
919                                         self.job["requested_time"])
920                elif name == "qstat_l_requests":
921                        self.lrequest = False
922                elif self.job and self.in_joblist:
923                        if name in name_trans:
924                                name = name_trans[name]
925                                self.job[name] = value
926
927# Abstracted from PBS original.
928# Fixme:  Is it worth (or appropriate for PBS) sorting the result?
929#
930def do_nodelist( nodes ):
931
932        """Translate node list as appropriate."""
933
934        nodeslist               = [ ]
935        my_domain               = fqdn_parts( socket.getfqdn() )[1]
936
937        for node in nodes:
938
939                host            = node.split( '/' )[0] # not relevant for SGE
940                h, host_domain  = fqdn_parts(host)
941
942                if host_domain == my_domain:
943
944                        host    = h
945
946                if nodeslist.count( host ) == 0:
947
948                        for translate_pattern in BATCH_HOST_TRANSLATE:
949
950                                if translate_pattern.find( '/' ) != -1:
951
952                                        translate_orig  = \
953                                            translate_pattern.split( '/' )[1]
954                                        translate_new   = \
955                                            translate_pattern.split( '/' )[2]
956                                        host = re.sub( translate_orig,
957                                                       translate_new, host )
958                        if not host in nodeslist:
959                                nodeslist.append( host )
960        return nodeslist
961
962class SgeDataGatherer(DataGatherer):
963
964        jobs = {}
965
966        def __init__( self ):
967                self.jobs = {}
968                self.timeoffset = 0
969                self.dp = DataProcessor()
970
971        def getJobData( self ):
972                """Gather all data on current jobs in SGE"""
973
974                import popen2
975
976                self.cur_time = 0
977                queues = ""
978                if QUEUE:       # only for specific queues
979                        # Fixme:  assumes queue names don't contain single
980                        # quote or comma.  Don't know what the SGE rules are.
981                        queues = " -q '" + string.join (QUEUE, ",") + "'"
982                # Note the comment in SgeQstatXMLParser about scaling with
983                # this method of getting data.  I haven't found better one.
984                # Output with args `-xml -ext -f -r' is easier to parse
985                # in some ways, harder in others, but it doesn't provide
986                # the submission time, at least.
987                piping = popen2.Popen3("qstat -u '*' -j '*' -xml" + queues,
988                                       True)
989                qstatparser = SgeQstatXMLParser()
990                parse_err = 0
991                try:
992                        xml.sax.parse(piping.fromchild, qstatparser)
993                except NoJobs:
994                        pass
995                except:
996                        parse_err = 1
997                if piping.wait():
998                        debug_msg(10,
999                                  "qstat error, skipping until next polling interval: "
1000                                  + piping.childerr.readline())
1001                        return None
1002                elif parse_err:
1003                        debug_msg(10, "Bad XML output from qstat"())
1004                        exit (1)
1005                for f in piping.fromchild, piping.tochild, piping.childerr:
1006                        f.close()
1007                self.cur_time = time.time()
1008                jobs_processed = []
1009                for job in qstatparser.joblist:
1010                        job_id = job["number"]
1011                        if job["status"] in [ 'Q', 'R' ]:
1012                                jobs_processed.append(job_id)
1013                        if job["status"] == "R":
1014                                job["nodes"] = do_nodelist (job["nodes"])
1015                                # Fixme: Is this right?
1016                                job["ppn"] = float(job["slots"]) / \
1017                                    len(job["nodes"])
1018                                if DETECT_TIME_DIFFS:
1019                                        # If a job start is later than our
1020                                        # current date, that must mean
1021                                        # the SGE server's time is later
1022                                        # than our local time.
1023                                        start_timestamp = \
1024                                            int (job["start_timestamp"])
1025                                        if start_timestamp > \
1026                                                    int(self.cur_time) + \
1027                                                    int(self.timeoffset):
1028
1029                                                self.timeoffset = \
1030                                                    start_timestamp - \
1031                                                    int(self.cur_time)
1032                        else:
1033                                # fixme: Note sure what this should be:
1034                                job["ppn"] = job["RN_max"]
1035                                job["nodes"] = "1"
1036
1037                        myAttrs = {}
1038                        for attr in ["name", "queue", "owner",
1039                                     "requested_time", "status",
1040                                     "requested_memory", "ppn",
1041                                     "start_timestamp", "queued_timestamp"]:
1042                                myAttrs[attr] = str(job[attr])
1043                        myAttrs["nodes"] = job["nodes"]
1044                        myAttrs["reported"] = str(int(self.cur_time) + \
1045                                                  int(self.timeoffset))
1046                        myAttrs["domain"] = fqdn_parts(socket.getfqdn())[1]
1047                        myAttrs["poll_interval"] = str(BATCH_POLL_INTERVAL)
1048
1049                        if self.jobDataChanged(self.jobs, job_id, myAttrs) \
1050                                    and myAttrs["status"] in ["R", "Q"]:
1051                                self.jobs[job_id] = myAttrs
1052                for id, attrs in self.jobs.items():
1053                        if id not in jobs_processed:
1054                                del self.jobs[id]
1055
1056class PbsDataGatherer( DataGatherer ):
1057
1058        """This is the DataGatherer for PBS and Torque"""
1059
1060        global PBSQuery
1061
1062        def __init__( self ):
1063
1064                """Setup appropriate variables"""
1065
1066                self.jobs       = { }
1067                self.timeoffset = 0
1068                self.dp         = DataProcessor()
1069
1070                self.initPbsQuery()
1071
1072        def initPbsQuery( self ):
1073
1074                self.pq         = None
1075
1076                if( BATCH_SERVER ):
1077
1078                        self.pq         = PBSQuery( BATCH_SERVER )
1079                else:
1080                        self.pq         = PBSQuery()
1081
1082        def getJobData( self ):
1083
1084                """Gather all data on current jobs in Torque"""
1085
1086                joblist         = {}
1087                self.cur_time   = 0
1088
1089                try:
1090                        joblist         = self.pq.getjobs()
1091                        self.cur_time   = time.time()
1092
1093                except PBSError, detail:
1094
1095                        debug_msg( 10, "Caught PBS unavailable, skipping until next polling interval: " + str( detail ) )
1096                        return None
1097
1098                jobs_processed  = [ ]
1099
1100                for name, attrs in joblist.items():
1101                        display_queue           = 1
1102                        job_id                  = name.split( '.' )[0]
1103
1104                        name                    = self.getAttr( attrs, 'Job_Name' )
1105                        queue                   = self.getAttr( attrs, 'queue' )
1106
1107                        if QUEUE:
1108                                for q in QUEUE:
1109                                        if q == queue:
1110                                                display_queue = 1
1111                                                break
1112                                        else:
1113                                                display_queue = 0
1114                                                continue
1115                        if display_queue == 0:
1116                                continue
1117
1118
1119                        owner                   = self.getAttr( attrs, 'Job_Owner' ).split( '@' )[0]
1120                        requested_time          = self.getAttr( attrs, 'Resource_List.walltime' )
1121                        requested_memory        = self.getAttr( attrs, 'Resource_List.mem' )
1122
1123                        mynoderequest           = self.getAttr( attrs, 'Resource_List.nodes' )
1124
1125                        ppn                     = ''
1126
1127                        if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
1128
1129                                mynoderequest_fields    = mynoderequest.split( ':' )
1130
1131                                for mynoderequest_field in mynoderequest_fields:
1132
1133                                        if mynoderequest_field.find( 'ppn' ) != -1:
1134
1135                                                ppn     = mynoderequest_field.split( 'ppn=' )[1]
1136
1137                        status                  = self.getAttr( attrs, 'job_state' )
1138
1139                        if status in [ 'Q', 'R' ]:
1140
1141                                jobs_processed.append( job_id )
1142
1143                        queued_timestamp        = self.getAttr( attrs, 'ctime' )
1144
1145                        if status == 'R':
1146
1147                                start_timestamp         = self.getAttr( attrs, 'mtime' )
1148                                nodes                   = self.getAttr( attrs, 'exec_host' ).split( '+' )
1149
1150                                nodeslist               = do_nodelist( nodes )
1151
1152                                if DETECT_TIME_DIFFS:
1153
1154                                        # If a job start if later than our current date,
1155                                        # that must mean the Torque server's time is later
1156                                        # than our local time.
1157                               
1158                                        if int( start_timestamp ) > int( int( self.cur_time ) + int( self.timeoffset ) ):
1159
1160                                                self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
1161
1162                        elif status == 'Q':
1163
1164                                # 'mynodequest' can be a string in the following syntax according to the
1165                                # Torque Administator's manual:
1166                                #
1167                                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1168                                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1169                                # etc
1170                                #
1171
1172                                #
1173                                # For now we only count the amount of nodes request and ignore properties
1174                                #
1175
1176                                start_timestamp         = ''
1177                                count_mynodes           = 0
1178
1179                                for node in mynoderequest.split( '+' ):
1180
1181                                        # Just grab the {node_count|hostname} part and ignore properties
1182                                        #
1183                                        nodepart        = node.split( ':' )[0]
1184
1185                                        # Let's assume a node_count value
1186                                        #
1187                                        numeric_node    = 1
1188
1189                                        # Chop the value up into characters
1190                                        #
1191                                        for letter in nodepart:
1192
1193                                                # If this char is not a digit (0-9), this must be a hostname
1194                                                #
1195                                                if letter not in string.digits:
1196
1197                                                        numeric_node    = 0
1198
1199                                        # If this is a hostname, just count this as one (1) node
1200                                        #
1201                                        if not numeric_node:
1202
1203                                                count_mynodes   = count_mynodes + 1
1204                                        else:
1205
1206                                                # If this a number, it must be the node_count
1207                                                # and increase our count with it's value
1208                                                #
1209                                                try:
1210                                                        count_mynodes   = count_mynodes + int( nodepart )
1211
1212                                                except ValueError, detail:
1213
1214                                                        # When we arrive here I must be bugged or very confused
1215                                                        # THIS SHOULD NOT HAPPEN!
1216                                                        #
1217                                                        debug_msg( 10, str( detail ) )
1218                                                        debug_msg( 10, "Encountered weird node in Resources_List?!" )
1219                                                        debug_msg( 10, 'nodepart = ' + str( nodepart ) )
1220                                                        debug_msg( 10, 'job = ' + str( name ) )
1221                                                        debug_msg( 10, 'attrs = ' + str( attrs ) )
1222                                               
1223                                nodeslist       = str( count_mynodes )
1224                        else:
1225                                start_timestamp = ''
1226                                nodeslist       = ''
1227
1228                        myAttrs                         = { }
1229
1230                        myAttrs[ 'name' ]               = str( name )
1231                        myAttrs[ 'queue' ]              = str( queue )
1232                        myAttrs[ 'owner' ]              = str( owner )
1233                        myAttrs[ 'requested_time' ]     = str( requested_time )
1234                        myAttrs[ 'requested_memory' ]   = str( requested_memory )
1235                        myAttrs[ 'ppn' ]                = str( ppn )
1236                        myAttrs[ 'status' ]             = str( status )
1237                        myAttrs[ 'start_timestamp' ]    = str( start_timestamp )
1238                        myAttrs[ 'queued_timestamp' ]   = str( queued_timestamp )
1239                        myAttrs[ 'reported' ]           = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1240                        myAttrs[ 'nodes' ]              = nodeslist
1241                        myAttrs[ 'domain' ]             = fqdn_parts( socket.getfqdn() )[1]
1242                        myAttrs[ 'poll_interval' ]      = str( BATCH_POLL_INTERVAL )
1243
1244                        if self.jobDataChanged( self.jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
1245
1246                                self.jobs[ job_id ]     = myAttrs
1247
1248                for id, attrs in self.jobs.items():
1249
1250                        if id not in jobs_processed:
1251
1252                                # This one isn't there anymore; toedeledoki!
1253                                #
1254                                del self.jobs[ id ]
1255
1256#
1257# Gmetric by Nick Galbreath - nickg(a.t)modp(d.o.t)com
1258# Version 1.0 - 21-April2-2007
1259# http://code.google.com/p/embeddedgmetric/
1260#
1261# Modified by: Ramon Bastiaans
1262# For the Job Monarch Project, see: https://subtrac.sara.nl/oss/jobmonarch/
1263#
1264# added: DEFAULT_TYPE for Gmetric's
1265# added: checkHostProtocol to determine if target is multicast or not
1266# changed: allow default for Gmetric constructor
1267# changed: allow defaults for all send() values except dmax
1268#
1269
1270GMETRIC_DEFAULT_TYPE    = 'string'
1271GMETRIC_DEFAULT_HOST    = '127.0.0.1'
1272GMETRIC_DEFAULT_PORT    = '8649'
1273GMETRIC_DEFAULT_UNITS   = ''
1274
1275class Gmetric:
1276
1277        global GMETRIC_DEFAULT_HOST, GMETRIC_DEFAULT_PORT
1278
1279        slope           = { 'zero' : 0, 'positive' : 1, 'negative' : 2, 'both' : 3, 'unspecified' : 4 }
1280        type            = ( '', 'string', 'uint16', 'int16', 'uint32', 'int32', 'float', 'double', 'timestamp' )
1281        protocol        = ( 'udp', 'multicast' )
1282
1283        def __init__( self, host=GMETRIC_DEFAULT_HOST, port=GMETRIC_DEFAULT_PORT ):
1284               
1285                global GMETRIC_DEFAULT_TYPE
1286
1287                self.prot       = self.checkHostProtocol( host )
1288                self.msg        = xdrlib.Packer()
1289                self.socket     = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
1290
1291                if self.prot not in self.protocol:
1292
1293                        raise ValueError( "Protocol must be one of: " + str( self.protocol ) )
1294
1295                if self.prot == 'multicast':
1296
1297                        # Set multicast options
1298                        #
1299                        self.socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20 )
1300
1301                self.hostport   = ( host, int( port ) )
1302                self.slopestr   = 'both'
1303                self.tmax       = 60
1304
1305        def checkHostProtocol( self, ip ):
1306
1307                """Detect if a ip adress is a multicast address"""
1308
1309                MULTICAST_ADDRESS_MIN   = ( "224", "0", "0", "0" )
1310                MULTICAST_ADDRESS_MAX   = ( "239", "255", "255", "255" )
1311
1312                ip_fields               = ip.split( '.' )
1313
1314                if ip_fields >= MULTICAST_ADDRESS_MIN and ip_fields <= MULTICAST_ADDRESS_MAX:
1315
1316                        return 'multicast'
1317                else:
1318                        return 'udp'
1319
1320        def send( self, name, value, dmax, typestr = '', units = '' ):
1321
1322                if len( units ) == 0:
1323                        units           = GMETRIC_DEFAULT_UNITS
1324
1325                if len( typestr ) == 0:
1326                        typestr         = GMETRIC_DEFAULT_TYPE
1327
1328                msg             = self.makexdr( name, value, typestr, units, self.slopestr, self.tmax, dmax )
1329
1330                return self.socket.sendto( msg, self.hostport )
1331
1332        def makexdr( self, name, value, typestr, unitstr, slopestr, tmax, dmax ):
1333
1334                if slopestr not in self.slope:
1335
1336                        raise ValueError( "Slope must be one of: " + str( self.slope.keys() ) )
1337
1338                if typestr not in self.type:
1339
1340                        raise ValueError( "Type must be one of: " + str( self.type ) )
1341
1342                if len( name ) == 0:
1343
1344                        raise ValueError( "Name must be non-empty" )
1345
1346                self.msg.reset()
1347                self.msg.pack_int( 0 )
1348                self.msg.pack_string( typestr )
1349                self.msg.pack_string( name )
1350                self.msg.pack_string( str( value ) )
1351                self.msg.pack_string( unitstr )
1352                self.msg.pack_int( self.slope[ slopestr ] )
1353                self.msg.pack_uint( int( tmax ) )
1354                self.msg.pack_uint( int( dmax ) )
1355
1356                return self.msg.get_buffer()
1357
1358def printTime( ):
1359
1360        """Print current time/date in human readable format for log/debug"""
1361
1362        return time.strftime("%a, %d %b %Y %H:%M:%S")
1363
1364def debug_msg( level, msg ):
1365
1366        """Print msg if at or above current debug level"""
1367
1368        global DAEMONIZE, DEBUG_LEVEL, SYSLOG_LEVEL
1369
1370        if (not DAEMONIZE and DEBUG_LEVEL >= level):
1371                sys.stderr.write( msg + '\n' )
1372
1373        if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
1374                syslog.syslog( msg )
1375
1376def write_pidfile():
1377
1378        # Write pidfile if PIDFILE is set
1379        #
1380        if PIDFILE:
1381
1382                pid     = os.getpid()
1383
1384                pidfile = open( PIDFILE, 'w' )
1385
1386                pidfile.write( str( pid ) )
1387                pidfile.close()
1388
1389def main():
1390
1391        """Application start"""
1392
1393        global PBSQuery, PBSError
1394        global SYSLOG_FACILITY, USE_SYSLOG, BATCH_API, DAEMONIZE
1395
1396        if not processArgs( sys.argv[1:] ):
1397
1398                sys.exit( 1 )
1399
1400        # Load appropriate DataGatherer depending on which BATCH_API is set
1401        # and any required modules for the Gatherer
1402        #
1403        if BATCH_API == 'pbs':
1404
1405                try:
1406                        from PBSQuery import PBSQuery, PBSError
1407
1408                except ImportError:
1409
1410                        debug_msg( 0, "FATAL ERROR: BATCH_API set to 'pbs' but python module 'pbs_python' is not installed" )
1411                        sys.exit( 1 )
1412
1413                gather = PbsDataGatherer()
1414
1415        elif BATCH_API == 'sge':
1416
1417                # Tested with SGE 6.0u11.
1418#               debug_msg( 0, "FATAL ERROR: BATCH_API 'sge' implementation is currently broken, check future releases" )
1419
1420#               sys.exit( 1 )
1421
1422                gather = SgeDataGatherer()
1423
1424        else:
1425                debug_msg( 0, "FATAL ERROR: unknown BATCH_API '" + BATCH_API + "' is not supported" )
1426
1427                sys.exit( 1 )
1428
1429        if( DAEMONIZE and USE_SYSLOG ):
1430
1431                syslog.openlog( 'jobmond', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
1432
1433
1434        if DAEMONIZE:
1435
1436                gather.daemon()
1437        else:
1438                gather.run()
1439
1440# wh00t? someone started me! :)
1441#
1442if __name__ == '__main__':
1443        main()
Note: See TracBrowser for help on using the repository browser.