source: branches/1.1/jobmond/jobmond.py @ 927

Last change on this file since 927 was 927, checked in by ramonb, 11 years ago

jobmond/jobmond.py:

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