source: trunk/jobmond/jobmond.py @ 373

Last change on this file since 373 was 373, checked in by bastiaans, 17 years ago

jobmond/jobmond.py:

  • added syslog support with backwards compatible config
  • Property svn:keywords set to Id
File size: 23.5 KB
RevLine 
[23]1#!/usr/bin/env python
[225]2#
3# This file is part of Jobmonarch
4#
[363]5# Copyright (C) 2006-2007  Ramon Bastiaans
[225]6#
7# Jobmonarch is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# Jobmonarch is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20#
[228]21# SVN $Id: jobmond.py 373 2007-06-13 13:38:52Z bastiaans $
[227]22#
[23]23
[212]24import sys, getopt, ConfigParser
[354]25import time, os, socket, string, re
[373]26import xdrlib, socket, syslog
[318]27import xml, xml.sax
28from xml.sax import saxutils, make_parser
29from xml.sax import make_parser
30from xml.sax.handler import feature_namespaces
31
[307]32def usage():
33
34        print
35        print 'usage: jobmond [options]'
36        print 'options:'
37        print '      --config, -c      configuration file'
38        print '      --pidfile, -p     pid file'
39        print '      --help, -h        help'
40        print
41
[212]42def processArgs( args ):
[26]43
[354]44        SHORT_L         = 'hc:'
45        LONG_L          = [ 'help', 'config=' ]
[165]46
[307]47        global PIDFILE
[354]48        PIDFILE         = None
[61]49
[354]50        config_filename = '/etc/jobmond.conf'
51
[212]52        try:
[68]53
[354]54                opts, args      = getopt.getopt( args, SHORT_L, LONG_L )
[185]55
[307]56        except getopt.GetoptError, detail:
[212]57
58                print detail
[307]59                usage()
[354]60                sys.exit( 1 )
[212]61
62        for opt, value in opts:
63
64                if opt in [ '--config', '-c' ]:
65               
[354]66                        config_filename = value
[212]67
[307]68                if opt in [ '--pidfile', '-p' ]:
[212]69
[354]70                        PIDFILE         = value
[307]71               
72                if opt in [ '--help', '-h' ]:
73 
74                        usage()
[354]75                        sys.exit( 0 )
[212]76
77        return loadConfig( config_filename )
78
79def loadConfig( filename ):
80
[215]81        def getlist( cfg_string ):
82
83                my_list = [ ]
84
85                for item_txt in cfg_string.split( ',' ):
86
87                        sep_char = None
88
89                        item_txt = item_txt.strip()
90
91                        for s_char in [ "'", '"' ]:
92
93                                if item_txt.find( s_char ) != -1:
94
95                                        if item_txt.count( s_char ) != 2:
96
97                                                print 'Missing quote: %s' %item_txt
98                                                sys.exit( 1 )
99
100                                        else:
101
102                                                sep_char = s_char
103                                                break
104
105                        if sep_char:
106
107                                item_txt = item_txt.split( sep_char )[1]
108
109                        my_list.append( item_txt )
110
111                return my_list
112
[354]113        cfg             = ConfigParser.ConfigParser()
[212]114
115        cfg.read( filename )
116
[354]117        global DEBUG_LEVEL, DAEMONIZE, BATCH_SERVER, BATCH_POLL_INTERVAL
118        global GMOND_CONF, DETECT_TIME_DIFFS, BATCH_HOST_TRANSLATE
[373]119        global BATCH_API, QUEUE, GMETRIC_TARGET, USE_SYSLOG
120        global SYSLOG_LEVEL, SYSLOG_FACILITY
[212]121
[354]122        DEBUG_LEVEL     = cfg.getint( 'DEFAULT', 'DEBUG_LEVEL' )
[212]123
[354]124        DAEMONIZE       = cfg.getboolean( 'DEFAULT', 'DAEMONIZE' )
[212]125
[265]126        try:
[373]127                USE_SYSLOG      = cfg.getboolean( 'DEFAULT', 'USE_SYSLOG' )
[212]128
[373]129        except ConfigParser.NoOptionError:
130
131                USE_SYSLOG      = True
132
133                debug_msg( 0, 'ERROR: no option USE_SYSLOG found: assuming yes' )
134
135        if USE_SYSLOG:
136
137                try:
138                        SYSLOG_LEVEL    = cfg.getint( 'DEFAULT', 'SYSLOG_LEVEL' )
139
140                except ConfigParser.NoOptionError:
141
142                        debug_msg( 0, 'ERROR: no option SYSLOG_LEVEL found: assuming level 0' )
143                        SYSLOG_LEVEL    = 0
144
145                try:
146
147                        SYSLOG_FACILITY = eval( 'syslog.LOG_' + cfg.get( 'DEFAULT', 'SYSLOG_FACILITY' ) )
148
149                except AttributeError, detail:
150
151                        SYSLOG_FACILITY = syslog.LOG_DAEMON
152
153                        debug_msg( 0, 'ERROR: no option SYSLOG_FACILITY found: assuming facility DAEMON' )
154
155        try:
156
[354]157                BATCH_SERVER            = cfg.get( 'DEFAULT', 'BATCH_SERVER' )
[212]158
[265]159        except ConfigParser.NoOptionError:
160
161                # Backwards compatibility for old configs
162                #
163
[354]164                BATCH_SERVER            = cfg.get( 'DEFAULT', 'TORQUE_SERVER' )
165                api_guess               = 'pbs'
[265]166       
167        try:
168       
[354]169                BATCH_POLL_INTERVAL     = cfg.getint( 'DEFAULT', 'BATCH_POLL_INTERVAL' )
[265]170
171        except ConfigParser.NoOptionError:
172
173                # Backwards compatibility for old configs
174                #
175
[354]176                BATCH_POLL_INTERVAL     = cfg.getint( 'DEFAULT', 'TORQUE_POLL_INTERVAL' )
177                api_guess               = 'pbs'
[353]178       
179        try:
[212]180
[354]181                GMOND_CONF              = cfg.get( 'DEFAULT', 'GMOND_CONF' )
[353]182
183        except ConfigParser.NoOptionError:
184
[354]185                GMOND_CONF              = None
[353]186
[354]187        DETECT_TIME_DIFFS       = cfg.getboolean( 'DEFAULT', 'DETECT_TIME_DIFFS' )
[212]188
[354]189        BATCH_HOST_TRANSLATE    = getlist( cfg.get( 'DEFAULT', 'BATCH_HOST_TRANSLATE' ) )
[215]190
[266]191        try:
[256]192
[354]193                BATCH_API       = cfg.get( 'DEFAULT', 'BATCH_API' )
[266]194
195        except ConfigParser.NoOptionError, detail:
196
197                if BATCH_SERVER and api_guess:
[354]198
199                        BATCH_API       = api_guess
[266]200                else:
[373]201                        debug_msg( 0, "FATAL ERROR: BATCH_API not set and can't make guess" )
[266]202                        sys.exit( 1 )
[317]203
204        try:
205
[354]206                QUEUE           = getlist( cfg.get( 'DEFAULT', 'QUEUE' ) )
[317]207
208        except ConfigParser.NoOptionError, detail:
209
[354]210                QUEUE           = None
[353]211
212        try:
213
[354]214                GMETRIC_TARGET  = cfg.get( 'DEFAULT', 'GMETRIC_TARGET' )
[353]215
216        except ConfigParser.NoOptionError:
217
[354]218                GMETRIC_TARGET  = None
[353]219
220                if not GMOND_CONF:
221
[373]222                        debug_msg( 0, "FATAL ERROR: GMETRIC_TARGET and GMOND_CONF both not set! Set at least one!" )
[353]223                        sys.exit( 1 )
224                else:
225
[373]226                        debug_msg( 0, "ERROR: GMETRIC_TARGET not set: internel Gmetric handling aborted. Failing back to DEPRECATED use of gmond.conf/gmetric binary. This will slow down jobmond significantly!" )
[353]227
[212]228        return True
229
[253]230METRIC_MAX_VAL_LEN = 900
231
[61]232class DataProcessor:
[355]233
[68]234        """Class for processing of data"""
[61]235
236        binary = '/usr/bin/gmetric'
237
238        def __init__( self, binary=None ):
[355]239
[68]240                """Remember alternate binary location if supplied"""
[61]241
242                if binary:
243                        self.binary = binary
244
[80]245                # Timeout for XML
246                #
247                # From ganglia's documentation:
248                #
249                # 'A metric will be deleted DMAX seconds after it is received, and
250                # DMAX=0 means eternal life.'
[61]251
[256]252                self.dmax = str( int( int( BATCH_POLL_INTERVAL ) * 2 ) )
[80]253
[353]254                if GMOND_CONF:
[354]255
[353]256                        try:
257                                gmond_file = GMOND_CONF
[68]258
[353]259                        except NameError:
260                                gmond_file = '/etc/gmond.conf'
[68]261
[353]262                        if not os.path.exists( gmond_file ):
[373]263                                debug_msg( 0, 'FATAL ERROR: ' + gmond_file + ' does not exist' )
[353]264                                sys.exit( 1 )
[68]265
[353]266                        incompatible = self.checkGmetricVersion()
[61]267
[353]268                        if incompatible:
[355]269
270                                debug_msg( 0, 'Gmetric version not compatible, please upgrade to at least 3.0.1' )
[353]271                                sys.exit( 1 )
[65]272
273        def checkGmetricVersion( self ):
[355]274
[68]275                """
276                Check version of gmetric is at least 3.0.1
277                for the syntax we use
278                """
[65]279
[255]280                global METRIC_MAX_VAL_LEN
281
[341]282                incompatible    = 0
283
[355]284                gfp             = os.popen( self.binary + ' --version' )
285                lines           = gfp.readlines()
[65]286
[355]287                gfp.close()
288
289                for line in lines:
290
[65]291                        line = line.split( ' ' )
292
[355]293                        if len( line ) == 2 and str( line ).find( 'gmetric' ) != -1:
[65]294                       
[355]295                                gmetric_version = line[1].split( '\n' )[0]
[65]296
[355]297                                version_major   = int( gmetric_version.split( '.' )[0] )
298                                version_minor   = int( gmetric_version.split( '.' )[1] )
299                                version_patch   = int( gmetric_version.split( '.' )[2] )
[65]300
[355]301                                incompatible    = 0
[65]302
303                                if version_major < 3:
304
305                                        incompatible = 1
306                               
307                                elif version_major == 3:
308
309                                        if version_minor == 0:
310
311                                                if version_patch < 1:
312                                               
[91]313                                                        incompatible = 1
[65]314
[255]315                                                if version_patch < 3:
316
317                                                        METRIC_MAX_VAL_LEN = 900
318
319                                                elif version_patch >= 3:
320
321                                                        METRIC_MAX_VAL_LEN = 1400
322
[65]323                return incompatible
324
[75]325        def multicastGmetric( self, metricname, metricval, valtype='string' ):
[355]326
[68]327                """Call gmetric binary and multicast"""
[65]328
329                cmd = self.binary
330
[353]331                if GMETRIC_TARGET:
[61]332
[353]333                        from gmetric import Gmetric
[61]334
[353]335                if GMETRIC_TARGET:
[61]336
[353]337                        GMETRIC_TARGET_HOST     = GMETRIC_TARGET.split( ':' )[0]
338                        GMETRIC_TARGET_PORT     = GMETRIC_TARGET.split( ':' )[1]
339
340                        metric_debug            = "[gmetric] name: %s - val: %s - dmax: %s" %( str( metricname ), str( metricval ), str( self.dmax ) )
341
342                        debug_msg( 10, printTime() + ' ' + metric_debug)
343
344                        gm = Gmetric( GMETRIC_TARGET_HOST, GMETRIC_TARGET_PORT )
345
346                        gm.send( str( metricname ), str( metricval ), str( self.dmax ) )
347
348                else:
349                        try:
350                                cmd = cmd + ' -c' + GMOND_CONF
351
352                        except NameError:
353
354                                debug_msg( 10, 'Assuming /etc/gmond.conf for gmetric cmd (ommitting)' )
355
356                        cmd = cmd + ' -n' + str( metricname )+ ' -v"' + str( metricval )+ '" -t' + str( valtype ) + ' -d' + str( self.dmax )
357
358                        debug_msg( 10, printTime() + ' ' + cmd )
359
360                        os.system( cmd )
361
[318]362class DataGatherer:
[23]363
[318]364        """Skeleton class for batch system DataGatherer"""
[256]365
[318]366        def printJobs( self, jobs ):
[355]367
[318]368                """Print a jobinfo overview"""
369
370                for name, attrs in self.jobs.items():
371
372                        print 'job %s' %(name)
373
374                        for name, val in attrs.items():
375
376                                print '\t%s = %s' %( name, val )
377
378        def printJob( self, jobs, job_id ):
[355]379
[318]380                """Print job with job_id from jobs"""
381
382                print 'job %s' %(job_id)
383
384                for name, val in jobs[ job_id ].items():
385
386                        print '\t%s = %s' %( name, val )
387
[256]388        def daemon( self ):
[355]389
[318]390                """Run as daemon forever"""
[256]391
[318]392                # Fork the first child
393                #
394                pid = os.fork()
395                if pid > 0:
396                        sys.exit(0)  # end parent
[256]397
[318]398                # creates a session and sets the process group ID
399                #
400                os.setsid()
401
402                # Fork the second child
403                #
404                pid = os.fork()
405                if pid > 0:
406                        sys.exit(0)  # end parent
407
408                write_pidfile()
409
410                # Go to the root directory and set the umask
411                #
412                os.chdir('/')
413                os.umask(0)
414
415                sys.stdin.close()
416                sys.stdout.close()
417                sys.stderr.close()
418
419                os.open('/dev/null', os.O_RDWR)
420                os.dup2(0, 1)
421                os.dup2(0, 2)
422
423                self.run()
424
[256]425        def run( self ):
[355]426
[318]427                """Main thread"""
[256]428
[318]429                while ( 1 ):
430               
[348]431                        self.getJobData()
432                        self.submitJobData()
[318]433                        time.sleep( BATCH_POLL_INTERVAL )       
[256]434
[318]435class SgeQstatXMLParser(xml.sax.handler.ContentHandler):
[256]436
[318]437        """Babu Sundaram's experimental SGE qstat XML parser"""
[256]438
[318]439        def __init__(self, qstatinxml):
440
441                self.qstatfile = qstatinxml
442                self.attribs = {}
443                self.value = ''
444                self.jobID = ''
445                self.currentJobInfo = ''
446                self.job_list = []
447                self.EOFFlag = 0
448                self.jobinfoCount = 0
449
450
451        def startElement(self, name, attrs):
452
453                if name == 'job_list':
454                        self.currentJobInfo = 'Status=' + attrs.get('state', None) + ' '
455                elif name == 'job_info':
456                        self.job_list = []
457                        self.jobinfoCount += 1
458
459        def characters(self, ch):
460
461                self.value = self.value + ch
462
463        def endElement(self, name):
464
465                if len(self.value.strip()) > 0 :
466
467                        self.currentJobInfo += name + '=' + self.value.strip() + ' '         
468                elif name != 'job_list':
469
470                        self.currentJobInfo += name + '=Unknown '
471
472                if name == 'JB_job_number':
473
474                        self.jobID = self.value.strip()
475                        self.job_list.append(self.jobID)         
476
477                if name == 'job_list':
478
479                        if self.attribs.has_key(self.jobID) == False:
480                                self.attribs[self.jobID] = self.currentJobInfo
481                        elif self.attribs.has_key(self.jobID) and self.attribs[self.jobID] != self.currentJobInfo:
482                                self.attribs[self.jobID] = self.currentJobInfo
483                        self.currentJobInfo = ''
484                        self.jobID = ''
485
486                elif name == 'job_info' and self.jobinfoCount == 2:
487
488                        deljobs = []
489                        for id in self.attribs:
490                                try:
491                                        self.job_list.index(str(id))
492                                except ValueError:
493                                        deljobs.append(id)
494                        for i in deljobs:
495                                del self.attribs[i]
496                        deljobs = []
497                        self.jobinfoCount = 0
498
499                self.value = ''
500
501class SgeDataGatherer(DataGatherer):
502
[61]503        jobs = { }
[347]504        SGE_QSTAT_XML_FILE      = '/tmp/.jobmonarch.sge.qstat'
[61]505
[318]506        def __init__( self ):
507                """Setup appropriate variables"""
508
509                self.jobs = { }
510                self.timeoffset = 0
511                self.dp = DataProcessor()
512                self.initSgeJobInfo()
513
514        def initSgeJobInfo( self ):
515                """This is outside the scope of DRMAA; Get the current jobs in SGE"""
516                """This is a hack because we cant get info about jobs beyond"""
517                """those in the current DRMAA session"""
518
[347]519                self.qstatparser = SgeQstatXMLParser( self.SGE_QSTAT_XML_FILE )
[318]520
521                # Obtain the qstat information from SGE in XML format
522                # This would change to DRMAA-specific calls from 6.0u9
523
524        def getJobData(self):
525                """Gather all data on current jobs in SGE"""
526
527                # Get the information about the current jobs in the SGE queue
528                info = os.popen("qstat -ext -xml").readlines()
[347]529                f = open(self.SGE_QSTAT_XML_FILE,'w')
[318]530                for lines in info:
531                        f.write(lines)
532                f.close()
533
534                # Parse the input
535                f = open(self.qstatparser.qstatfile, 'r')
536                xml.sax.parse(f, self.qstatparser)
537                f.close()
538
539                self.cur_time = time.time()
540
541                return self.qstatparser.attribs
542
543        def submitJobData(self):
544                """Submit job info list"""
545
546                self.dp.multicastGmetric( 'MONARCH-HEARTBEAT', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
547                # Now let's spread the knowledge
548                #
549                metric_increment = 0
550                for jobid, jobattrs in self.qstatparser.attribs.items():
551
552                        self.dp.multicastGmetric( 'MONARCH-JOB-' + jobid + '-' + str(metric_increment), jobattrs)
553
[355]554class PbsDataGatherer( DataGatherer ):
[318]555
556        """This is the DataGatherer for PBS and Torque"""
557
[256]558        global PBSQuery
559
[23]560        def __init__( self ):
[354]561
[68]562                """Setup appropriate variables"""
[23]563
[354]564                self.jobs       = { }
565                self.timeoffset = 0
566                self.dp         = DataProcessor()
567
[91]568                self.initPbsQuery()
[23]569
[91]570        def initPbsQuery( self ):
571
[354]572                self.pq         = None
573
[256]574                if( BATCH_SERVER ):
[354]575
576                        self.pq         = PBSQuery( BATCH_SERVER )
[174]577                else:
[354]578                        self.pq         = PBSQuery()
[91]579
[26]580        def getAttr( self, attrs, name ):
[354]581
[68]582                """Return certain attribute from dictionary, if exists"""
[26]583
584                if attrs.has_key( name ):
[354]585
586                        return attrs[ name ]
[26]587                else:
588                        return ''
589
590        def jobDataChanged( self, jobs, job_id, attrs ):
[354]591
[68]592                """Check if job with attrs and job_id in jobs has changed"""
[26]593
594                if jobs.has_key( job_id ):
[354]595
[26]596                        oldData = jobs[ job_id ]       
597                else:
598                        return 1
599
600                for name, val in attrs.items():
601
602                        if oldData.has_key( name ):
603
604                                if oldData[ name ] != attrs[ name ]:
605
606                                        return 1
607
608                        else:
609                                return 1
610
611                return 0
612
[348]613        def getJobData( self ):
[354]614
[68]615                """Gather all data on current jobs in Torque"""
[26]616
[354]617                joblist         = {}
[359]618                self.cur_time   = 0
[349]619
[359]620                try:
621                        joblist         = self.pq.getjobs()
622                        self.cur_time   = time.time()
[354]623
[359]624                except PBSError, detail:
[354]625
[359]626                        debug_msg( 10, "Caught PBS unavailable, skipping until next polling interval: " + str( detail ) )
627                        return None
[354]628
629                jobs_processed  = [ ]
[26]630
631                for name, attrs in joblist.items():
632
[354]633                        job_id                  = name.split( '.' )[0]
[26]634
635                        jobs_processed.append( job_id )
[61]636
[354]637                        name                    = self.getAttr( attrs, 'Job_Name' )
638                        queue                   = self.getAttr( attrs, 'queue' )
[317]639
640                        if QUEUE:
641
642                                if QUEUE != queue:
643
644                                        continue
645
[354]646                        owner                   = self.getAttr( attrs, 'Job_Owner' ).split( '@' )[0]
647                        requested_time          = self.getAttr( attrs, 'Resource_List.walltime' )
648                        requested_memory        = self.getAttr( attrs, 'Resource_List.mem' )
[95]649
[354]650                        mynoderequest           = self.getAttr( attrs, 'Resource_List.nodes' )
[95]651
[354]652                        ppn                     = ''
[281]653
[26]654                        if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
[95]655
[354]656                                mynoderequest_fields    = mynoderequest.split( ':' )
[281]657
658                                for mynoderequest_field in mynoderequest_fields:
659
660                                        if mynoderequest_field.find( 'ppn' ) != -1:
661
[354]662                                                ppn     = mynoderequest_field.split( 'ppn=' )[1]
[281]663
[354]664                        status                  = self.getAttr( attrs, 'job_state' )
[25]665
[354]666                        queued_timestamp        = self.getAttr( attrs, 'ctime' )
[243]667
[95]668                        if status == 'R':
[133]669
[354]670                                start_timestamp         = self.getAttr( attrs, 'mtime' )
671                                nodes                   = self.getAttr( attrs, 'exec_host' ).split( '+' )
[133]672
[354]673                                nodeslist               = [ ]
674
[133]675                                for node in nodes:
676
[354]677                                        host            = node.split( '/' )[0]
678
[133]679                                        if nodeslist.count( host ) == 0:
[215]680
681                                                for translate_pattern in BATCH_HOST_TRANSLATE:
682
[220]683                                                        if translate_pattern.find( '/' ) != -1:
[215]684
[354]685                                                                translate_orig  = translate_pattern.split( '/' )[1]
686                                                                translate_new   = translate_pattern.split( '/' )[2]
[220]687
[354]688                                                                host            = re.sub( translate_orig, translate_new, host )
[216]689                               
[217]690                                                if not host in nodeslist:
[216]691                               
692                                                        nodeslist.append( host )
[133]693
[185]694                                if DETECT_TIME_DIFFS:
695
696                                        # If a job start if later than our current date,
697                                        # that must mean the Torque server's time is later
698                                        # than our local time.
699                               
[354]700                                        if int( start_timestamp ) > int( int( self.cur_time ) + int( self.timeoffset ) ):
[185]701
[354]702                                                self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
[185]703
[133]704                        elif status == 'Q':
[95]705
[354]706                                start_timestamp         = ''
707                                count_mynodes           = 0
708                                numeric_node            = 1
709
[133]710                                for node in mynoderequest.split( '+' ):
[67]711
[354]712                                        nodepart        = node.split( ':' )[0]
[67]713
[133]714                                        for letter in nodepart:
[67]715
[133]716                                                if letter not in string.digits:
717
[354]718                                                        numeric_node    = 0
[133]719
720                                        if not numeric_node:
[354]721
722                                                count_mynodes   = count_mynodes + 1
[133]723                                        else:
[327]724                                                try:
[354]725                                                        count_mynodes   = count_mynodes + int( nodepart )
726
[327]727                                                except ValueError, detail:
[354]728
[327]729                                                        debug_msg( 10, str( detail ) )
730                                                        debug_msg( 10, "Encountered weird node in Resources_List?!" )
731                                                        debug_msg( 10, 'nodepart = ' + str( nodepart ) )
732                                                        debug_msg( 10, 'job = ' + str( name ) )
733                                                        debug_msg( 10, 'attrs = ' + str( attrs ) )
[133]734                                               
[354]735                                nodeslist       = str( count_mynodes )
[172]736                        else:
[354]737                                start_timestamp = ''
738                                nodeslist       = ''
[133]739
[354]740                        myAttrs                         = { }
[26]741
[354]742                        myAttrs[ 'name' ]                       = str( name )
743                        myAttrs[ 'queue' ]              = str( queue )
744                        myAttrs[ 'owner' ]              = str( owner )
745                        myAttrs[ 'requested_time' ]     = str( requested_time )
746                        myAttrs[ 'requested_memory' ]   = str( requested_memory )
747                        myAttrs[ 'ppn' ]                = str( ppn )
748                        myAttrs[ 'status' ]             = str( status )
749                        myAttrs[ 'start_timestamp' ]    = str( start_timestamp )
750                        myAttrs[ 'queued_timestamp' ]   = str( queued_timestamp )
751                        myAttrs[ 'reported' ]           = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
752                        myAttrs[ 'nodes' ]              = nodeslist
753                        myAttrs[ 'domain' ]             = string.join( socket.getfqdn().split( '.' )[1:], '.' )
754                        myAttrs[ 'poll_interval' ]      = str( BATCH_POLL_INTERVAL )
755
[348]756                        if self.jobDataChanged( self.jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
[61]757
[354]758                                self.jobs[ job_id ]     = myAttrs
[26]759
[348]760                for id, attrs in self.jobs.items():
[76]761
762                        if id not in jobs_processed:
763
764                                # This one isn't there anymore; toedeledoki!
765                                #
[348]766                                del self.jobs[ id ]
[76]767
[348]768        def submitJobData( self ):
[354]769
[65]770                """Submit job info list"""
771
[219]772                self.dp.multicastGmetric( 'MONARCH-HEARTBEAT', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
[69]773
[61]774                # Now let's spread the knowledge
775                #
[348]776                for jobid, jobattrs in self.jobs.items():
[61]777
[354]778                        gmetric_val             = self.compileGmetricVal( jobid, jobattrs )
779                        metric_increment        = 0
[61]780
[354]781                        for val in gmetric_val:
[253]782
783                                self.dp.multicastGmetric( 'MONARCH-JOB-' + jobid + '-' + str(metric_increment), val )
[61]784
[354]785                                metric_increment        = metric_increment + 1
786
[253]787        def compileGmetricVal( self, jobid, jobattrs ):
[354]788
[253]789                """Create a val string for gmetric of jobinfo"""
[67]790
[354]791                gval_lists      = [ ]
792                mystr           = None
793                val_list        = { }
[67]794
[253]795                for val_name, val_value in jobattrs.items():
[61]796
[253]797                        val_list_names_len      = len( string.join( val_list.keys() ) ) + len(val_list.keys())
798                        val_list_vals_len       = len( string.join( val_list.values() ) ) + len(val_list.values())
[95]799
[254]800                        if val_name == 'nodes' and jobattrs['status'] == 'R':
[95]801
[253]802                                node_str = None
[95]803
[253]804                                for node in val_value:
[65]805
[253]806                                        if node_str:
[354]807
[253]808                                                node_str = node_str + ';' + node
809                                        else:
810                                                node_str = node
[65]811
[253]812                                        if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(node_str) ) > METRIC_MAX_VAL_LEN:
[65]813
[354]814                                                val_list[ val_name ]    = node_str
815
[253]816                                                gval_lists.append( val_list )
[65]817
[354]818                                                val_list                = { }
819                                                node_str                = None
820
821                                val_list[ val_name ]    = node_str
822
[253]823                                gval_lists.append( val_list )
[65]824
[354]825                                val_list                = { }
826
[254]827                        elif val_value != '':
828
829                                if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(str(val_value)) ) > METRIC_MAX_VAL_LEN:
830
831                                        gval_lists.append( val_list )
832
[354]833                                        val_list                = { }
[254]834
[354]835                                val_list[ val_name ]    = val_value
836
837                if len( val_list ) > 0:
838
[254]839                        gval_lists.append( val_list )
840
[354]841                str_list        = [ ]
[65]842
[253]843                for val_list in gval_lists:
[65]844
[354]845                        my_val_str      = None
[65]846
[253]847                        for val_name, val_value in val_list.items():
[65]848
[253]849                                if my_val_str:
[65]850
[253]851                                        my_val_str = my_val_str + ' ' + val_name + '=' + val_value
852                                else:
853                                        my_val_str = val_name + '=' + val_value
854
855                        str_list.append( my_val_str )
856
857                return str_list
858
[363]859#
860# Gmetric by Nick Galbreath - nickg(a.t)modp(d.o.t)com
861# Version 1.0 - 21-April2-2007
862# http://code.google.com/p/embeddedgmetric/
863#
864# Modified by: Ramon Bastiaans
865# For the Job Monarch Project, see: https://subtrac.sara.nl/oss/jobmonarch/
866#
867# added: DEFAULT_TYPE for Gmetric's
868# added: checkHostProtocol to determine if target is multicast or not
869# changed: allow default for Gmetric constructor
870# changed: allow defaults for all send() values except dmax
871#
872
[362]873GMETRIC_DEFAULT_TYPE    = 'string'
874GMETRIC_DEFAULT_HOST    = '127.0.0.1'
875GMETRIC_DEFAULT_PORT    = '8649'
876
877class Gmetric:
878
879        global GMETRIC_DEFAULT_HOST, GMETRIC_DEFAULT_PORT
880
881        slope           = { 'zero' : 0, 'positive' : 1, 'negative' : 2, 'both' : 3, 'unspecified' : 4 }
882        type            = ( '', 'string', 'uint16', 'int16', 'uint32', 'int32', 'float', 'double', 'timestamp' )
883        protocol        = ( 'udp', 'multicast' )
884
885        def __init__( self, host=GMETRIC_DEFAULT_HOST, port=GMETRIC_DEFAULT_PORT ):
886               
887                global GMETRIC_DEFAULT_TYPE
888
889                self.prot       = self.checkHostProtocol( host )
890                self.msg        = xdrlib.Packer()
891                self.socket     = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
892
893                if self.prot not in self.protocol:
894
895                        raise ValueError( "Protocol must be one of: " + str( self.protocol ) )
896
897                if self.prot == 'multicast':
898
899                        self.socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20 )
900
901                self.hostport   = ( host, int( port ) )
902                self.type       = GMETRIC_DEFAULT_TYPE
903                self.unitstr    = ''
904                self.slopestr   = 'both'
905                self.tmax       = 60
906
907        def checkHostProtocol( self, ip ):
908
909                MULTICAST_ADDRESS_MIN   = ( "224", "0", "0", "0" )
910                MULTICAST_ADDRESS_MAX   = ( "239", "255", "255", "255" )
911
912                ip_fields               = ip.split( '.' )
913
914                if ip_fields >= MULTICAST_ADDRESS_MIN and ip_fields <= MULTICAST_ADDRESS_MAX:
915
916                        return 'multicast'
917                else:
918                        return 'udp'
919
920        def send( self, name, value, dmax ):
921
922                msg             = self.makexdr( name, value, self.type, self.unitstr, self.slopestr, self.tmax, dmax )
923
924                return self.socket.sendto( msg, self.hostport )
925
926        def makexdr( self, name, value, typestr, unitstr, slopestr, tmax, dmax ):
927
928                if slopestr not in self.slope:
929
930                        raise ValueError( "Slope must be one of: " + str( self.slope.keys() ) )
931
932                if typestr not in self.type:
933
934                        raise ValueError( "Type must be one of: " + str( self.type ) )
935
936                if len( name ) == 0:
937
938                        raise ValueError( "Name must be non-empty" )
939
940                self.msg.reset()
941                self.msg.pack_int( 0 )
942                self.msg.pack_string( typestr )
943                self.msg.pack_string( name )
944                self.msg.pack_string( str( value ) )
945                self.msg.pack_string( unitstr )
946                self.msg.pack_int( self.slope[ slopestr ] )
947                self.msg.pack_uint( int( tmax ) )
948                self.msg.pack_uint( int( dmax ) )
949
950                return self.msg.get_buffer()
951
[26]952def printTime( ):
[354]953
[65]954        """Print current time/date in human readable format for log/debug"""
[26]955
956        return time.strftime("%a, %d %b %Y %H:%M:%S")
957
958def debug_msg( level, msg ):
[354]959
[65]960        """Print msg if at or above current debug level"""
[26]961
[373]962        if (not DAEMONIZE and DEBUG_LEVEL >= level):
963                sys.stderr.write( msg + '\n' )
[26]964
[373]965        if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
966                syslog.syslog( msg )
967
[307]968def write_pidfile():
969
970        # Write pidfile if PIDFILE exists
971        if PIDFILE:
972
[354]973                pid     = os.getpid()
974
975                pidfile = open(PIDFILE, 'w')
976
977                pidfile.write( str( pid ) )
[307]978                pidfile.close()
979
[23]980def main():
[354]981
[65]982        """Application start"""
[23]983
[352]984        global PBSQuery, PBSError
[373]985        global SYSLOG_FACILITY, USE_SYSLOG, BATCH_API, DAEMONIZE
[256]986
[212]987        if not processArgs( sys.argv[1:] ):
[354]988
[212]989                sys.exit( 1 )
990
[256]991        if BATCH_API == 'pbs':
992
993                try:
[282]994                        from PBSQuery import PBSQuery, PBSError
[256]995
996                except ImportError:
997
[373]998                        debug_msg( 0, "FATAL ERROR: BATCH_API set to 'pbs' but python module 'pbs_python' is not installed" )
[256]999                        sys.exit( 1 )
1000
1001                gather = PbsDataGatherer()
1002
1003        elif BATCH_API == 'sge':
1004
[373]1005                debug_msg( 0, "FATAL ERROR: BATCH_API 'sge' implementation is currently broken, check future releases" )
[368]1006
1007                sys.exit( 1 )
1008
[347]1009                gather = SgeDataGatherer()
[256]1010
1011        else:
[373]1012                debug_msg( 0, "FATAL ERROR: unknown BATCH_API '" + BATCH_API + "' is not supported" )
[354]1013
[256]1014                sys.exit( 1 )
1015
[373]1016        if( DAEMONIZE and USE_SYSLOG ):
1017
1018                syslog.openlog( 'jobmond', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
1019
1020
[26]1021        if DAEMONIZE:
[354]1022
[26]1023                gather.daemon()
1024        else:
1025                gather.run()
[23]1026
[256]1027# wh00t? someone started me! :)
[65]1028#
[23]1029if __name__ == '__main__':
1030        main()
Note: See TracBrowser for help on using the repository browser.