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

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