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

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

jobmond.py:

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