source: branches/0.4/jobmond/jobmond.py @ 702

Last change on this file since 702 was 702, checked in by ramonb, 11 years ago
  • METRIC_MAX_VAL_LEN is now determined from gmond.conf
  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 57.0 KB
Line 
1#!/usr/bin/env python
2#
3# This file is part of Jobmonarch
4#
5# Copyright (C) 2006-2013  Ramon Bastiaans
6# Copyright (C) 2007, 2009  Dave Love  (SGE code)
7#
8# Jobmonarch is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or
11# (at your option) any later version.
12#
13# Jobmonarch is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with this program; if not, write to the Free Software
20# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21#
22# SVN $Id: jobmond.py 702 2013-03-21 15:55:35Z ramonb $
23#
24
25# vi :set ts=4
26
27import sys, getopt, ConfigParser, time, os, socket, string, re
28import xdrlib, socket, syslog, xml, xml.sax, shlex
29from xml.sax.handler import feature_namespaces
30from collections import deque
31from glob import glob
32
33VERSION='0.4+SVN'
34
35def usage( ver ):
36
37    print 'jobmond %s' %VERSION
38
39    if ver:
40        return 0
41
42    print
43    print 'Purpose:'
44    print '  The Job Monitoring Daemon (jobmond) reports batch jobs information and statistics'
45    print '  to Ganglia, which can be viewed with Job Monarch web frontend'
46    print
47    print 'Usage:    jobmond [OPTIONS]'
48    print
49    print '  -c, --config=FILE    The configuration file to use (default: /etc/jobmond.conf)'
50    print '  -p, --pidfile=FILE    Use pid file to store the process id'
51    print '  -h, --help        Print help and exit'
52    print '  -v, --version      Print version and exit'
53    print
54
55def processArgs( args ):
56
57    SHORT_L      = 'p:hvc:'
58    LONG_L       = [ 'help', 'config=', 'pidfile=', 'version' ]
59
60    global PIDFILE JOBMOND_CONF
61    PIDFILE      = None
62
63    JOBMOND_CONF = '/etc/jobmond.conf'
64
65    try:
66
67        opts, args    = getopt.getopt( args, SHORT_L, LONG_L )
68
69    except getopt.GetoptError, detail:
70
71        print detail
72        usage()
73        sys.exit( 1 )
74
75    for opt, value in opts:
76
77        if opt in [ '--config', '-c' ]:
78       
79            JOBMOND_CONF = value
80
81        if opt in [ '--pidfile', '-p' ]:
82
83            PIDFILE      = value
84       
85        if opt in [ '--help', '-h' ]:
86 
87            usage( False )
88            sys.exit( 0 )
89
90        if opt in [ '--version', '-v' ]:
91
92            usage( True )
93            sys.exit( 0 )
94
95    return loadConfig( JOBMOND_CONF )
96
97class GangliaConfigParser:
98
99    def __init__( self, filename ):
100
101        self.conf_lijst   = [ ]
102        self.conf_dict    = { }
103        self.filename     = filename
104        self.file_pointer = file( filename, 'r' )
105        self.lexx         = shlex.shlex( self.file_pointer )
106        self.lexx.whitespace_split = True
107
108        self.parse()
109
110    def __del__( self ):
111
112        """
113        Cleanup: close file descriptor
114        """
115
116        self.file_pointer.close()
117        del self.lexx
118        del self.conf_lijst
119
120    def removeQuotes( self, value ):
121
122        clean_value = value
123        clean_value = clean_value.replace( "'", "" )
124        clean_value = clean_value.replace( '"', '' )
125        clean_value = clean_value.strip()
126
127        return clean_value
128
129    def removeBraces( self, value ):
130
131        clean_value = value
132        clean_value = clean_value.replace( "(", "" )
133        clean_value = clean_value.replace( ')', '' )
134        clean_value = clean_value.strip()
135
136        return clean_value
137
138    def parse( self ):
139
140        """
141        Parse self.filename using shlex scanning.
142        - Removes /* comments */
143        - Traverses (recursively) through all include () statements
144        - Stores complete valid config tokens in self.conf_list
145
146        i.e.:
147            ['globals',
148             '{',
149             'daemonize',
150             '=',
151             'yes',
152             'setuid',
153             '=',
154             'yes',
155             'user',
156             '=',
157             'ganglia',
158             'debug_level',
159             '=',
160             '0',
161             <etc> ]
162        """
163
164        t = 'bogus'
165        c = False
166        i = False
167
168        while t != self.lexx.eof:
169            #print 'get token'
170            t = self.lexx.get_token()
171
172            if len( t ) >= 2:
173
174                if len( t ) >= 4:
175
176                    if t[:2] == '/*' and t[-2:] == '*/':
177
178                        #print 'comment line'
179                        #print 'skipping: %s' %t
180                        continue
181
182                if t == '/*' or t[:2] == '/*':
183                    c = True
184                    #print 'comment start'
185                    #print 'skipping: %s' %t
186                    continue
187
188                if t == '*/' or t[-2:] == '*/':
189                    c = False
190                    #print 'skipping: %s' %t
191                    #print 'comment end'
192                    continue
193
194            if c:
195                #print 'skipping: %s' %t
196                continue
197
198            if t == 'include':
199                i = True
200                #print 'include start'
201                #print 'skipping: %s' %t
202                continue
203
204            if i:
205
206                #print 'include start: %s' %t
207
208                t2 = self.removeQuotes( t )
209                t2 = self.removeBraces( t )
210
211                for in_file in glob( self.removeQuotes(t2) ):
212
213                    #print 'including file: %s' %in_file
214                    parse_infile = GangliaConfigParser( in_file )
215
216                    self.conf_lijst = self.conf_lijst + parse_infile.getConfLijst()
217
218                    del parse_infile
219
220                i = False
221                #print 'include end'
222                #print 'skipping: %s' %t
223                continue
224
225            #print 'keep: %s' %t
226            self.conf_lijst.append( self.removeQuotes(t) )
227
228    def getConfLijst( self ):
229
230        return self.conf_lijst
231
232    def confListToDict( self, parent_list=None ):
233
234        """
235        Recursively traverses a conf_list and creates dictionary from it
236        """
237
238        new_dict = { }
239        count    = 0
240        skip     = 0
241
242        if not parent_list:
243            parent_list = self.conf_lijst
244
245        #print 'entering confListToDict(): (parent) list size %s' %len(parent_list)
246
247        for n, c in enumerate( parent_list ):
248
249            count = count + 1
250
251            #print 'CL: n %d c %s' %(n, c)
252
253            if skip > 0:
254
255                #print '- skipped'
256                skip = skip - 1
257                continue
258
259            if (n+1) <= (len( parent_list )-1):
260
261                if parent_list[(n+1)] == '{':
262
263                    if not new_dict.has_key( c ):
264                        new_dict[ c ] = [ ]
265
266                    (temp_new_dict, skip) = self.confListToDict( parent_list[(n+2):] )
267                    new_dict[ c ].append( temp_new_dict )
268
269                if parent_list[(n+1)] == '=' and (n+2) <= (len( parent_list )-1):
270
271                    if not new_dict.has_key( c ):
272                        new_dict[ c ] = [ ]
273
274                    new_dict[ c ].append( parent_list[ (n+2) ] )
275
276                    skip = 2
277
278                if parent_list[n] == '}':
279
280                    #print 'leaving confListToDict(): new dict = %s' %new_dict
281                    return (new_dict, count)
282
283    def makeConfDict( self ):
284
285        """
286        Walks through self.conf_list and creates a dictionary based upon config values
287
288        i.e.:
289            'tcp_accept_channel': [{'acl': [{'access': [{'action': ['"allow"'],
290                                                         'ip': ['"127.0.0.1"'],
291                                                         'mask': ['32']}]}],
292                                    'port': ['8649']}],
293            'udp_recv_channel': [{'port': ['8649']}],
294            'udp_send_channel': [{'host': ['145.101.32.3'],
295                                  'port': ['8649']},
296                                 {'host': ['145.101.32.207'],
297                                  'port': ['8649']}]}
298        """
299
300        new_dict = { }
301        skip     = 0
302
303        #print 'entering makeConfDict()'
304
305        for n, c in enumerate( self.conf_lijst ):
306
307            #print 'M: n %d c %s' %(n, c)
308
309            if skip > 0:
310
311                #print '- skipped'
312                skip = skip - 1
313                continue
314
315            if (n+1) <= (len( self.conf_lijst )-1):
316
317                if self.conf_lijst[(n+1)] == '{':
318
319                    if not new_dict.has_key( c ):
320                        new_dict[ c ] = [ ]
321
322                    ( temp_new_dict, skip ) = self.confListToDict( self.conf_lijst[(n+2):] )
323                    new_dict[ c ].append( temp_new_dict )
324
325                if self.conf_lijst[(n+1)] == '=' and (n+2) <= (len( self.conf_lijst )-1):
326
327                    if not new_dict.has_key( c ):
328                        new_dict[ c ] = [ ]
329
330                    new_dict[ c ].append( self.conf_lijst[ (n+2) ] )
331
332                    skip = 2
333
334        self.conf_dict = new_dict
335        #print 'leaving makeConfDict(): conf dict size %d' %len( self.conf_dict )
336
337    def checkConfDict( self ):
338
339        if len( self.conf_lijst ) == 0:
340
341            raise Exception("Something went wrong generating conf list for %s" %self.file_name )
342
343        if len( self.conf_dict ) == 0:
344
345            self.makeConfDict()
346
347    def getConfDict( self ):
348
349        self.checkConfDict()
350        return self.conf_dict
351
352    def getUdpSendChannels( self ):
353
354        self.checkConfDict()
355        return self.conf_dict[ 'udp_send_channel' ]
356
357    def getSectionLastOption( self, section, option ):
358
359        """
360        Get last option set in a config section that could be set multiple times in multiple (include) files.
361
362        i.e.: getSectionLastOption( 'globals', 'send_metadata_interval' )
363        """
364
365        self.checkConfDict()
366        value = None
367
368        if not self.conf_dict.has_key( section ):
369
370            return None
371
372        # Could be set multiple times in multiple (include) files: get last one set
373        for c in self.conf_dict[ section ]:
374
375                if c.has_key( option ):
376
377                    cluster_name = c[ option ][0]
378
379        return cluster_name
380
381    def getClusterName( self ):
382
383        return self.getSectionLastOption( 'cluster', 'name' )
384
385    def getVal( self, section, option ):
386
387        return self.getSectionLastOption( section, option )
388
389    def getInt( self, section, valname ):
390
391        value    = self.getVal( section, valname )
392
393        if not value:
394            return None
395
396        return int( value )
397
398    def getStr( self, section, valname ):
399
400        value    = self.getVal( section, valname )
401
402        if not value:
403            return None
404
405        return str( value )
406
407def findGmetric():
408
409    for dir in os.path.expandvars( '$PATH' ).split( ':' ):
410
411        guess    = '%s/%s' %( dir, 'gmetric' )
412
413        if os.path.exists( guess ):
414
415            return guess
416
417    return False
418
419def loadConfig( filename ):
420
421    def getlist( cfg_string ):
422
423        my_list = [ ]
424
425        for item_txt in cfg_string.split( ',' ):
426
427            sep_char = None
428
429            item_txt = item_txt.strip()
430
431            for s_char in [ "'", '"' ]:
432
433                if item_txt.find( s_char ) != -1:
434
435                    if item_txt.count( s_char ) != 2:
436
437                        print 'Missing quote: %s' %item_txt
438                        sys.exit( 1 )
439
440                    else:
441
442                        sep_char = s_char
443                        break
444
445            if sep_char:
446
447                item_txt = item_txt.split( sep_char )[1]
448
449            my_list.append( item_txt )
450
451        return my_list
452
453    cfg        = ConfigParser.ConfigParser()
454
455    cfg.read( filename )
456
457    global DEBUG_LEVEL, DAEMONIZE, BATCH_SERVER, BATCH_POLL_INTERVAL
458    global GMOND_CONF, DETECT_TIME_DIFFS, BATCH_HOST_TRANSLATE
459    global BATCH_API, QUEUE, GMETRIC_TARGET, USE_SYSLOG
460    global SYSLOG_LEVEL, SYSLOG_FACILITY, GMETRIC_BINARY
461    global METRIC_MAX_VAL_LEN
462
463    DEBUG_LEVEL = cfg.getint( 'DEFAULT', 'DEBUG_LEVEL' )
464
465    DAEMONIZE   = cfg.getboolean( 'DEFAULT', 'DAEMONIZE' )
466
467    SYSLOG_LEVEL    = -1
468    SYSLOG_FACILITY = None
469
470    try:
471        USE_SYSLOG  = cfg.getboolean( 'DEFAULT', 'USE_SYSLOG' )
472
473    except ConfigParser.NoOptionError:
474
475        USE_SYSLOG  = True
476
477        debug_msg( 0, 'ERROR: no option USE_SYSLOG found: assuming yes' )
478
479    if USE_SYSLOG:
480
481        try:
482            SYSLOG_LEVEL = cfg.getint( 'DEFAULT', 'SYSLOG_LEVEL' )
483
484        except ConfigParser.NoOptionError:
485
486            debug_msg( 0, 'ERROR: no option SYSLOG_LEVEL found: assuming level 0' )
487            SYSLOG_LEVEL = 0
488
489        try:
490
491            SYSLOG_FACILITY = eval( 'syslog.LOG_' + cfg.get( 'DEFAULT', 'SYSLOG_FACILITY' ) )
492
493        except ConfigParser.NoOptionError:
494
495            SYSLOG_FACILITY = syslog.LOG_DAEMON
496
497            debug_msg( 0, 'ERROR: no option SYSLOG_FACILITY found: assuming facility DAEMON' )
498
499    try:
500
501        BATCH_SERVER = cfg.get( 'DEFAULT', 'BATCH_SERVER' )
502
503    except ConfigParser.NoOptionError:
504
505        # Backwards compatibility for old configs
506        #
507
508        BATCH_SERVER = cfg.get( 'DEFAULT', 'TORQUE_SERVER' )
509        api_guess    = 'pbs'
510   
511    try:
512   
513        BATCH_POLL_INTERVAL = cfg.getint( 'DEFAULT', 'BATCH_POLL_INTERVAL' )
514
515    except ConfigParser.NoOptionError:
516
517        # Backwards compatibility for old configs
518        #
519
520        BATCH_POLL_INTERVAL = cfg.getint( 'DEFAULT', 'TORQUE_POLL_INTERVAL' )
521        api_guess           = 'pbs'
522   
523    try:
524
525        GMOND_CONF          = cfg.get( 'DEFAULT', 'GMOND_CONF' )
526
527    except ConfigParser.NoOptionError:
528
529        # Not specified: assume /etc/gmond.conf
530        #
531        GMOND_CONF          = '/etc/gmond.conf'
532
533    ganglia_cfg     = GangliaConfigParser( GMOND_CONF )
534
535    # Let's try to find the GMETRIC_TARGET ourselves first from GMOND_CONF
536    #
537    gmetric_dest_ip = ganglia_cfg.getStr( 'udp_send_channel', 'mcast_join' )
538
539    if not gmetric_dest_ip:
540
541        # Maybe unicast target then
542        #
543        gmetric_dest_ip = ganglia_cfg.getStr( 'udp_send_channel', 'host' )
544
545    gmetric_dest_port   = ganglia_cfg.getStr( 'udp_send_channel', 'port' )
546
547    #TODO: use multiple udp send channels (if found)
548    if gmetric_dest_ip and gmetric_dest_port:
549
550        GMETRIC_TARGET  = '%s:%s' %( gmetric_dest_ip, gmetric_dest_port )
551    else:
552
553        debug_msg( 0, "WARNING: Can't parse udp_send_channel from: '%s' - Trying: %s" %( GMOND_CONF, JOBMOND_CONF ) )
554
555        # Couldn't figure it out: let's see if it's in our jobmond.conf
556        #
557        try:
558
559            GMETRIC_TARGET    = cfg.get( 'DEFAULT', 'GMETRIC_TARGET' )
560
561        # Guess not: now just give up
562       
563        except ConfigParser.NoOptionError:
564
565            GMETRIC_TARGET    = None
566
567            debug_msg( 0, "ERROR: GMETRIC_TARGET not set: internal Gmetric handling aborted. Failing back to DEPRECATED use of gmond.conf/gmetric binary. This will slow down jobmond significantly!" )
568
569            gmetric_bin    = findGmetric()
570
571            if gmetric_bin:
572
573                GMETRIC_BINARY     = gmetric_bin
574            else:
575                debug_msg( 0, "WARNING: Can't find gmetric binary anywhere in $PATH" )
576
577                try:
578
579                    GMETRIC_BINARY = cfg.get( 'DEFAULT', 'GMETRIC_BINARY' )
580
581                except ConfigParser.NoOptionError:
582
583                    debug_msg( 0, "FATAL ERROR: GMETRIC_BINARY not set and not in $PATH" )
584                    sys.exit( 1 )
585
586    #TODO: is this really still needed or should be automatic
587    DETECT_TIME_DIFFS    = cfg.getboolean( 'DEFAULT', 'DETECT_TIME_DIFFS' )
588
589    BATCH_HOST_TRANSLATE = getlist( cfg.get( 'DEFAULT', 'BATCH_HOST_TRANSLATE' ) )
590
591    try:
592
593        BATCH_API    = cfg.get( 'DEFAULT', 'BATCH_API' )
594
595    except ConfigParser.NoOptionError, detail:
596
597        if BATCH_SERVER and api_guess:
598
599            BATCH_API    = api_guess
600        else:
601            debug_msg( 0, "FATAL ERROR: BATCH_API not set and can't make guess" )
602            sys.exit( 1 )
603
604    try:
605
606        QUEUE        = getlist( cfg.get( 'DEFAULT', 'QUEUE' ) )
607
608    except ConfigParser.NoOptionError, detail:
609
610        QUEUE        = None
611
612    METRIC_MAX_VAL_LEN = ganglia_cfg.getInt( 'globals', 'max_udp_msg_len' )
613
614    return True
615
616def fqdn_parts (fqdn):
617
618    """Return pair of host and domain for fully-qualified domain name arg."""
619
620    parts = fqdn.split (".")
621
622    return (parts[0], string.join(parts[1:], "."))
623
624class DataProcessor:
625
626    """Class for processing of data"""
627
628    binary = None
629
630    def __init__( self, binary=None ):
631
632        """Remember alternate binary location if supplied"""
633
634        global GMETRIC_BINARY, GMOND_CONF
635
636        if binary:
637            self.binary = binary
638
639        if not self.binary:
640            self.binary = GMETRIC_BINARY
641
642        # Timeout for XML
643        #
644        # From ganglia's documentation:
645        #
646        # 'A metric will be deleted DMAX seconds after it is received, and
647        # DMAX=0 means eternal life.'
648
649        self.dmax = str( int( int( BATCH_POLL_INTERVAL ) * 2 ) )
650
651        if GMOND_CONF:
652
653            incompatible = self.checkGmetricVersion()
654
655            if incompatible:
656
657                debug_msg( 0, 'Gmetric version not compatible, please upgrade to at least 3.4.0' )
658                sys.exit( 1 )
659
660    def checkGmetricVersion( self ):
661
662        """
663        Check version of gmetric is at least 3.4.0
664        for the syntax we use
665        """
666
667        global METRIC_MAX_VAL_LEN, GMETRIC_TARGET
668
669        incompatible    = 0
670
671        gfp        = os.popen( self.binary + ' --version' )
672        lines      = gfp.readlines()
673
674        gfp.close()
675
676        for line in lines:
677
678            line = line.split( ' ' )
679
680            if len( line ) == 2 and str( line ).find( 'gmetric' ) != -1:
681           
682                gmetric_version    = line[1].split( '\n' )[0]
683
684                version_major    = int( gmetric_version.split( '.' )[0] )
685                version_minor    = int( gmetric_version.split( '.' )[1] )
686                version_patch    = int( gmetric_version.split( '.' )[2] )
687
688                incompatible    = 0
689
690                if version_major < 3:
691
692                    incompatible = 1
693               
694                elif version_major == 3:
695
696                    if version_minor < 4:
697
698                        incompatible = 1
699
700        return incompatible
701
702    def multicastGmetric( self, metricname, metricval, valtype='string', units='' ):
703
704        """Call gmetric binary and multicast"""
705
706        cmd = self.binary
707
708        if GMETRIC_TARGET:
709
710            GMETRIC_TARGET_HOST    = GMETRIC_TARGET.split( ':' )[0]
711            GMETRIC_TARGET_PORT    = GMETRIC_TARGET.split( ':' )[1]
712
713            metric_debug        = "[gmetric] name: %s - val: %s - dmax: %s" %( str( metricname ), str( metricval ), str( self.dmax ) )
714
715            debug_msg( 10, printTime() + ' ' + metric_debug)
716
717            gm = Gmetric( GMETRIC_TARGET_HOST, GMETRIC_TARGET_PORT )
718
719            gm.send( str( metricname ), str( metricval ), str( self.dmax ), valtype, units )
720
721        else:
722            try:
723                cmd = cmd + ' -c' + GMOND_CONF
724
725            except NameError:
726
727                debug_msg( 10, 'Assuming /etc/gmond.conf for gmetric cmd (omitting)' )
728
729            cmd = cmd + ' -n' + str( metricname )+ ' -v"' + str( metricval )+ '" -t' + str( valtype ) + ' -d' + str( self.dmax )
730
731            if len( units ) > 0:
732
733                cmd = cmd + ' -u"' + units + '"'
734
735            debug_msg( 10, printTime() + ' ' + cmd )
736
737            os.system( cmd )
738
739class DataGatherer:
740
741    """Skeleton class for batch system DataGatherer"""
742
743    def printJobs( self, jobs ):
744
745        """Print a jobinfo overview"""
746
747        for name, attrs in self.jobs.items():
748
749            print 'job %s' %(name)
750
751            for name, val in attrs.items():
752
753                print '\t%s = %s' %( name, val )
754
755    def printJob( self, jobs, job_id ):
756
757        """Print job with job_id from jobs"""
758
759        print 'job %s' %(job_id)
760
761        for name, val in jobs[ job_id ].items():
762
763            print '\t%s = %s' %( name, val )
764
765    def getAttr( self, attrs, name ):
766
767        """Return certain attribute from dictionary, if exists"""
768
769        if attrs.has_key( name ):
770
771            return attrs[ name ]
772        else:
773            return ''
774
775    def jobDataChanged( self, jobs, job_id, attrs ):
776
777        """Check if job with attrs and job_id in jobs has changed"""
778
779        if jobs.has_key( job_id ):
780
781            oldData = jobs[ job_id ]   
782        else:
783            return 1
784
785        for name, val in attrs.items():
786
787            if oldData.has_key( name ):
788
789                if oldData[ name ] != attrs[ name ]:
790
791                    return 1
792
793            else:
794                return 1
795
796        return 0
797
798    def submitJobData( self ):
799
800        """Submit job info list"""
801
802        global BATCH_API
803
804        self.dp.multicastGmetric( 'MONARCH-HEARTBEAT', str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
805
806        running_jobs    = 0
807        queued_jobs    = 0
808
809        # Count how many running/queued jobs we found
810        #
811        for jobid, jobattrs in self.jobs.items():
812
813            if jobattrs[ 'status' ] == 'Q':
814
815                queued_jobs += 1
816
817            elif jobattrs[ 'status' ] == 'R':
818
819                running_jobs += 1
820
821        # Report running/queued jobs as seperate metric for a nice RRD graph
822        #
823        self.dp.multicastGmetric( 'MONARCH-RJ', str( running_jobs ), 'uint32', 'jobs' )
824        self.dp.multicastGmetric( 'MONARCH-QJ', str( queued_jobs ), 'uint32', 'jobs' )
825
826        # Report down/offline nodes in batch (PBS only ATM)
827        #
828        if BATCH_API == 'pbs':
829
830            domain        = fqdn_parts( socket.getfqdn() )[1]
831
832            downed_nodes    = list()
833            offline_nodes    = list()
834       
835            l        = ['state']
836       
837            for name, node in self.pq.getnodes().items():
838
839                if ( node[ 'state' ].find( "down" ) != -1 ):
840
841                    downed_nodes.append( name )
842
843                if ( node[ 'state' ].find( "offline" ) != -1 ):
844
845                    offline_nodes.append( name )
846
847            downnodeslist        = do_nodelist( downed_nodes )
848            offlinenodeslist    = do_nodelist( offline_nodes )
849
850            down_str    = 'nodes=%s domain=%s reported=%s' %( string.join( downnodeslist, ';' ), domain, str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
851            offl_str    = 'nodes=%s domain=%s reported=%s' %( string.join( offlinenodeslist, ';' ), domain, str( int( int( self.cur_time ) + int( self.timeoffset ) ) ) )
852            self.dp.multicastGmetric( 'MONARCH-DOWN'   , down_str )
853            self.dp.multicastGmetric( 'MONARCH-OFFLINE', offl_str )
854
855        # Now let's spread the knowledge
856        #
857        for jobid, jobattrs in self.jobs.items():
858
859            # Make gmetric values for each job: respect max gmetric value length
860            #
861            gmetric_val        = self.compileGmetricVal( jobid, jobattrs )
862            metric_increment    = 0
863
864            # If we have more job info than max gmetric value length allows, split it up
865            # amongst multiple metrics
866            #
867            for val in gmetric_val:
868
869                self.dp.multicastGmetric( 'MONARCH-JOB-' + jobid + '-' + str(metric_increment), val )
870
871                # Increase follow number if this jobinfo is split up amongst more than 1 gmetric
872                #
873                metric_increment    = metric_increment + 1
874
875    def compileGmetricVal( self, jobid, jobattrs ):
876
877        """Create a val string for gmetric of jobinfo"""
878
879        gval_lists    = [ ]
880        val_list    = { }
881
882        for val_name, val_value in jobattrs.items():
883
884            # These are our own metric names, i.e.: status, start_timestamp, etc
885            #
886            val_list_names_len    = len( string.join( val_list.keys() ) ) + len(val_list.keys())
887
888            # These are their corresponding values
889            #
890            val_list_vals_len    = len( string.join( val_list.values() ) ) + len(val_list.values())
891
892            if val_name == 'nodes' and jobattrs['status'] == 'R':
893
894                node_str = None
895
896                for node in val_value:
897
898                    if node_str:
899
900                        node_str = node_str + ';' + node
901                    else:
902                        node_str = node
903
904                    # Make sure if we add this new info, that the total metric's value length does not exceed METRIC_MAX_VAL_LEN
905                    #
906                    if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(node_str) ) > METRIC_MAX_VAL_LEN:
907
908                        # It's too big, we need to make a new gmetric for the additional info
909                        #
910                        val_list[ val_name ]    = node_str
911
912                        gval_lists.append( val_list )
913
914                        val_list        = { }
915                        node_str        = None
916
917                val_list[ val_name ]    = node_str
918
919                gval_lists.append( val_list )
920
921                val_list        = { }
922
923            elif val_value != '':
924
925                # Make sure if we add this new info, that the total metric's value length does not exceed METRIC_MAX_VAL_LEN
926                #
927                if (val_list_names_len + len(val_name) ) + (val_list_vals_len + len(str(val_value)) ) > METRIC_MAX_VAL_LEN:
928
929                    # It's too big, we need to make a new gmetric for the additional info
930                    #
931                    gval_lists.append( val_list )
932
933                    val_list        = { }
934
935                val_list[ val_name ]    = val_value
936
937        if len( val_list ) > 0:
938
939            gval_lists.append( val_list )
940
941        str_list    = [ ]
942
943        # Now append the value names and values together, i.e.: stop_timestamp=value, etc
944        #
945        for val_list in gval_lists:
946
947            my_val_str    = None
948
949            for val_name, val_value in val_list.items():
950
951                if type(val_value) == list:
952
953                    val_value    = val_value.join( ',' )
954
955                if my_val_str:
956
957                    try:
958                        # fixme: It's getting
959                        # ('nodes', None) items
960                        my_val_str = my_val_str + ' ' + val_name + '=' + val_value
961                    except:
962                        pass
963
964                else:
965                    my_val_str = val_name + '=' + val_value
966
967            str_list.append( my_val_str )
968
969        return str_list
970
971    def daemon( self ):
972
973        """Run as daemon forever"""
974
975        # Fork the first child
976        #
977        pid = os.fork()
978        if pid > 0:
979            sys.exit(0)  # end parent
980
981        # creates a session and sets the process group ID
982        #
983        os.setsid()
984
985        # Fork the second child
986        #
987        pid = os.fork()
988        if pid > 0:
989            sys.exit(0)  # end parent
990
991        write_pidfile()
992
993        # Go to the root directory and set the umask
994        #
995        os.chdir('/')
996        os.umask(0)
997
998        sys.stdin.close()
999        sys.stdout.close()
1000        sys.stderr.close()
1001
1002        os.open('/dev/null', os.O_RDWR)
1003        os.dup2(0, 1)
1004        os.dup2(0, 2)
1005
1006        self.run()
1007
1008    def run( self ):
1009
1010        """Main thread"""
1011
1012        while ( 1 ):
1013       
1014            self.getJobData()
1015            self.submitJobData()
1016            time.sleep( BATCH_POLL_INTERVAL )   
1017
1018# SGE code by Dave Love <fx@gnu.org>.  Tested with SGE 6.0u8 and 6.0u11.  May
1019# work with SGE 6.1 (else should be easily fixable), but definitely doesn't
1020# with 6.2.  See also the fixmes.
1021
1022class NoJobs (Exception):
1023    """Exception raised by empty job list in qstat output."""
1024    pass
1025
1026class SgeQstatXMLParser(xml.sax.handler.ContentHandler):
1027    """SAX handler for XML output from Sun Grid Engine's `qstat'."""
1028
1029    def __init__(self):
1030        self.value = ""
1031        self.joblist = []
1032        self.job = {}
1033        self.queue = ""
1034        self.in_joblist = False
1035        self.lrequest = False
1036        self.eltq = deque()
1037        xml.sax.handler.ContentHandler.__init__(self)
1038
1039    # The structure of the output is as follows (for SGE 6.0).  It's
1040    # similar for 6.1, but radically different for 6.2, and is
1041    # undocumented generally.  Unfortunately it's voluminous, and probably
1042    # doesn't scale to large clusters/queues.
1043
1044    # <detailed_job_info  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
1045    #   <djob_info>
1046    #     <qmaster_response>  <!-- job -->
1047    #       ...
1048    #       <JB_ja_template> 
1049    #     <ulong_sublist>
1050    #     ...         <!-- start_time, state ... -->
1051    #     </ulong_sublist>
1052    #       </JB_ja_template> 
1053    #       <JB_ja_tasks>
1054    #     <ulong_sublist>
1055    #       ...       <!-- task info
1056    #     </ulong_sublist>
1057    #     ...
1058    #       </JB_ja_tasks>
1059    #       ...
1060    #     </qmaster_response>
1061    #   </djob_info>
1062    #   <messages>
1063    #   ...
1064
1065    # NB.  We might treat each task as a separate job, like
1066    # straight qstat output, but the web interface expects jobs to
1067    # be identified by integers, not, say, <job number>.<task>.
1068
1069    # So, I lied.  If the job list is empty, we get invalid XML
1070    # like this, which we need to defend against:
1071
1072    # <unknown_jobs  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
1073    #   <>
1074    #     <ST_name>*</ST_name>
1075    #   </>
1076    # </unknown_jobs>
1077
1078    def startElement(self, name, attrs):
1079        self.value = ""
1080        if name == "djob_info":    # job list
1081            self.in_joblist = True
1082        # The job container is "qmaster_response" in SGE 6.0
1083        # and 6.1, but "element" in 6.2.  This is only the very
1084        # start of what's necessary for 6.2, though (sigh).
1085        elif (name == "qmaster_response" or name == "element") \
1086                and self.eltq[-1] == "djob_info": # job
1087            self.job = {"job_state": "U", "slots": 0,
1088                    "nodes": [], "queued_timestamp": "",
1089                    "queued_timestamp": "", "queue": "",
1090                    "ppn": "0", "RN_max": 0,
1091                    # fixme in endElement
1092                    "requested_memory": 0, "requested_time": 0
1093                    }
1094            self.joblist.append(self.job)
1095        elif name == "qstat_l_requests": # resource request
1096            self.lrequest = True
1097        elif name == "unknown_jobs":
1098            raise NoJobs
1099        self.eltq.append (name)
1100
1101    def characters(self, ch):
1102        self.value += ch
1103
1104    def endElement(self, name): 
1105        """Snarf job elements contents into job dictionary.
1106           Translate keys if appropriate."""
1107
1108        name_trans = {
1109          "JB_job_number": "number",
1110          "JB_job_name": "name", "JB_owner": "owner",
1111          "queue_name": "queue", "JAT_start_time": "start_timestamp",
1112          "JB_submission_time": "queued_timestamp"
1113          }
1114        value = self.value
1115        self.eltq.pop ()
1116
1117        if name == "djob_info":
1118            self.in_joblist = False
1119            self.job = {}
1120        elif name == "JAT_master_queue":
1121            self.job["queue"] = value.split("@")[0]
1122        elif name == "JG_qhostname":
1123            if not (value in self.job["nodes"]):
1124                self.job["nodes"].append(value)
1125        elif name == "JG_slots": # slots in use
1126            self.job["slots"] += int(value)
1127        elif name == "RN_max": # requested slots (tasks or parallel)
1128            self.job["RN_max"] = max (self.job["RN_max"],
1129                          int(value))
1130        elif name == "JAT_state": # job state (bitwise or)
1131            value = int (value)
1132            # Status values from sge_jobL.h
1133            #define JIDLE           0x00000000
1134            #define JHELD           0x00000010
1135            #define JMIGRATING          0x00000020
1136            #define JQUEUED         0x00000040
1137            #define JRUNNING        0x00000080
1138            #define JSUSPENDED          0x00000100
1139            #define JTRANSFERING        0x00000200
1140            #define JDELETED        0x00000400
1141            #define JWAITING        0x00000800
1142            #define JEXITING        0x00001000
1143            #define JWRITTEN        0x00002000
1144            #define JSUSPENDED_ON_THRESHOLD 0x00010000
1145            #define JFINISHED           0x00010000
1146            if value & 0x80:
1147                self.job["status"] = "R"
1148            elif value & 0x40:
1149                self.job["status"] = "Q"
1150            else:
1151                self.job["status"] = "O" # `other'
1152        elif name == "CE_name" and self.lrequest and self.value in \
1153                ("h_cpu", "s_cpu", "cpu", "h_core", "s_core"):
1154            # We're in a container for an interesting resource
1155            # request; record which type.
1156            self.lrequest = self.value
1157        elif name == "CE_doubleval" and self.lrequest:
1158            # if we're in a container for an interesting
1159            # resource request, use the maxmimum of the hard
1160            # and soft requests to record the requested CPU
1161            # or core.  Fixme:  I'm not sure if this logic is
1162            # right.
1163            if self.lrequest in ("h_core", "s_core"):
1164                self.job["requested_memory"] = \
1165                    max (float (value),
1166                     self.job["requested_memory"])
1167            # Fixme:  Check what cpu means, c.f [hs]_cpu.
1168            elif self.lrequest in ("h_cpu", "s_cpu", "cpu"):
1169                self.job["requested_time"] = \
1170                    max (float (value),
1171                     self.job["requested_time"])
1172        elif name == "qstat_l_requests":
1173            self.lrequest = False
1174        elif self.job and self.in_joblist:
1175            if name in name_trans:
1176                name = name_trans[name]
1177                self.job[name] = value
1178
1179# Abstracted from PBS original.
1180# Fixme:  Is it worth (or appropriate for PBS) sorting the result?
1181#
1182def do_nodelist( nodes ):
1183
1184    """Translate node list as appropriate."""
1185
1186    nodeslist        = [ ]
1187    my_domain        = fqdn_parts( socket.getfqdn() )[1]
1188
1189    for node in nodes:
1190
1191        host        = node.split( '/' )[0] # not relevant for SGE
1192        h, host_domain    = fqdn_parts(host)
1193
1194        if host_domain == my_domain:
1195
1196            host    = h
1197
1198        if nodeslist.count( host ) == 0:
1199
1200            for translate_pattern in BATCH_HOST_TRANSLATE:
1201
1202                if translate_pattern.find( '/' ) != -1:
1203
1204                    translate_orig    = \
1205                        translate_pattern.split( '/' )[1]
1206                    translate_new    = \
1207                        translate_pattern.split( '/' )[2]
1208                    host = re.sub( translate_orig,
1209                               translate_new, host )
1210            if not host in nodeslist:
1211                nodeslist.append( host )
1212    return nodeslist
1213
1214class SgeDataGatherer(DataGatherer):
1215
1216    jobs = {}
1217
1218    def __init__( self ):
1219        self.jobs = {}
1220        self.timeoffset = 0
1221        self.dp = DataProcessor()
1222
1223    def getJobData( self ):
1224        """Gather all data on current jobs in SGE"""
1225
1226        import popen2
1227
1228        self.cur_time = 0
1229        queues = ""
1230        if QUEUE:    # only for specific queues
1231            # Fixme:  assumes queue names don't contain single
1232            # quote or comma.  Don't know what the SGE rules are.
1233            queues = " -q '" + string.join (QUEUE, ",") + "'"
1234        # Note the comment in SgeQstatXMLParser about scaling with
1235        # this method of getting data.  I haven't found better one.
1236        # Output with args `-xml -ext -f -r' is easier to parse
1237        # in some ways, harder in others, but it doesn't provide
1238        # the submission time (at least SGE 6.0).  The pipeline
1239        # into sed corrects bogus XML observed with a configuration
1240        # of SGE 6.0u8, which otherwise causes the parsing to hang.
1241        piping = popen2.Popen3("qstat -u '*' -j '*' -xml | \
1242sed -e 's/reported usage>/reported_usage>/g' -e 's;<\/*JATASK:.*>;;'" \
1243                           + queues, True)
1244        qstatparser = SgeQstatXMLParser()
1245        parse_err = 0
1246        try:
1247            xml.sax.parse(piping.fromchild, qstatparser)
1248        except NoJobs:
1249            pass
1250        except:
1251            parse_err = 1
1252               if piping.wait():
1253            debug_msg(10,
1254                  "qstat error, skipping until next polling interval: "
1255                  + piping.childerr.readline())
1256            return None
1257        elif parse_err:
1258            debug_msg(10, "Bad XML output from qstat"())
1259            exit (1)
1260        for f in piping.fromchild, piping.tochild, piping.childerr:
1261            f.close()
1262        self.cur_time = time.time()
1263        jobs_processed = []
1264        for job in qstatparser.joblist:
1265            job_id = job["number"]
1266            if job["status"] in [ 'Q', 'R' ]:
1267                jobs_processed.append(job_id)
1268            if job["status"] == "R":
1269                job["nodes"] = do_nodelist (job["nodes"])
1270                # Fixme: why is job["nodes"] sometimes null?
1271                try:
1272                    # Fixme: Is this sensible?  The
1273                    # PBS-type PPN isn't something you use
1274                    # with SGE.
1275                    job["ppn"] = float(job["slots"]) / \
1276                        len(job["nodes"])
1277                except:
1278                    job["ppn"] = 0
1279                if DETECT_TIME_DIFFS:
1280                    # If a job start is later than our
1281                    # current date, that must mean
1282                    # the SGE server's time is later
1283                    # than our local time.
1284                    start_timestamp = \
1285                        int (job["start_timestamp"])
1286                    if start_timestamp > \
1287                            int(self.cur_time) + \
1288                            int(self.timeoffset):
1289
1290                        self.timeoffset    = \
1291                            start_timestamp - \
1292                            int(self.cur_time)
1293            else:
1294                # fixme: Note sure what this should be:
1295                job["ppn"] = job["RN_max"]
1296                job["nodes"] = "1"
1297
1298            myAttrs = {}
1299            for attr in ["name", "queue", "owner",
1300                     "requested_time", "status",
1301                     "requested_memory", "ppn",
1302                     "start_timestamp", "queued_timestamp"]:
1303                myAttrs[attr] = str(job[attr])
1304            myAttrs["nodes"] = job["nodes"]
1305            myAttrs["reported"] = str(int(self.cur_time) + \
1306                          int(self.timeoffset))
1307            myAttrs["domain"] = fqdn_parts(socket.getfqdn())[1]
1308            myAttrs["poll_interval"] = str(BATCH_POLL_INTERVAL)
1309
1310            if self.jobDataChanged(self.jobs, job_id, myAttrs) \
1311                    and myAttrs["status"] in ["R", "Q"]:
1312                self.jobs[job_id] = myAttrs
1313        for id, attrs in self.jobs.items():
1314            if id not in jobs_processed:
1315                del self.jobs[id]
1316
1317# LSF code by Mahmoud Hanafi <hanafim@users.sourceforge.nt>
1318# Requres LSFObject http://sourceforge.net/projects/lsfobject
1319#
1320class LsfDataGatherer(DataGatherer):
1321
1322    """This is the DataGatherer for LSf"""
1323
1324    global lsfObject
1325
1326    def __init__( self ):
1327
1328        self.jobs = { }
1329        self.timeoffset = 0
1330        self.dp = DataProcessor()
1331        self.initLsfQuery()
1332
1333    def _countDuplicatesInList( self, dupedList ):
1334
1335        countDupes    = { }
1336
1337        for item in dupedList:
1338
1339            if not countDupes.has_key( item ):
1340
1341                countDupes[ item ]    = 1
1342            else:
1343                countDupes[ item ]    = countDupes[ item ] + 1
1344
1345        dupeCountList    = [ ]
1346
1347        for item, count in countDupes.items():
1348
1349            dupeCountList.append( ( item, count ) )
1350
1351        return dupeCountList
1352#
1353#lst = ['I1','I2','I1','I3','I4','I4','I7','I7','I7','I7','I7']
1354#print _countDuplicatesInList(lst)
1355#[('I1', 2), ('I3', 1), ('I2', 1), ('I4', 2), ('I7', 5)]
1356########################
1357
1358    def initLsfQuery( self ):
1359        self.pq = None
1360        self.pq = lsfObject.jobInfoEntObject()
1361
1362    def getJobData( self, known_jobs="" ):
1363        """Gather all data on current jobs in LSF"""
1364        if len( known_jobs ) > 0:
1365            jobs = known_jobs
1366        else:
1367            jobs = { }
1368        joblist = {}
1369        joblist = self.pq.getJobInfo()
1370        nodelist = ''
1371
1372        self.cur_time = time.time()
1373
1374        jobs_processed = [ ]
1375
1376        for name, attrs in joblist.items():
1377            job_id = str(name)
1378            jobs_processed.append( job_id )
1379            name = self.getAttr( attrs, 'jobName' )
1380            queue = self.getAttr( self.getAttr( attrs, 'submit') , 'queue' )
1381            owner = self.getAttr( attrs, 'user' )
1382
1383### THIS IS THE rLimit List index values
1384#define LSF_RLIMIT_CPU      0        /* cpu time in milliseconds */
1385#define LSF_RLIMIT_FSIZE    1        /* maximum file size */
1386#define LSF_RLIMIT_DATA     2        /* data size */
1387#define LSF_RLIMIT_STACK    3        /* stack size */
1388#define LSF_RLIMIT_CORE     4        /* core file size */
1389#define LSF_RLIMIT_RSS      5        /* resident set size */
1390#define LSF_RLIMIT_NOFILE   6        /* open files */
1391#define LSF_RLIMIT_OPEN_MAX 7        /* (from HP-UX) */
1392#define LSF_RLIMIT_VMEM     8        /* maximum swap mem */
1393#define LSF_RLIMIT_SWAP     8
1394#define LSF_RLIMIT_RUN      9        /* max wall-clock time limit */
1395#define LSF_RLIMIT_PROCESS  10       /* process number limit */
1396#define LSF_RLIMIT_THREAD   11       /* thread number limit (introduced in LSF6.0) */
1397#define LSF_RLIM_NLIMITS    12       /* number of resource limits */
1398
1399            requested_time = self.getAttr( self.getAttr( attrs, 'submit') , 'rLimits' )[9]
1400            if requested_time == -1: 
1401                requested_time = ""
1402            requested_memory = self.getAttr( self.getAttr( attrs, 'submit') , 'rLimits' )[8]
1403            if requested_memory == -1: 
1404                requested_memory = ""
1405# This tries to get proc per node. We don't support this right now
1406            ppn = 0 #self.getAttr( self.getAttr( attrs, 'SubmitList') , 'numProessors' )
1407            requested_cpus = self.getAttr( self.getAttr( attrs, 'submit') , 'numProcessors' )
1408            if requested_cpus == None or requested_cpus == "":
1409                requested_cpus = 1
1410
1411            if QUEUE:
1412                for q in QUEUE:
1413                    if q == queue:
1414                        display_queue = 1
1415                        break
1416                    else:
1417                        display_queue = 0
1418                        continue
1419            if display_queue == 0:
1420                continue
1421
1422            runState = self.getAttr( attrs, 'status' )
1423            if runState == 4:
1424                status = 'R'
1425            else:
1426                status = 'Q'
1427            queued_timestamp = self.getAttr( attrs, 'submitTime' )
1428
1429            if status == 'R':
1430                start_timestamp = self.getAttr( attrs, 'startTime' )
1431                nodesCpu =  dict(self._countDuplicatesInList(self.getAttr( attrs, 'exHosts' )))
1432                nodelist = nodesCpu.keys()
1433
1434                if DETECT_TIME_DIFFS:
1435
1436                    # If a job start if later than our current date,
1437                    # that must mean the Torque server's time is later
1438                    # than our local time.
1439
1440                    if int(start_timestamp) > int( int(self.cur_time) + int(self.timeoffset) ):
1441
1442                        self.timeoffset = int( int(start_timestamp) - int(self.cur_time) )
1443
1444            elif status == 'Q':
1445                start_timestamp = ''
1446                count_mynodes = 0
1447                numeric_node = 1
1448                nodelist = ''
1449
1450            myAttrs = { }
1451            if name == "":
1452                myAttrs['name'] = "none"
1453            else:
1454                myAttrs['name'] = name
1455
1456            myAttrs[ 'owner' ]        = owner
1457            myAttrs[ 'requested_time' ]    = str(requested_time)
1458            myAttrs[ 'requested_memory' ]    = str(requested_memory)
1459            myAttrs[ 'requested_cpus' ]    = str(requested_cpus)
1460            myAttrs[ 'ppn' ]        = str( ppn )
1461            myAttrs[ 'status' ]        = status
1462            myAttrs[ 'start_timestamp' ]    = str(start_timestamp)
1463            myAttrs[ 'queue' ]        = str(queue)
1464            myAttrs[ 'queued_timestamp' ]    = str(queued_timestamp)
1465            myAttrs[ 'reported' ]        = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1466            myAttrs[ 'nodes' ]        = do_nodelist( nodelist )
1467            myAttrs[ 'domain' ]        = fqdn_parts( socket.getfqdn() )[1]
1468            myAttrs[ 'poll_interval' ]    = str(BATCH_POLL_INTERVAL)
1469
1470            if self.jobDataChanged( jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
1471                jobs[ job_id ] = myAttrs
1472
1473                debug_msg( 10, printTime() + ' job %s state changed' %(job_id) )
1474
1475        for id, attrs in jobs.items():
1476            if id not in jobs_processed:
1477                # This one isn't there anymore
1478                #
1479                del jobs[ id ]
1480        self.jobs=jobs
1481
1482
1483class PbsDataGatherer( DataGatherer ):
1484
1485    """This is the DataGatherer for PBS and Torque"""
1486
1487    global PBSQuery, PBSError
1488
1489    def __init__( self ):
1490
1491        """Setup appropriate variables"""
1492
1493        self.jobs    = { }
1494        self.timeoffset    = 0
1495        self.dp        = DataProcessor()
1496
1497        self.initPbsQuery()
1498
1499    def initPbsQuery( self ):
1500
1501        self.pq        = None
1502
1503        if( BATCH_SERVER ):
1504
1505            self.pq        = PBSQuery( BATCH_SERVER )
1506        else:
1507            self.pq        = PBSQuery()
1508
1509        try:
1510            self.pq.old_data_structure()
1511
1512        except AttributeError:
1513
1514            # pbs_query is older
1515            #
1516            pass
1517
1518    def getJobData( self ):
1519
1520        """Gather all data on current jobs in Torque"""
1521
1522        joblist        = {}
1523        self.cur_time    = 0
1524
1525        try:
1526            joblist        = self.pq.getjobs()
1527            self.cur_time    = time.time()
1528
1529        except PBSError, detail:
1530
1531            debug_msg( 10, "Caught PBS unavailable, skipping until next polling interval: " + str( detail ) )
1532            return None
1533
1534        jobs_processed    = [ ]
1535
1536        for name, attrs in joblist.items():
1537            display_queue        = 1
1538            job_id            = name.split( '.' )[0]
1539
1540            name            = self.getAttr( attrs, 'Job_Name' )
1541            queue            = self.getAttr( attrs, 'queue' )
1542
1543            if QUEUE:
1544                for q in QUEUE:
1545                    if q == queue:
1546                        display_queue = 1
1547                        break
1548                    else:
1549                        display_queue = 0
1550                        continue
1551            if display_queue == 0:
1552                continue
1553
1554
1555            owner            = self.getAttr( attrs, 'Job_Owner' ).split( '@' )[0]
1556            requested_time        = self.getAttr( attrs, 'Resource_List.walltime' )
1557            requested_memory    = self.getAttr( attrs, 'Resource_List.mem' )
1558
1559            mynoderequest        = self.getAttr( attrs, 'Resource_List.nodes' )
1560
1561            ppn            = ''
1562
1563            if mynoderequest.find( ':' ) != -1 and mynoderequest.find( 'ppn' ) != -1:
1564
1565                mynoderequest_fields    = mynoderequest.split( ':' )
1566
1567                for mynoderequest_field in mynoderequest_fields:
1568
1569                    if mynoderequest_field.find( 'ppn' ) != -1:
1570
1571                        ppn    = mynoderequest_field.split( 'ppn=' )[1]
1572
1573            status            = self.getAttr( attrs, 'job_state' )
1574
1575            if status in [ 'Q', 'R' ]:
1576
1577                jobs_processed.append( job_id )
1578
1579            queued_timestamp    = self.getAttr( attrs, 'ctime' )
1580
1581            if status == 'R':
1582
1583                start_timestamp        = self.getAttr( attrs, 'mtime' )
1584                nodes            = self.getAttr( attrs, 'exec_host' ).split( '+' )
1585
1586                nodeslist        = do_nodelist( nodes )
1587
1588                if DETECT_TIME_DIFFS:
1589
1590                    # If a job start if later than our current date,
1591                    # that must mean the Torque server's time is later
1592                    # than our local time.
1593               
1594                    if int( start_timestamp ) > int( int( self.cur_time ) + int( self.timeoffset ) ):
1595
1596                        self.timeoffset    = int( int(start_timestamp) - int(self.cur_time) )
1597
1598            elif status == 'Q':
1599
1600                # 'mynodequest' can be a string in the following syntax according to the
1601                # Torque Administator's manual:
1602                #
1603                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1604                # {<node_count> | <hostname>}[:ppn=<ppn>][:<property>[:<property>]...][+ ...]
1605                # etc
1606                #
1607
1608                #
1609                # For now we only count the amount of nodes request and ignore properties
1610                #
1611
1612                start_timestamp        = ''
1613                count_mynodes        = 0
1614
1615                for node in mynoderequest.split( '+' ):
1616
1617                    # Just grab the {node_count|hostname} part and ignore properties
1618                    #
1619                    nodepart    = node.split( ':' )[0]
1620
1621                    # Let's assume a node_count value
1622                    #
1623                    numeric_node    = 1
1624
1625                    # Chop the value up into characters
1626                    #
1627                    for letter in nodepart:
1628
1629                        # If this char is not a digit (0-9), this must be a hostname
1630                        #
1631                        if letter not in string.digits:
1632
1633                            numeric_node    = 0
1634
1635                    # If this is a hostname, just count this as one (1) node
1636                    #
1637                    if not numeric_node:
1638
1639                        count_mynodes    = count_mynodes + 1
1640                    else:
1641
1642                        # If this a number, it must be the node_count
1643                        # and increase our count with it's value
1644                        #
1645                        try:
1646                            count_mynodes    = count_mynodes + int( nodepart )
1647
1648                        except ValueError, detail:
1649
1650                            # When we arrive here I must be bugged or very confused
1651                            # THIS SHOULD NOT HAPPEN!
1652                            #
1653                            debug_msg( 10, str( detail ) )
1654                            debug_msg( 10, "Encountered weird node in Resources_List?!" )
1655                            debug_msg( 10, 'nodepart = ' + str( nodepart ) )
1656                            debug_msg( 10, 'job = ' + str( name ) )
1657                            debug_msg( 10, 'attrs = ' + str( attrs ) )
1658                       
1659                nodeslist    = str( count_mynodes )
1660            else:
1661                start_timestamp    = ''
1662                nodeslist    = ''
1663
1664            myAttrs                = { }
1665
1666            myAttrs[ 'name' ]        = str( name )
1667            myAttrs[ 'queue' ]        = str( queue )
1668            myAttrs[ 'owner' ]        = str( owner )
1669            myAttrs[ 'requested_time' ]    = str( requested_time )
1670            myAttrs[ 'requested_memory' ]    = str( requested_memory )
1671            myAttrs[ 'ppn' ]        = str( ppn )
1672            myAttrs[ 'status' ]        = str( status )
1673            myAttrs[ 'start_timestamp' ]    = str( start_timestamp )
1674            myAttrs[ 'queued_timestamp' ]    = str( queued_timestamp )
1675            myAttrs[ 'reported' ]        = str( int( int( self.cur_time ) + int( self.timeoffset ) ) )
1676            myAttrs[ 'nodes' ]        = nodeslist
1677            myAttrs[ 'domain' ]        = fqdn_parts( socket.getfqdn() )[1]
1678            myAttrs[ 'poll_interval' ]    = str( BATCH_POLL_INTERVAL )
1679
1680            if self.jobDataChanged( self.jobs, job_id, myAttrs ) and myAttrs['status'] in [ 'R', 'Q' ]:
1681
1682                self.jobs[ job_id ]    = myAttrs
1683
1684        for id, attrs in self.jobs.items():
1685
1686            if id not in jobs_processed:
1687
1688                # This one isn't there anymore; toedeledoki!
1689                #
1690                del self.jobs[ id ]
1691
1692GMETRIC_DEFAULT_TYPE    = 'string'
1693GMETRIC_DEFAULT_HOST    = '127.0.0.1'
1694GMETRIC_DEFAULT_PORT    = '8649'
1695GMETRIC_DEFAULT_UNITS   = ''
1696
1697class Gmetric:
1698
1699    global GMETRIC_DEFAULT_HOST, GMETRIC_DEFAULT_PORT
1700
1701    slope           = { 'zero' : 0, 'positive' : 1, 'negative' : 2, 'both' : 3, 'unspecified' : 4 }
1702    type            = ( '', 'string', 'uint16', 'int16', 'uint32', 'int32', 'float', 'double', 'timestamp' )
1703    protocol        = ( 'udp', 'multicast' )
1704
1705    def __init__( self, host=GMETRIC_DEFAULT_HOST, port=GMETRIC_DEFAULT_PORT ):
1706               
1707        global GMETRIC_DEFAULT_TYPE
1708
1709        self.prot       = self.checkHostProtocol( host )
1710        self.data_msg   = xdrlib.Packer()
1711        self.meta_msg   = xdrlib.Packer()
1712        self.socket     = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
1713
1714        if self.prot not in self.protocol:
1715
1716            raise ValueError( "Protocol must be one of: " + str( self.protocol ) )
1717
1718        if self.prot == 'multicast':
1719
1720            # Set multicast options
1721            #
1722            self.socket.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20 )
1723
1724        self.hostport   = ( host, int( port ) )
1725        self.slopestr   = 'both'
1726        self.tmax       = 60
1727
1728    def checkHostProtocol( self, ip ):
1729
1730        """Detect if a ip adress is a multicast address"""
1731
1732        MULTICAST_ADDRESS_MIN   = ( "224", "0", "0", "0" )
1733        MULTICAST_ADDRESS_MAX   = ( "239", "255", "255", "255" )
1734
1735        ip_fields               = ip.split( '.' )
1736
1737        if ip_fields >= MULTICAST_ADDRESS_MIN and ip_fields <= MULTICAST_ADDRESS_MAX:
1738
1739            return 'multicast'
1740        else:
1741            return 'udp'
1742
1743    def send( self, name, value, dmax, typestr = '', units = '' ):
1744
1745        if len( units ) == 0:
1746            units       = GMETRIC_DEFAULT_UNITS
1747
1748        if len( typestr ) == 0:
1749            typestr     = GMETRIC_DEFAULT_TYPE
1750
1751        (meta_msg, data_msg) = self.makexdr( name, value, typestr, units, self.slopestr, self.tmax, dmax )
1752
1753        meta_rt = self.socket.sendto( meta_msg, self.hostport )
1754        data_rt = self.socket.sendto( data_msg, self.hostport )
1755
1756        return ( meta_rt, data_rt )
1757
1758    def makexdr( self, name, value, typestr, unitstr, slopestr, tmax, dmax, group=None, spoof=None ):
1759
1760        hostname = "unset"
1761
1762        if slopestr not in self.slope:
1763
1764            raise ValueError( "Slope must be one of: " + str( self.slope.keys() ) )
1765
1766        if typestr not in self.type:
1767
1768            raise ValueError( "Type must be one of: " + str( self.type ) )
1769
1770        if len( name ) == 0:
1771
1772            raise ValueError( "Name must be non-empty" )
1773
1774        self.meta_msg.reset()
1775        self.meta_msg.pack_int( 128 )
1776
1777        if not spoof:
1778            self.meta_msg.pack_string( hostname )
1779        else:
1780            self.meta_msg.pack_string( spoof )
1781
1782        self.meta_msg.pack_string( name )
1783
1784        if not spoof:
1785            self.meta_msg.pack_int( 0 )
1786        else:
1787            self.meta_msg.pack_int( 1 )
1788           
1789        self.meta_msg.pack_string( typestr )
1790        self.meta_msg.pack_string( name )
1791        self.meta_msg.pack_string( unitstr )
1792        self.meta_msg.pack_int( self.slope[ slopestr ] )
1793        self.meta_msg.pack_uint( int( tmax ) )
1794        self.meta_msg.pack_uint( int( dmax ) )
1795
1796        if not group:
1797            self.meta_msg.pack_int( 0 )
1798        else:
1799            self.meta_msg.pack_int( 1 )
1800            self.meta_msg.pack_string( "GROUP" )
1801            self.meta_msg.pack_string( group )
1802
1803        self.data_msg.reset()
1804        self.data_msg.pack_int( 128+5 )
1805
1806        if not spoof:
1807            self.data_msg.pack_string( hostname )
1808        else:
1809            self.data_msg.pack_string( spoof )
1810
1811        self.data_msg.pack_string( name )
1812
1813        if not spoof:
1814            self.data_msg.pack_int( 0 )
1815        else:
1816            self.data_msg.pack_int( 1 )
1817
1818        self.data_msg.pack_string( "%s" )
1819        self.data_msg.pack_string( str( value ) )
1820
1821        return ( self.meta_msg.get_buffer(), self.data_msg.get_buffer() )
1822
1823def printTime( ):
1824
1825    """Print current time/date in human readable format for log/debug"""
1826
1827    return time.strftime("%a, %d %b %Y %H:%M:%S")
1828
1829def debug_msg( level, msg ):
1830
1831    """Print msg if at or above current debug level"""
1832
1833    global DAEMONIZE, DEBUG_LEVEL, SYSLOG_LEVEL
1834
1835    if (not DAEMONIZE and DEBUG_LEVEL >= level):
1836        sys.stderr.write( msg + '\n' )
1837
1838    if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
1839        syslog.syslog( msg )
1840
1841def write_pidfile():
1842
1843    # Write pidfile if PIDFILE is set
1844    #
1845    if PIDFILE:
1846
1847        pid    = os.getpid()
1848
1849        pidfile    = open( PIDFILE, 'w' )
1850
1851        pidfile.write( str( pid ) )
1852        pidfile.close()
1853
1854def main():
1855
1856    """Application start"""
1857
1858    global PBSQuery, PBSError, lsfObject
1859    global SYSLOG_FACILITY, USE_SYSLOG, BATCH_API, DAEMONIZE
1860
1861    if not processArgs( sys.argv[1:] ):
1862
1863        sys.exit( 1 )
1864
1865    # Load appropriate DataGatherer depending on which BATCH_API is set
1866    # and any required modules for the Gatherer
1867    #
1868    if BATCH_API == 'pbs':
1869
1870        try:
1871            from PBSQuery import PBSQuery, PBSError
1872
1873        except ImportError:
1874
1875            debug_msg( 0, "FATAL ERROR: BATCH_API set to 'pbs' but python module 'pbs_python' is not installed" )
1876            sys.exit( 1 )
1877
1878        gather = PbsDataGatherer()
1879
1880    elif BATCH_API == 'sge':
1881
1882        # Tested with SGE 6.0u11.
1883        #
1884        gather = SgeDataGatherer()
1885
1886    elif BATCH_API == 'lsf':
1887
1888        try:
1889            from lsfObject import lsfObject
1890        except:
1891            debug_msg(0, "fatal error: BATCH_API set to 'lsf' but python module is not found or installed")
1892            sys.exit( 1)
1893
1894        gather = LsfDataGatherer()
1895
1896    else:
1897        debug_msg( 0, "FATAL ERROR: unknown BATCH_API '" + BATCH_API + "' is not supported" )
1898
1899        sys.exit( 1 )
1900
1901    if( DAEMONIZE and USE_SYSLOG ):
1902
1903        syslog.openlog( 'jobmond', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
1904
1905    if DAEMONIZE:
1906
1907        gather.daemon()
1908    else:
1909        gather.run()
1910
1911# wh00t? someone started me! :)
1912#
1913if __name__ == '__main__':
1914    main()
Note: See TracBrowser for help on using the repository browser.