source: trunk/jobmond/jobmond.py @ 378

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

jobmond/jobmond.py:

  • bugfixes to syslog code
  • Property svn:keywords set to Id
File size: 23.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 377 2007-06-13 14:14:05Z 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         = 'hc:'
45        LONG_L          = [ 'help', 'config=' ]
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
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        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
153                except ConfigParser.NoOptionError:
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
161                BATCH_SERVER            = cfg.get( 'DEFAULT', 'BATCH_SERVER' )
162
163        except ConfigParser.NoOptionError:
164
165                # Backwards compatibility for old configs
166                #
167
168                BATCH_SERVER            = cfg.get( 'DEFAULT', 'TORQUE_SERVER' )
169                api_guess               = 'pbs'
170       
171        try:
172       
173                BATCH_POLL_INTERVAL     = cfg.getint( 'DEFAULT', 'BATCH_POLL_INTERVAL' )
174
175        except ConfigParser.NoOptionError:
176
177                # Backwards compatibility for old configs
178                #
179
180                BATCH_POLL_INTERVAL     = cfg.getint( 'DEFAULT', 'TORQUE_POLL_INTERVAL' )
181                api_guess               = 'pbs'
182       
183        try:
184
185                GMOND_CONF              = cfg.get( 'DEFAULT', 'GMOND_CONF' )
186
187        except ConfigParser.NoOptionError:
188
189                GMOND_CONF              = None
190
191        DETECT_TIME_DIFFS       = cfg.getboolean( 'DEFAULT', 'DETECT_TIME_DIFFS' )
192
193        BATCH_HOST_TRANSLATE    = getlist( cfg.get( 'DEFAULT', 'BATCH_HOST_TRANSLATE' ) )
194
195        try:
196
197                BATCH_API       = cfg.get( 'DEFAULT', 'BATCH_API' )
198
199        except ConfigParser.NoOptionError, detail:
200
201                if BATCH_SERVER and api_guess:
202
203                        BATCH_API       = api_guess
204                else:
205                        debug_msg( 0, "FATAL ERROR: BATCH_API not set and can't make guess" )
206                        sys.exit( 1 )
207
208        try:
209
210                QUEUE           = getlist( cfg.get( 'DEFAULT', 'QUEUE' ) )
211
212        except ConfigParser.NoOptionError, detail:
213
214                QUEUE           = None
215
216        try:
217
218                GMETRIC_TARGET  = cfg.get( 'DEFAULT', 'GMETRIC_TARGET' )
219
220        except ConfigParser.NoOptionError:
221
222                GMETRIC_TARGET  = None
223
224                if not GMOND_CONF:
225
226                        debug_msg( 0, "FATAL ERROR: GMETRIC_TARGET and GMOND_CONF both not set! Set at least one!" )
227                        sys.exit( 1 )
228                else:
229
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!" )
231
232        return True
233
234METRIC_MAX_VAL_LEN = 900
235
236class DataProcessor:
237
238        """Class for processing of data"""
239
240        binary = '/usr/bin/gmetric'
241
242        def __init__( self, binary=None ):
243
244                """Remember alternate binary location if supplied"""
245
246                if binary:
247                        self.binary = binary
248
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.'
255
256                self.dmax = str( int( int( BATCH_POLL_INTERVAL ) * 2 ) )
257
258                if GMOND_CONF:
259
260                        try:
261                                gmond_file = GMOND_CONF
262
263                        except NameError:
264                                gmond_file = '/etc/gmond.conf'
265
266                        if not os.path.exists( gmond_file ):
267                                debug_msg( 0, 'FATAL ERROR: ' + gmond_file + ' does not exist' )
268                                sys.exit( 1 )
269
270                        incompatible = self.checkGmetricVersion()
271
272                        if incompatible:
273
274                                debug_msg( 0, 'Gmetric version not compatible, please upgrade to at least 3.0.1' )
275                                sys.exit( 1 )
276
277        def checkGmetricVersion( self ):
278
279                """
280                Check version of gmetric is at least 3.0.1
281                for the syntax we use
282                """
283
284                global METRIC_MAX_VAL_LEN
285
286                incompatible    = 0
287
288                gfp             = os.popen( self.binary + ' --version' )
289                lines           = gfp.readlines()
290
291                gfp.close()
292
293                for line in lines:
294
295                        line = line.split( ' ' )
296
297                        if len( line ) == 2 and str( line ).find( 'gmetric' ) != -1:
298                       
299                                gmetric_version = line[1].split( '\n' )[0]
300
301                                version_major   = int( gmetric_version.split( '.' )[0] )
302                                version_minor   = int( gmetric_version.split( '.' )[1] )
303                                version_patch   = int( gmetric_version.split( '.' )[2] )
304
305                                incompatible    = 0
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                                               
317                                                        incompatible = 1
318
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
327                return incompatible
328
329        def multicastGmetric( self, metricname, metricval, valtype='string' ):
330
331                """Call gmetric binary and multicast"""
332
333                cmd = self.binary
334
335                if GMETRIC_TARGET:
336
337                        from gmetric import Gmetric
338
339                if GMETRIC_TARGET:
340
341                        GMETRIC_TARGET_HOST     = GMETRIC_TARGET.split( ':' )[0]
342                        GMETRIC_TARGET_PORT     = GMETRIC_TARGET.split( ':' )[1]
343
344                        metric_debug            = "[gmetric] name: %s - val: %s - dmax: %s" %( str( metricname ), str( metricval ), str( self.dmax ) )
345
346                        debug_msg( 10, printTime() + ' ' + metric_debug)
347
348                        gm = Gmetric( GMETRIC_TARGET_HOST, GMETRIC_TARGET_PORT )
349
350                        gm.send( str( metricname ), str( metricval ), str( self.dmax ) )
351
352                else:
353                        try:
354                                cmd = cmd + ' -c' + GMOND_CONF
355
356                        except NameError:
357
358                                debug_msg( 10, 'Assuming /etc/gmond.conf for gmetric cmd (ommitting)' )
359
360                        cmd = cmd + ' -n' + str( metricname )+ ' -v"' + str( metricval )+ '" -t' + str( valtype ) + ' -d' + str( self.dmax )
361
362                        debug_msg( 10, printTime() + ' ' + cmd )
363
364                        os.system( cmd )
365
366class DataGatherer:
367
368        """Skeleton class for batch system DataGatherer"""
369
370        def printJobs( self, jobs ):
371
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 ):
383
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
392        def daemon( self ):
393
394                """Run as daemon forever"""
395
396                # Fork the first child
397                #
398                pid = os.fork()
399                if pid > 0:
400                        sys.exit(0)  # end parent
401
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
429        def run( self ):
430
431                """Main thread"""
432
433                while ( 1 ):
434               
435                        self.getJobData()
436                        self.submitJobData()
437                        time.sleep( BATCH_POLL_INTERVAL )       
438
439class SgeQstatXMLParser(xml.sax.handler.ContentHandler):
440
441        """Babu Sundaram's experimental SGE qstat XML parser"""
442
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
507        jobs = { }
508        SGE_QSTAT_XML_FILE      = '/tmp/.jobmonarch.sge.qstat'
509
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
523                self.qstatparser = SgeQstatXMLParser( self.SGE_QSTAT_XML_FILE )
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()
533                f = open(self.SGE_QSTAT_XML_FILE,'w')
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
558class PbsDataGatherer( DataGatherer ):
559
560        """This is the DataGatherer for PBS and Torque"""
561
562        global PBSQuery
563
564        def __init__( self ):
565
566                """Setup appropriate variables"""
567
568                self.jobs       = { }
569                self.timeoffset = 0
570                self.dp         = DataProcessor()
571
572                self.initPbsQuery()
573
574        def initPbsQuery( self ):
575
576                self.pq         = None
577
578                if( BATCH_SERVER ):
579
580                        self.pq         = PBSQuery( BATCH_SERVER )
581                else:
582                        self.pq         = PBSQuery()
583
584        def getAttr( self, attrs, name ):
585
586                """Return certain attribute from dictionary, if exists"""
587
588                if attrs.has_key( name ):
589
590                        return attrs[ name ]
591                else:
592                        return ''
593
594        def jobDataChanged( self, jobs, job_id, attrs ):
595
596                """Check if job with attrs and job_id in jobs has changed"""
597
598                if jobs.has_key( job_id ):
599
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
617        def getJobData( self ):
618
619                """Gather all data on current jobs in Torque"""
620
621                joblist         = {}
622                self.cur_time   = 0
623
624                try:
625                        joblist         = self.pq.getjobs()
626                        self.cur_time   = time.time()
627
628                except PBSError, detail:
629
630                        debug_msg( 10, "Caught PBS unavailable, skipping until next polling interval: " + str( detail ) )
631                        return None
632
633                jobs_processed  = [ ]
634
635                for name, attrs in joblist.items():
636
637                        job_id                  = name.split( '.' )[0]
638
639                        jobs_processed.append( job_id )
640
641                        name                    = self.getAttr( attrs, 'Job_Name' )
642                        queue                   = self.getAttr( attrs, 'queue' )
643
644                        if QUEUE:
645
646                                if QUEUE != queue:
647
648                                        continue
649
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' )
653
654                        mynoderequest           = self.getAttr( attrs, 'Resource_List.nodes' )
655
656                        ppn                     = ''
657
658                        if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
659
660                                mynoderequest_fields    = mynoderequest.split( ':' )
661
662                                for mynoderequest_field in mynoderequest_fields:
663
664                                        if mynoderequest_field.find( 'ppn' ) != -1:
665
666                                                ppn     = mynoderequest_field.split( 'ppn=' )[1]
667
668                        status                  = self.getAttr( attrs, 'job_state' )
669
670                        queued_timestamp        = self.getAttr( attrs, 'ctime' )
671
672                        if status == 'R':
673
674                                start_timestamp         = self.getAttr( attrs, 'mtime' )
675                                nodes                   = self.getAttr( attrs, 'exec_host' ).split( '+' )
676
677                                nodeslist               = [ ]
678
679                                for node in nodes:
680
681                                        host            = node.split( '/' )[0]
682
683                                        if nodeslist.count( host ) == 0:
684
685                                                for translate_pattern in BATCH_HOST_TRANSLATE:
686
687                                                        if translate_pattern.find( '/' ) != -1:
688
689                                                                translate_orig  = translate_pattern.split( '/' )[1]
690                                                                translate_new   = translate_pattern.split( '/' )[2]
691
692                                                                host            = re.sub( translate_orig, translate_new, host )
693                               
694                                                if not host in nodeslist:
695                               
696                                                        nodeslist.append( host )
697
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                               
704                                        if int( start_timestamp ) > int( int( self.cur_time ) + int( self.timeoffset ) ):
705
706                                                self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
707
708                        elif status == 'Q':
709
710                                start_timestamp         = ''
711                                count_mynodes           = 0
712                                numeric_node            = 1
713
714                                for node in mynoderequest.split( '+' ):
715
716                                        nodepart        = node.split( ':' )[0]
717
718                                        for letter in nodepart:
719
720                                                if letter not in string.digits:
721
722                                                        numeric_node    = 0
723
724                                        if not numeric_node:
725
726                                                count_mynodes   = count_mynodes + 1
727                                        else:
728                                                try:
729                                                        count_mynodes   = count_mynodes + int( nodepart )
730
731                                                except ValueError, detail:
732
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 ) )
738                                               
739                                nodeslist       = str( count_mynodes )
740                        else:
741                                start_timestamp = ''
742                                nodeslist       = ''
743
744                        myAttrs                         = { }
745
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
760                        if self.jobDataChanged( self.jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
761
762                                self.jobs[ job_id ]     = myAttrs
763
764                for id, attrs in self.jobs.items():
765
766                        if id not in jobs_processed:
767
768                                # This one isn't there anymore; toedeledoki!
769                                #
770                                del self.jobs[ id ]
771
772        def submitJobData( self ):
773
774                """Submit job info list"""
775
776                self.dp.multicastGmetric( 'MONARCH-HEARTBEAT', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
777
778                # Now let's spread the knowledge
779                #
780                for jobid, jobattrs in self.jobs.items():
781
782                        gmetric_val             = self.compileGmetricVal( jobid, jobattrs )
783                        metric_increment        = 0
784
785                        for val in gmetric_val:
786
787                                self.dp.multicastGmetric( 'MONARCH-JOB-' + jobid + '-' + str(metric_increment), val )
788
789                                metric_increment        = metric_increment + 1
790
791        def compileGmetricVal( self, jobid, jobattrs ):
792
793                """Create a val string for gmetric of jobinfo"""
794
795                gval_lists      = [ ]
796                mystr           = None
797                val_list        = { }
798
799                for val_name, val_value in jobattrs.items():
800
801                        val_list_names_len      = len( string.join( val_list.keys() ) ) + len(val_list.keys())
802                        val_list_vals_len       = len( string.join( val_list.values() ) ) + len(val_list.values())
803
804                        if val_name == 'nodes' and jobattrs['status'] == 'R':
805
806                                node_str = None
807
808                                for node in val_value:
809
810                                        if node_str:
811
812                                                node_str = node_str + ';' + node
813                                        else:
814                                                node_str = node
815
816                                        if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(node_str) ) > METRIC_MAX_VAL_LEN:
817
818                                                val_list[ val_name ]    = node_str
819
820                                                gval_lists.append( val_list )
821
822                                                val_list                = { }
823                                                node_str                = None
824
825                                val_list[ val_name ]    = node_str
826
827                                gval_lists.append( val_list )
828
829                                val_list                = { }
830
831                        elif val_value != '':
832
833                                if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(str(val_value)) ) > METRIC_MAX_VAL_LEN:
834
835                                        gval_lists.append( val_list )
836
837                                        val_list                = { }
838
839                                val_list[ val_name ]    = val_value
840
841                if len( val_list ) > 0:
842
843                        gval_lists.append( val_list )
844
845                str_list        = [ ]
846
847                for val_list in gval_lists:
848
849                        my_val_str      = None
850
851                        for val_name, val_value in val_list.items():
852
853                                if my_val_str:
854
855                                        my_val_str = my_val_str + ' ' + val_name + '=' + val_value
856                                else:
857                                        my_val_str = val_name + '=' + val_value
858
859                        str_list.append( my_val_str )
860
861                return str_list
862
863#
864# Gmetric by Nick Galbreath - nickg(a.t)modp(d.o.t)com
865# Version 1.0 - 21-April2-2007
866# http://code.google.com/p/embeddedgmetric/
867#
868# Modified by: Ramon Bastiaans
869# For the Job Monarch Project, see: https://subtrac.sara.nl/oss/jobmonarch/
870#
871# added: DEFAULT_TYPE for Gmetric's
872# added: checkHostProtocol to determine if target is multicast or not
873# changed: allow default for Gmetric constructor
874# changed: allow defaults for all send() values except dmax
875#
876
877GMETRIC_DEFAULT_TYPE    = 'string'
878GMETRIC_DEFAULT_HOST    = '127.0.0.1'
879GMETRIC_DEFAULT_PORT    = '8649'
880
881class Gmetric:
882
883        global GMETRIC_DEFAULT_HOST, GMETRIC_DEFAULT_PORT
884
885        slope           = { 'zero' : 0, 'positive' : 1, 'negative' : 2, 'both' : 3, 'unspecified' : 4 }
886        type            = ( '', 'string', 'uint16', 'int16', 'uint32', 'int32', 'float', 'double', 'timestamp' )
887        protocol        = ( 'udp', 'multicast' )
888
889        def __init__( self, host=GMETRIC_DEFAULT_HOST, port=GMETRIC_DEFAULT_PORT ):
890               
891                global GMETRIC_DEFAULT_TYPE
892
893                self.prot       = self.checkHostProtocol( host )
894                self.msg        = xdrlib.Packer()
895                self.socket     = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
896
897                if self.prot not in self.protocol:
898
899                        raise ValueError( "Protocol must be one of: " + str( self.protocol ) )
900
901                if self.prot == 'multicast':
902
903                        self.socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20 )
904
905                self.hostport   = ( host, int( port ) )
906                self.type       = GMETRIC_DEFAULT_TYPE
907                self.unitstr    = ''
908                self.slopestr   = 'both'
909                self.tmax       = 60
910
911        def checkHostProtocol( self, ip ):
912
913                MULTICAST_ADDRESS_MIN   = ( "224", "0", "0", "0" )
914                MULTICAST_ADDRESS_MAX   = ( "239", "255", "255", "255" )
915
916                ip_fields               = ip.split( '.' )
917
918                if ip_fields >= MULTICAST_ADDRESS_MIN and ip_fields <= MULTICAST_ADDRESS_MAX:
919
920                        return 'multicast'
921                else:
922                        return 'udp'
923
924        def send( self, name, value, dmax ):
925
926                msg             = self.makexdr( name, value, self.type, self.unitstr, self.slopestr, self.tmax, dmax )
927
928                return self.socket.sendto( msg, self.hostport )
929
930        def makexdr( self, name, value, typestr, unitstr, slopestr, tmax, dmax ):
931
932                if slopestr not in self.slope:
933
934                        raise ValueError( "Slope must be one of: " + str( self.slope.keys() ) )
935
936                if typestr not in self.type:
937
938                        raise ValueError( "Type must be one of: " + str( self.type ) )
939
940                if len( name ) == 0:
941
942                        raise ValueError( "Name must be non-empty" )
943
944                self.msg.reset()
945                self.msg.pack_int( 0 )
946                self.msg.pack_string( typestr )
947                self.msg.pack_string( name )
948                self.msg.pack_string( str( value ) )
949                self.msg.pack_string( unitstr )
950                self.msg.pack_int( self.slope[ slopestr ] )
951                self.msg.pack_uint( int( tmax ) )
952                self.msg.pack_uint( int( dmax ) )
953
954                return self.msg.get_buffer()
955
956def printTime( ):
957
958        """Print current time/date in human readable format for log/debug"""
959
960        return time.strftime("%a, %d %b %Y %H:%M:%S")
961
962def debug_msg( level, msg ):
963
964        """Print msg if at or above current debug level"""
965
966        global DAEMONIZE, DEBUG_LEVEL, SYSLOG_LEVEL
967
968        if (not DAEMONIZE and DEBUG_LEVEL >= level):
969                sys.stderr.write( msg + '\n' )
970
971        if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
972                syslog.syslog( msg )
973
974def write_pidfile():
975
976        # Write pidfile if PIDFILE exists
977        if PIDFILE:
978
979                pid     = os.getpid()
980
981                pidfile = open(PIDFILE, 'w')
982
983                pidfile.write( str( pid ) )
984                pidfile.close()
985
986def main():
987
988        """Application start"""
989
990        global PBSQuery, PBSError
991        global SYSLOG_FACILITY, USE_SYSLOG, BATCH_API, DAEMONIZE
992
993        if not processArgs( sys.argv[1:] ):
994
995                sys.exit( 1 )
996
997        if BATCH_API == 'pbs':
998
999                try:
1000                        from PBSQuery import PBSQuery, PBSError
1001
1002                except ImportError:
1003
1004                        debug_msg( 0, "FATAL ERROR: BATCH_API set to 'pbs' but python module 'pbs_python' is not installed" )
1005                        sys.exit( 1 )
1006
1007                gather = PbsDataGatherer()
1008
1009        elif BATCH_API == 'sge':
1010
1011                debug_msg( 0, "FATAL ERROR: BATCH_API 'sge' implementation is currently broken, check future releases" )
1012
1013                sys.exit( 1 )
1014
1015                gather = SgeDataGatherer()
1016
1017        else:
1018                debug_msg( 0, "FATAL ERROR: unknown BATCH_API '" + BATCH_API + "' is not supported" )
1019
1020                sys.exit( 1 )
1021
1022        if( DAEMONIZE and USE_SYSLOG ):
1023
1024                syslog.openlog( 'jobmond', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
1025
1026
1027        if DAEMONIZE:
1028
1029                gather.daemon()
1030        else:
1031                gather.run()
1032
1033# wh00t? someone started me! :)
1034#
1035if __name__ == '__main__':
1036        main()
Note: See TracBrowser for help on using the repository browser.