source: trunk/jobmond/jobmond.py @ 425

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

jobmond/jobmond.py:

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