source: branches/1.0/jobmond/jobmond.py @ 827

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