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

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