source: trunk/jobmond/jobmond.py @ 552

Last change on this file since 552 was 525, checked in by bastiaans, 16 years ago

jobmond/jobmond.py:

  • changed countDuplicateList: previous function gives a error in python2.3
  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 42.6 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 525 2008-03-19 09:48:11Z 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       = ganglia_cfg.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
1056# LSF code by Mahmoud Hanafi <hanafim@users.sourceforge.nt>
1057# Requres LSFObject http://sourceforge.net/projects/lsfobject
1058#
1059class LsfDataGatherer(DataGatherer):
1060
1061        """This is the DataGatherer for LSf"""
1062
1063        global lsfObject
1064
1065        def __init__( self ):
1066
1067                self.jobs = { }
1068                self.timeoffset = 0
1069                self.dp = DataProcessor()
1070                self.initLsfQuery()
1071
1072        def _countDuplicatesInList( self, dupedList ):
1073
1074                countDupes      = { }
1075
1076                for item in dupedList:
1077
1078                        if not countDupes.has_key( item ):
1079
1080                                countDupes[ item ]      = 1
1081                        else:
1082                                countDupes[ item ]      = countDupes[ item ] + 1
1083
1084                dupeCountList   = [ ]
1085
1086                for item, count in countDupes.items():
1087
1088                        dupeCountList.append( ( item, count ) )
1089
1090                return dupeCountList
1091#
1092#lst = ['I1','I2','I1','I3','I4','I4','I7','I7','I7','I7','I7']
1093#print _countDuplicatesInList(lst)
1094#[('I1', 2), ('I3', 1), ('I2', 1), ('I4', 2), ('I7', 5)]
1095########################
1096
1097        def initLsfQuery( self ):
1098                self.pq = None
1099                self.pq = lsfObject.jobInfoEntObject()
1100
1101        def getJobData( self, known_jobs="" ):
1102                """Gather all data on current jobs in LSF"""
1103                if len( known_jobs ) > 0:
1104                        jobs = known_jobs
1105                else:
1106                        jobs = { }
1107                joblist = {}
1108                joblist = self.pq.getJobInfo()
1109                nodelist = ''
1110
1111                self.cur_time = time.time()
1112
1113                jobs_processed = [ ]
1114
1115                for name, attrs in joblist.items():
1116                        job_id = str(name)
1117                        jobs_processed.append( job_id )
1118                        name = self.getAttr( attrs, 'jobName' )
1119                        queue = self.getAttr( self.getAttr( attrs, 'submit') , 'queue' )
1120                        owner = self.getAttr( attrs, 'user' )
1121
1122### THIS IS THE rLimit List index values
1123#define LSF_RLIMIT_CPU      0            /* cpu time in milliseconds */
1124#define LSF_RLIMIT_FSIZE    1            /* maximum file size */
1125#define LSF_RLIMIT_DATA     2            /* data size */
1126#define LSF_RLIMIT_STACK    3            /* stack size */
1127#define LSF_RLIMIT_CORE     4            /* core file size */
1128#define LSF_RLIMIT_RSS      5            /* resident set size */
1129#define LSF_RLIMIT_NOFILE   6            /* open files */
1130#define LSF_RLIMIT_OPEN_MAX 7            /* (from HP-UX) */
1131#define LSF_RLIMIT_VMEM     8            /* maximum swap mem */
1132#define LSF_RLIMIT_SWAP     8
1133#define LSF_RLIMIT_RUN      9            /* max wall-clock time limit */
1134#define LSF_RLIMIT_PROCESS  10           /* process number limit */
1135#define LSF_RLIMIT_THREAD   11           /* thread number limit (introduced in LSF6.0) */
1136#define LSF_RLIM_NLIMITS    12           /* number of resource limits */
1137
1138                        requested_time = self.getAttr( self.getAttr( attrs, 'submit') , 'rLimits' )[9]
1139                        if requested_time == -1: 
1140                                requested_time = ""
1141                        requested_memory = self.getAttr( self.getAttr( attrs, 'submit') , 'rLimits' )[8]
1142                        if requested_memory == -1: 
1143                                requested_memory = ""
1144# This tries to get proc per node. We don't support this right now
1145                        ppn = 0 #self.getAttr( self.getAttr( attrs, 'SubmitList') , 'numProessors' )
1146                        requested_cpus = self.getAttr( self.getAttr( attrs, 'submit') , 'numProcessors' )
1147                        if requested_cpus == None or requested_cpus == "":
1148                                requested_cpus = 1
1149
1150                        if QUEUE:
1151                                for q in QUEUE:
1152                                        if q == queue:
1153                                                display_queue = 1
1154                                                break
1155                                        else:
1156                                                display_queue = 0
1157                                                continue
1158                        if display_queue == 0:
1159                                continue
1160
1161                        runState = self.getAttr( attrs, 'status' )
1162                        if runState == 4:
1163                                status = 'R'
1164                        else:
1165                                status = 'Q'
1166                        queued_timestamp = self.getAttr( attrs, 'submitTime' )
1167
1168                        if status == 'R':
1169                                start_timestamp = self.getAttr( attrs, 'startTime' )
1170                                nodesCpu =  dict(self._countDuplicatesInList(self.getAttr( attrs, 'exHosts' )))
1171                                nodelist = nodesCpu.keys()
1172
1173                                if DETECT_TIME_DIFFS:
1174
1175                                        # If a job start if later than our current date,
1176                                        # that must mean the Torque server's time is later
1177                                        # than our local time.
1178
1179                                        if int(start_timestamp) > int( int(self.cur_time) + int(self.timeoffset) ):
1180
1181                                                self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
1182
1183                        elif status == 'Q':
1184                                start_timestamp = ''
1185                                count_mynodes = 0
1186                                numeric_node = 1
1187                                nodelist = ''
1188
1189                        myAttrs = { }
1190                        if name == "":
1191                                myAttrs['name'] = "none"
1192                        else:
1193                                myAttrs['name'] = name
1194
1195                        myAttrs[ 'owner' ]              = owner
1196                        myAttrs[ 'requested_time' ]     = str(requested_time)
1197                        myAttrs[ 'requested_memory' ]   = str(requested_memory)
1198                        myAttrs[ 'requested_cpus' ]     = str(requested_cpus)
1199                        myAttrs[ 'ppn' ]                = str( ppn )
1200                        myAttrs[ 'status' ]             = status
1201                        myAttrs[ 'start_timestamp' ]    = str(start_timestamp)
1202                        myAttrs[ 'queue' ]              = str(queue)
1203                        myAttrs[ 'queued_timestamp' ]   = str(queued_timestamp)
1204                        myAttrs[ 'reported' ]           = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1205                        myAttrs[ 'nodes' ]              = do_nodelist( nodelist )
1206                        myAttrs[ 'domain' ]             = fqdn_parts( socket.getfqdn() )[1]
1207                        myAttrs[ 'poll_interval' ]      = str(BATCH_POLL_INTERVAL)
1208
1209                        if self.jobDataChanged( jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
1210                                jobs[ job_id ] = myAttrs
1211
1212                                debug_msg( 10, printTime() + ' job %s state changed' %(job_id) )
1213
1214                for id, attrs in jobs.items():
1215                        if id not in jobs_processed:
1216                                # This one isn't there anymore
1217                                #
1218                                del jobs[ id ]
1219                self.jobs=jobs
1220
1221
1222class PbsDataGatherer( DataGatherer ):
1223
1224        """This is the DataGatherer for PBS and Torque"""
1225
1226        global PBSQuery, PBSError
1227
1228        def __init__( self ):
1229
1230                """Setup appropriate variables"""
1231
1232                self.jobs       = { }
1233                self.timeoffset = 0
1234                self.dp         = DataProcessor()
1235
1236                self.initPbsQuery()
1237
1238        def initPbsQuery( self ):
1239
1240                self.pq         = None
1241
1242                if( BATCH_SERVER ):
1243
1244                        self.pq         = PBSQuery( BATCH_SERVER )
1245                else:
1246                        self.pq         = PBSQuery()
1247
1248        def getJobData( self ):
1249
1250                """Gather all data on current jobs in Torque"""
1251
1252                joblist         = {}
1253                self.cur_time   = 0
1254
1255                try:
1256                        joblist         = self.pq.getjobs()
1257                        self.cur_time   = time.time()
1258
1259                except PBSError, detail:
1260
1261                        debug_msg( 10, "Caught PBS unavailable, skipping until next polling interval: " + str( detail ) )
1262                        return None
1263
1264                jobs_processed  = [ ]
1265
1266                for name, attrs in joblist.items():
1267                        display_queue           = 1
1268                        job_id                  = name.split( '.' )[0]
1269
1270                        name                    = self.getAttr( attrs, 'Job_Name' )
1271                        queue                   = self.getAttr( attrs, 'queue' )
1272
1273                        if QUEUE:
1274                                for q in QUEUE:
1275                                        if q == queue:
1276                                                display_queue = 1
1277                                                break
1278                                        else:
1279                                                display_queue = 0
1280                                                continue
1281                        if display_queue == 0:
1282                                continue
1283
1284
1285                        owner                   = self.getAttr( attrs, 'Job_Owner' ).split( '@' )[0]
1286                        requested_time          = self.getAttr( attrs, 'Resource_List.walltime' )
1287                        requested_memory        = self.getAttr( attrs, 'Resource_List.mem' )
1288
1289                        mynoderequest           = self.getAttr( attrs, 'Resource_List.nodes' )
1290
1291                        ppn                     = ''
1292
1293                        if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
1294
1295                                mynoderequest_fields    = mynoderequest.split( ':' )
1296
1297                                for mynoderequest_field in mynoderequest_fields:
1298
1299                                        if mynoderequest_field.find( 'ppn' ) != -1:
1300
1301                                                ppn     = mynoderequest_field.split( 'ppn=' )[1]
1302
1303                        status                  = self.getAttr( attrs, 'job_state' )
1304
1305                        if status in [ 'Q', 'R' ]:
1306
1307                                jobs_processed.append( job_id )
1308
1309                        queued_timestamp        = self.getAttr( attrs, 'ctime' )
1310
1311                        if status == 'R':
1312
1313                                start_timestamp         = self.getAttr( attrs, 'mtime' )
1314                                nodes                   = self.getAttr( attrs, 'exec_host' ).split( '+' )
1315
1316                                nodeslist               = do_nodelist( nodes )
1317
1318                                if DETECT_TIME_DIFFS:
1319
1320                                        # If a job start if later than our current date,
1321                                        # that must mean the Torque server's time is later
1322                                        # than our local time.
1323                               
1324                                        if int( start_timestamp ) > int( int( self.cur_time ) + int( self.timeoffset ) ):
1325
1326                                                self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
1327
1328                        elif status == 'Q':
1329
1330                                # 'mynodequest' can be a string in the following syntax according to the
1331                                # Torque Administator's manual:
1332                                #
1333                                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1334                                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1335                                # etc
1336                                #
1337
1338                                #
1339                                # For now we only count the amount of nodes request and ignore properties
1340                                #
1341
1342                                start_timestamp         = ''
1343                                count_mynodes           = 0
1344
1345                                for node in mynoderequest.split( '+' ):
1346
1347                                        # Just grab the {node_count|hostname} part and ignore properties
1348                                        #
1349                                        nodepart        = node.split( ':' )[0]
1350
1351                                        # Let's assume a node_count value
1352                                        #
1353                                        numeric_node    = 1
1354
1355                                        # Chop the value up into characters
1356                                        #
1357                                        for letter in nodepart:
1358
1359                                                # If this char is not a digit (0-9), this must be a hostname
1360                                                #
1361                                                if letter not in string.digits:
1362
1363                                                        numeric_node    = 0
1364
1365                                        # If this is a hostname, just count this as one (1) node
1366                                        #
1367                                        if not numeric_node:
1368
1369                                                count_mynodes   = count_mynodes + 1
1370                                        else:
1371
1372                                                # If this a number, it must be the node_count
1373                                                # and increase our count with it's value
1374                                                #
1375                                                try:
1376                                                        count_mynodes   = count_mynodes + int( nodepart )
1377
1378                                                except ValueError, detail:
1379
1380                                                        # When we arrive here I must be bugged or very confused
1381                                                        # THIS SHOULD NOT HAPPEN!
1382                                                        #
1383                                                        debug_msg( 10, str( detail ) )
1384                                                        debug_msg( 10, "Encountered weird node in Resources_List?!" )
1385                                                        debug_msg( 10, 'nodepart = ' + str( nodepart ) )
1386                                                        debug_msg( 10, 'job = ' + str( name ) )
1387                                                        debug_msg( 10, 'attrs = ' + str( attrs ) )
1388                                               
1389                                nodeslist       = str( count_mynodes )
1390                        else:
1391                                start_timestamp = ''
1392                                nodeslist       = ''
1393
1394                        myAttrs                         = { }
1395
1396                        myAttrs[ 'name' ]               = str( name )
1397                        myAttrs[ 'queue' ]              = str( queue )
1398                        myAttrs[ 'owner' ]              = str( owner )
1399                        myAttrs[ 'requested_time' ]     = str( requested_time )
1400                        myAttrs[ 'requested_memory' ]   = str( requested_memory )
1401                        myAttrs[ 'ppn' ]                = str( ppn )
1402                        myAttrs[ 'status' ]             = str( status )
1403                        myAttrs[ 'start_timestamp' ]    = str( start_timestamp )
1404                        myAttrs[ 'queued_timestamp' ]   = str( queued_timestamp )
1405                        myAttrs[ 'reported' ]           = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1406                        myAttrs[ 'nodes' ]              = nodeslist
1407                        myAttrs[ 'domain' ]             = fqdn_parts( socket.getfqdn() )[1]
1408                        myAttrs[ 'poll_interval' ]      = str( BATCH_POLL_INTERVAL )
1409
1410                        if self.jobDataChanged( self.jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
1411
1412                                self.jobs[ job_id ]     = myAttrs
1413
1414                for id, attrs in self.jobs.items():
1415
1416                        if id not in jobs_processed:
1417
1418                                # This one isn't there anymore; toedeledoki!
1419                                #
1420                                del self.jobs[ id ]
1421
1422#
1423# Gmetric by Nick Galbreath - nickg(a.t)modp(d.o.t)com
1424# Version 1.0 - 21-April2-2007
1425# http://code.google.com/p/embeddedgmetric/
1426#
1427# Modified by: Ramon Bastiaans
1428# For the Job Monarch Project, see: https://subtrac.sara.nl/oss/jobmonarch/
1429#
1430# added: DEFAULT_TYPE for Gmetric's
1431# added: checkHostProtocol to determine if target is multicast or not
1432# changed: allow default for Gmetric constructor
1433# changed: allow defaults for all send() values except dmax
1434#
1435
1436GMETRIC_DEFAULT_TYPE    = 'string'
1437GMETRIC_DEFAULT_HOST    = '127.0.0.1'
1438GMETRIC_DEFAULT_PORT    = '8649'
1439GMETRIC_DEFAULT_UNITS   = ''
1440
1441class Gmetric:
1442
1443        global GMETRIC_DEFAULT_HOST, GMETRIC_DEFAULT_PORT
1444
1445        slope           = { 'zero' : 0, 'positive' : 1, 'negative' : 2, 'both' : 3, 'unspecified' : 4 }
1446        type            = ( '', 'string', 'uint16', 'int16', 'uint32', 'int32', 'float', 'double', 'timestamp' )
1447        protocol        = ( 'udp', 'multicast' )
1448
1449        def __init__( self, host=GMETRIC_DEFAULT_HOST, port=GMETRIC_DEFAULT_PORT ):
1450               
1451                global GMETRIC_DEFAULT_TYPE
1452
1453                self.prot       = self.checkHostProtocol( host )
1454                self.msg        = xdrlib.Packer()
1455                self.socket     = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
1456
1457                if self.prot not in self.protocol:
1458
1459                        raise ValueError( "Protocol must be one of: " + str( self.protocol ) )
1460
1461                if self.prot == 'multicast':
1462
1463                        # Set multicast options
1464                        #
1465                        self.socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20 )
1466
1467                self.hostport   = ( host, int( port ) )
1468                self.slopestr   = 'both'
1469                self.tmax       = 60
1470
1471        def checkHostProtocol( self, ip ):
1472
1473                """Detect if a ip adress is a multicast address"""
1474
1475                MULTICAST_ADDRESS_MIN   = ( "224", "0", "0", "0" )
1476                MULTICAST_ADDRESS_MAX   = ( "239", "255", "255", "255" )
1477
1478                ip_fields               = ip.split( '.' )
1479
1480                if ip_fields >= MULTICAST_ADDRESS_MIN and ip_fields <= MULTICAST_ADDRESS_MAX:
1481
1482                        return 'multicast'
1483                else:
1484                        return 'udp'
1485
1486        def send( self, name, value, dmax, typestr = '', units = '' ):
1487
1488                if len( units ) == 0:
1489                        units           = GMETRIC_DEFAULT_UNITS
1490
1491                if len( typestr ) == 0:
1492                        typestr         = GMETRIC_DEFAULT_TYPE
1493
1494                msg             = self.makexdr( name, value, typestr, units, self.slopestr, self.tmax, dmax )
1495
1496                return self.socket.sendto( msg, self.hostport )
1497
1498        def makexdr( self, name, value, typestr, unitstr, slopestr, tmax, dmax ):
1499
1500                if slopestr not in self.slope:
1501
1502                        raise ValueError( "Slope must be one of: " + str( self.slope.keys() ) )
1503
1504                if typestr not in self.type:
1505
1506                        raise ValueError( "Type must be one of: " + str( self.type ) )
1507
1508                if len( name ) == 0:
1509
1510                        raise ValueError( "Name must be non-empty" )
1511
1512                self.msg.reset()
1513                self.msg.pack_int( 0 )
1514                self.msg.pack_string( typestr )
1515                self.msg.pack_string( name )
1516                self.msg.pack_string( str( value ) )
1517                self.msg.pack_string( unitstr )
1518                self.msg.pack_int( self.slope[ slopestr ] )
1519                self.msg.pack_uint( int( tmax ) )
1520                self.msg.pack_uint( int( dmax ) )
1521
1522                return self.msg.get_buffer()
1523
1524def printTime( ):
1525
1526        """Print current time/date in human readable format for log/debug"""
1527
1528        return time.strftime("%a, %d %b %Y %H:%M:%S")
1529
1530def debug_msg( level, msg ):
1531
1532        """Print msg if at or above current debug level"""
1533
1534        global DAEMONIZE, DEBUG_LEVEL, SYSLOG_LEVEL
1535
1536        if (not DAEMONIZE and DEBUG_LEVEL >= level):
1537                sys.stderr.write( msg + '\n' )
1538
1539        if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
1540                syslog.syslog( msg )
1541
1542def write_pidfile():
1543
1544        # Write pidfile if PIDFILE is set
1545        #
1546        if PIDFILE:
1547
1548                pid     = os.getpid()
1549
1550                pidfile = open( PIDFILE, 'w' )
1551
1552                pidfile.write( str( pid ) )
1553                pidfile.close()
1554
1555def main():
1556
1557        """Application start"""
1558
1559        global PBSQuery, PBSError, lsfObject
1560        global SYSLOG_FACILITY, USE_SYSLOG, BATCH_API, DAEMONIZE
1561
1562        if not processArgs( sys.argv[1:] ):
1563
1564                sys.exit( 1 )
1565
1566        # Load appropriate DataGatherer depending on which BATCH_API is set
1567        # and any required modules for the Gatherer
1568        #
1569        if BATCH_API == 'pbs':
1570
1571                try:
1572                        from PBSQuery import PBSQuery, PBSError
1573
1574                except ImportError:
1575
1576                        debug_msg( 0, "FATAL ERROR: BATCH_API set to 'pbs' but python module 'pbs_python' is not installed" )
1577                        sys.exit( 1 )
1578
1579                gather = PbsDataGatherer()
1580
1581        elif BATCH_API == 'sge':
1582
1583                # Tested with SGE 6.0u11.
1584                #
1585                gather = SgeDataGatherer()
1586
1587        elif BATCH_API == 'lsf':
1588
1589                try:
1590                        from lsfObject import lsfObject
1591                except:
1592                        debug_msg(0, "fatal error: BATCH_API set to 'lsf' but python module is not found or installed")
1593                        sys.exit( 1)
1594
1595                gather = LsfDataGatherer()
1596
1597        else:
1598                debug_msg( 0, "FATAL ERROR: unknown BATCH_API '" + BATCH_API + "' is not supported" )
1599
1600                sys.exit( 1 )
1601
1602        if( DAEMONIZE and USE_SYSLOG ):
1603
1604                syslog.openlog( 'jobmond', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
1605
1606        if DAEMONIZE:
1607
1608                gather.daemon()
1609        else:
1610                gather.run()
1611
1612# wh00t? someone started me! :)
1613#
1614if __name__ == '__main__':
1615        main()
Note: See TracBrowser for help on using the repository browser.