source: trunk/jobmond/jobmond.py @ 450

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

jobmond/jobmond.py:

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