source: branches/0.4/jobarchived/jobarchived.py @ 774

Last change on this file since 774 was 774, checked in by ramonb, 11 years ago
  • job_id is now varchar and not int anymore (due to array ids)
  • fixed monarch job detection: jobid is now last field and sequence number is first
  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 58.4 KB
Line 
1#!/usr/bin/env python
2#
3# This file is part of Jobmonarch
4#
5# Copyright (C) 2006-2013  Ramon Bastiaans
6#
7# Jobmonarch is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# Jobmonarch is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20#
21# SVN $Id: jobarchived.py 774 2013-03-29 13:07:28Z ramonb $
22#
23
24import getopt, syslog, ConfigParser, sys
25
26VERSION='0.4+SVN'
27
28def usage( ver ):
29
30    print 'jobarchived %s' %VERSION
31
32    if ver:
33        return 0
34
35    print
36    print 'Purpose:'
37    print '  The Job Archive Daemon (jobarchived) stores batch job information in a SQL database'
38    print '  and node statistics in a RRD archive'
39    print
40    print 'Usage:    jobarchived [OPTIONS]'
41    print
42    print '  -c, --config=FILE    The configuration file to use (default: /etc/jobarchived.conf)'
43    print '  -p, --pidfile=FILE    Use pid file to store the process id'
44    print '  -h, --help        Print help and exit'
45    print '  -v, --version        Print version and exit'
46    print
47
48def processArgs( args ):
49
50    SHORT_L    = 'p:hvc:'
51    LONG_L    = [ 'help', 'config=', 'pidfile=', 'version' ]
52
53    config_filename = '/etc/jobarchived.conf'
54
55    global PIDFILE
56
57    PIDFILE    = None
58
59    try:
60
61        opts, args = getopt.getopt( args, SHORT_L, LONG_L )
62
63    except getopt.error, detail:
64
65        print detail
66        sys.exit(1)
67
68    for opt, value in opts:
69
70        if opt in [ '--config', '-c' ]:
71
72            config_filename = value
73
74        if opt in [ '--pidfile', '-p' ]:
75
76            PIDFILE         = value
77
78        if opt in [ '--help', '-h' ]:
79
80            usage( False )
81            sys.exit( 0 )
82
83        if opt in [ '--version', '-v' ]:
84
85            usage( True )
86            sys.exit( 0 )
87
88    try:
89        return loadConfig( config_filename )
90
91    except ConfigParser.NoOptionError, detail:
92
93        print detail
94        sys.exit( 1 )
95
96def loadConfig( filename ):
97
98    def getlist( cfg_string ):
99
100        my_list = [ ]
101
102        for item_txt in cfg_string.split( ',' ):
103
104            sep_char = None
105
106            item_txt = item_txt.strip()
107
108            for s_char in [ "'", '"' ]:
109
110                if item_txt.find( s_char ) != -1:
111
112                    if item_txt.count( s_char ) != 2:
113
114                        print 'Missing quote: %s' %item_txt
115                        sys.exit( 1 )
116
117                    else:
118
119                        sep_char = s_char
120                        break
121
122            if sep_char:
123
124                item_txt = item_txt.split( sep_char )[1]
125
126            my_list.append( item_txt )
127
128        return my_list
129
130    cfg = ConfigParser.ConfigParser()
131
132    cfg.read( filename )
133
134    global DEBUG_LEVEL, USE_SYSLOG, SYSLOG_LEVEL, SYSLOG_FACILITY, GMETAD_CONF, ARCHIVE_XMLSOURCE
135    global ARCHIVE_DATASOURCES, ARCHIVE_PATH, ARCHIVE_HOURS_PER_RRD, ARCHIVE_EXCLUDE_METRICS
136    global JOB_SQL_DBASE, DAEMONIZE, RRDTOOL, JOB_TIMEOUT, MODRRDTOOL, JOB_SQL_PASSWORD, JOB_SQL_USER
137
138    ARCHIVE_PATH        = cfg.get( 'DEFAULT', 'ARCHIVE_PATH' )
139
140    ARCHIVE_HOURS_PER_RRD    = cfg.getint( 'DEFAULT', 'ARCHIVE_HOURS_PER_RRD' )
141
142    DEBUG_LEVEL        = cfg.getint( 'DEFAULT', 'DEBUG_LEVEL' )
143
144    USE_SYSLOG        = cfg.getboolean( 'DEFAULT', 'USE_SYSLOG' )
145
146    SYSLOG_LEVEL        = cfg.getint( 'DEFAULT', 'SYSLOG_LEVEL' )
147
148    MODRRDTOOL        = False
149
150    try:
151        global rrdtool
152        import rrdtool
153
154        MODRRDTOOL        = True
155
156    except ImportError:
157
158        MODRRDTOOL        = False
159
160        print "ERROR: py-rrdtool import FAILED: failing back to DEPRECATED use of rrdtool binary. This will slow down jobarchived significantly!"
161
162        RRDTOOL            = cfg.get( 'DEFAULT', 'RRDTOOL' )
163
164    try:
165
166        SYSLOG_FACILITY    = eval( 'syslog.LOG_' + cfg.get( 'DEFAULT', 'SYSLOG_FACILITY' ) )
167
168    except AttributeError, detail:
169
170        print 'Unknown syslog facility'
171        sys.exit( 1 )
172
173    GMETAD_CONF        = cfg.get( 'DEFAULT', 'GMETAD_CONF' )
174
175    ARCHIVE_XMLSOURCE    = cfg.get( 'DEFAULT', 'ARCHIVE_XMLSOURCE' )
176
177    ARCHIVE_DATASOURCES    = getlist( cfg.get( 'DEFAULT', 'ARCHIVE_DATASOURCES' ) )
178
179    ARCHIVE_EXCLUDE_METRICS    = getlist( cfg.get( 'DEFAULT', 'ARCHIVE_EXCLUDE_METRICS' ) )
180
181    JOB_SQL_DBASE        = cfg.get( 'DEFAULT', 'JOB_SQL_DBASE' )
182    JOB_SQL_USER        = cfg.get( 'DEFAULT', 'JOB_SQL_USER' )
183    JOB_SQL_PASSWORD        = cfg.get( 'DEFAULT', 'JOB_SQL_PASSWORD' )
184
185    JOB_TIMEOUT        = cfg.getint( 'DEFAULT', 'JOB_TIMEOUT' )
186
187    DAEMONIZE        = cfg.getboolean( 'DEFAULT', 'DAEMONIZE' )
188
189
190    return True
191
192# What XML data types not to store
193#
194UNSUPPORTED_ARCHIVE_TYPES = [ 'string' ]
195
196# Maximum time (in seconds) a parsethread may run
197#
198PARSE_TIMEOUT = 60
199
200# Maximum time (in seconds) a storethread may run
201#
202STORE_TIMEOUT = 360
203
204"""
205The Job Archiving Daemon
206"""
207
208from types import *
209
210import xml.sax, xml.sax.handler, socket, string, os, os.path, time, thread, threading, random, re
211
212try:
213    import psycopg2
214
215except ImportError, details:
216
217    print "FATAL ERROR: psycopg2 python module not found"
218    sys.exit( 1 )
219
220class InitVars:
221        Vars = {}
222       
223        def __init__(self, **key_arg):
224                for (key, value) in key_arg.items():
225                        if value:
226                                self.Vars[key] = value
227                        else:   
228                                self.Vars[key] = None
229                               
230        def __call__(self, *key):
231                key = "%s" % key
232                return self.Vars[key]
233               
234        def __getitem__(self, key):
235                return self.Vars[key]
236               
237        def __repr__(self):
238                return repr(self.Vars)
239               
240        def keys(self):
241                barf =  map(None, self.Vars.keys())
242                return barf
243               
244        def values(self):
245                barf =  map(None, self.Vars.values())
246                return barf
247               
248        def has_key(self, key):
249                if self.Vars.has_key(key):
250                        return 1
251                else:   
252                        return 0
253                       
254class DBError(Exception):
255        def __init__(self, msg=''):
256                self.msg = msg
257                Exception.__init__(self, msg)
258        def __repr__(self):
259                return self.msg
260        __str__ = __repr__
261
262#
263# Class to connect to a database
264# and return the queury in a list or dictionairy.
265#
266class DB:
267    def __init__(self, db_vars):
268
269        self.dict = db_vars
270
271        if self.dict.has_key('User'):
272            self.user = self.dict['User']
273        else:
274            self.user = 'postgres'
275
276        if self.dict.has_key('Host'):
277            self.host = self.dict['Host']
278        else:
279            self.host = 'localhost'
280
281        if self.dict.has_key('Password'):
282            self.passwd = self.dict['Password']
283        else:
284            self.passwd = ''
285
286        if self.dict.has_key('DataBaseName'):
287            self.db = self.dict['DataBaseName']
288        else:
289            self.db = 'jobarchive'
290
291        # connect_string = 'host:port:database:user:password:
292        dsn = "host='%s' dbname='%s' user='%s' password='%s'" %(self.host, self.db, self.user, self.passwd)
293
294        try:
295            self.SQL = psycopg2.connect(dsn)
296        except psycopg2.Error, details:
297            str = "%s" %details
298            raise DBError(str)
299
300    def __repr__(self):
301        return repr(self.result)
302
303    def __nonzero__(self):
304        return not(self.result == None)
305
306    def __len__(self):
307        return len(self.result)
308
309    def __getitem__(self,i):
310        return self.result[i]
311
312    def __getslice__(self,i,j):
313        return self.result[i:j]
314
315    def Get(self, q_str):
316        c = self.SQL.cursor()
317        try:
318            c.execute(q_str)
319            result = c.fetchall()
320        except psycopg2.Error, details:
321            c.close()
322            str = "%s" %details
323            raise DBError(str)
324
325        c.close()
326        return result
327
328    def Set(self, q_str):
329        c = self.SQL.cursor()
330        try:
331            c.execute(q_str)
332
333        except psycopg2.Error, details:
334            c.close()
335            str = "%s" %details
336            raise DBError(str)
337
338        c.close()
339        return True
340
341    def Commit(self):
342        self.SQL.commit()
343
344class DataSQLStore:
345
346    db_vars = None
347    dbc = None
348
349    def __init__( self, hostname, database ):
350
351        global JOB_SQL_USER, JOB_SQL_PASSWORD
352
353        self.db_vars = InitVars(DataBaseName=database,
354                User=JOB_SQL_USER,
355                Host=hostname,
356                Password=JOB_SQL_PASSWORD,
357                Dictionary='true')
358
359        try:
360            self.dbc     = DB(self.db_vars)
361        except DBError, details:
362            debug_msg( 0, 'FATAL ERROR: Unable to connect to database!: ' +str(details) )
363            sys.exit(1)
364
365    def setDatabase(self, statement):
366        ret = self.doDatabase('set', statement)
367        return ret
368       
369    def getDatabase(self, statement):
370        ret = self.doDatabase('get', statement)
371        return ret
372
373    def doDatabase(self, type, statement):
374
375        debug_msg( 10, 'doDatabase(): %s: %s' %(type, statement) )
376        try:
377            if type == 'set':
378                result = self.dbc.Set( statement )
379                self.dbc.Commit()
380            elif type == 'get':
381                result = self.dbc.Get( statement )
382               
383        except DBError, detail:
384            operation = statement.split(' ')[0]
385            debug_msg( 0, 'FATAL ERROR: ' +operation+ ' on database failed while doing ['+statement+'] full msg: '+str(detail) )
386            sys.exit(1)
387
388        debug_msg( 10, 'doDatabase(): result: %s' %(result) )
389        return result
390
391    def getJobNodeId( self, job_id, node_id ):
392
393        id = self.getDatabase( "SELECT job_id,node_id FROM job_nodes WHERE job_id = '%s' AND node_id = '%s'" %(job_id, node_id) )
394        if len( id ) > 0:
395
396            if len( id[0] ) > 0 and id[0] != '':
397           
398                return 1
399
400        return 0
401
402    def getNodeId( self, hostname ):
403
404        id = self.getDatabase( "SELECT node_id FROM nodes WHERE node_hostname = '%s'" %hostname )
405
406        if len( id ) > 0:
407
408            id = id[0][0]
409
410            return id
411        else:
412            return None
413
414    def getNodeIds( self, hostnames ):
415
416        ids = [ ]
417
418        for node in hostnames:
419
420            id = self.getNodeId( node )
421
422            if id:
423                ids.append( id )
424
425        return ids
426
427    def getJobId( self, jobid ):
428
429        id = self.getDatabase( "SELECT job_id FROM jobs WHERE job_id = '%s'" %jobid )
430
431        if id:
432            id = id[0][0]
433
434            return id
435        else:
436            return None
437
438    def addJob( self, job_id, jobattrs ):
439
440        if not self.getJobId( job_id ):
441
442            self.mutateJob( 'insert', job_id, jobattrs ) 
443        else:
444            self.mutateJob( 'update', job_id, jobattrs )
445
446    def mutateJob( self, action, job_id, jobattrs ):
447
448        job_values    = [ 'name', 'queue', 'owner', 'requested_time', 'requested_memory', 'ppn', 'status', 'start_timestamp', 'stop_timestamp' ]
449
450        insert_col_str    = 'job_id'
451        insert_val_str    = "'%s'" %job_id
452        update_str    = None
453
454        debug_msg( 10, 'mutateJob(): %s %s' %(action,job_id))
455
456        ids = [ ]
457
458        for valname, value in jobattrs.items():
459
460            if valname in job_values and value != '':
461
462                column_name = 'job_' + valname
463
464                if action == 'insert':
465
466                    if not insert_col_str:
467                        insert_col_str = column_name
468                    else:
469                        insert_col_str = insert_col_str + ',' + column_name
470
471                    if not insert_val_str:
472                        insert_val_str = value
473                    else:
474                        insert_val_str = insert_val_str + ",'%s'" %value
475
476                elif action == 'update':
477                   
478                    if not update_str:
479                        update_str = "%s='%s'" %(column_name, value)
480                    else:
481                        update_str = update_str + ",%s='%s'" %(column_name, value)
482
483            elif valname == 'nodes' and value:
484
485                node_valid = 1
486
487                if len(value) == 1:
488               
489                    if jobattrs['status'] == 'Q':
490
491                        node_valid = 0
492
493                    else:
494
495                        node_valid = 0
496
497                        for node_char in str(value[0]):
498
499                            if string.find( string.digits, node_char ) != -1 and not node_valid:
500
501                                node_valid = 1
502
503                if node_valid:
504
505                    ids = self.addNodes( value, jobattrs['domain'] )
506
507        if action == 'insert':
508
509            self.setDatabase( "INSERT INTO jobs ( %s ) VALUES ( %s )" %( insert_col_str, insert_val_str ) )
510
511        elif action == 'update':
512
513            self.setDatabase( "UPDATE jobs SET %s WHERE job_id='%s'" %(update_str, job_id) )
514
515        if len( ids ) > 0:
516            self.addJobNodes( job_id, ids )
517
518    def addNodes( self, hostnames, domain ):
519
520        ids = [ ]
521
522        for node in hostnames:
523
524            node    = '%s.%s' %( node, domain )
525            id    = self.getNodeId( node )
526   
527            if not id:
528                self.setDatabase( "INSERT INTO nodes ( node_hostname ) VALUES ( '%s' )" %node )
529                id = self.getNodeId( node )
530
531            ids.append( id )
532
533        return ids
534
535    def addJobNodes( self, jobid, nodes ):
536
537        for node in nodes:
538
539            if not self.getJobNodeId( jobid, node ):
540
541                self.addJobNode( jobid, node )
542
543    def addJobNode( self, jobid, nodeid ):
544
545        self.setDatabase( "INSERT INTO job_nodes (job_id,node_id) VALUES ( '%s',%s )" %(jobid, nodeid) )
546
547    def storeJobInfo( self, jobid, jobattrs ):
548
549        self.addJob( jobid, jobattrs )
550
551    def checkStaleJobs( self ):
552
553        # Locate all jobs in the database that are not set to finished
554        #
555        q = "SELECT * from jobs WHERE job_status != 'F'"
556
557        r = self.getDatabase( q )
558
559        if len( r ) == 0:
560
561            return None
562
563        cleanjobs    = [ ]
564        timeoutjobs    = [ ]
565
566        jobtimeout_sec    = JOB_TIMEOUT * (60 * 60)
567        cur_time    = time.time()
568
569        for row in r:
570
571            job_id            = row[0]
572            job_requested_time    = row[4]
573            job_status        = row[7]
574            job_start_timestamp    = row[8]
575
576            # If it was set to queued and we didn't see it started
577            # there's not point in keeping it around
578            #
579            if job_status == 'Q' or not job_start_timestamp:
580
581                cleanjobs.append( job_id )
582
583            else:
584
585                start_timestamp = int( job_start_timestamp )
586
587                # If it was set to running longer than JOB_TIMEOUT
588                # close the job: it probably finished while we were not running
589                #
590                if ( cur_time - start_timestamp ) > jobtimeout_sec:
591
592                    if job_requested_time:
593
594                        rtime_epoch    = reqtime2epoch( job_requested_time )
595                    else:
596                        rtime_epoch    = None
597                   
598                    timeoutjobs.append( (job_id, job_start_timestamp, rtime_epoch) )
599
600        debug_msg( 1, 'Found ' + str( len( cleanjobs ) ) + ' stale jobs in database: deleting entries' )
601
602        # Purge these from database
603        #
604        for j in cleanjobs:
605
606            q = "DELETE FROM jobs WHERE job_id = '" + str( j ) + "'"
607            self.setDatabase( q )
608
609        debug_msg( 1, 'Found ' + str( len( timeoutjobs ) ) + ' timed out jobs in database: closing entries' )
610
611        # Close these jobs in the database
612        # update the stop_timestamp to: start_timestamp + requested wallclock
613        # and set state: finished
614        #
615        for j in timeoutjobs:
616
617            ( i, s, r )        = j
618
619            if r:
620                new_end_timestamp    = int( s ) + r
621
622            q = "UPDATE jobs SET job_status='F',job_stop_timestamp = '" + str( new_end_timestamp ) + "' WHERE job_id = '" + str(i) + "'"
623            self.setDatabase( q )
624
625class RRDMutator:
626    """A class for performing RRD mutations"""
627
628    binary = None
629
630    def __init__( self, binary=None ):
631        """Set alternate binary if supplied"""
632
633        if binary:
634            self.binary = binary
635
636    def create( self, filename, args ):
637        """Create a new rrd with args"""
638
639        global MODRRDTOOL
640
641        if MODRRDTOOL:
642            return self.perform( 'create', filename, args )
643        else:
644            return self.perform( 'create', '"' + filename + '"', args )
645
646    def update( self, filename, args ):
647        """Update a rrd with args"""
648
649        global MODRRDTOOL
650
651        if MODRRDTOOL:
652            return self.perform( 'update', filename, args )
653        else:
654            return self.perform( 'update', '"' + filename + '"', args )
655
656    def grabLastUpdate( self, filename ):
657        """Determine the last update time of filename rrd"""
658
659        global MODRRDTOOL
660
661        last_update = 0
662
663        # Use the py-rrdtool module if it's available on this system
664        #
665        if MODRRDTOOL:
666
667            debug_msg( 8, 'rrdtool.info( ' + filename + ' )' )
668
669            rrd_header     = { }
670
671            try:
672                rrd_header    = rrdtool.info( filename )
673            except rrdtool.error, msg:
674                debug_msg( 8, str( msg ) )
675
676            if rrd_header.has_key( 'last_update' ):
677                return last_update
678            else:
679                return 0
680
681        # For backwards compatiblity: use the rrdtool binary if py-rrdtool is unavailable
682        # DEPRECATED (slow!)
683        #
684        else:
685            debug_msg( 8, self.binary + ' info ' + filename )
686
687            my_pipe        = os.popen( self.binary + ' info "' + filename + '"' )
688
689            for line in my_pipe.readlines():
690
691                if line.find( 'last_update') != -1:
692
693                    last_update = line.split( ' = ' )[1]
694
695            if my_pipe:
696
697                my_pipe.close()
698
699            if last_update:
700                return last_update
701            else:
702                return 0
703
704
705    def perform( self, action, filename, args ):
706        """Perform action on rrd filename with args"""
707
708        global MODRRDTOOL
709
710        arg_string = None
711
712        if type( args ) is not ListType:
713            debug_msg( 8, 'Arguments needs to be of type List' )
714            return 1
715
716        for arg in args:
717
718            if not arg_string:
719
720                arg_string = arg
721            else:
722                arg_string = arg_string + ' ' + arg
723
724        if MODRRDTOOL:
725
726            debug_msg( 8, 'rrdtool.' + action + "( " + filename + ' ' + arg_string + ")" )
727
728            try:
729                debug_msg( 8, "filename '" + str(filename) + "' type "+ str(type(filename)) + " args " + str( args ) )
730
731                if action == 'create':
732
733                    rrdtool.create( str( filename ), *args )
734
735                elif action == 'update':
736
737                    rrdtool.update( str( filename ), *args )
738
739            except rrdtool.error, msg:
740
741                error_msg = str( msg )
742                debug_msg( 8, error_msg )
743                return 1
744
745        else:
746
747            debug_msg( 8, self.binary + ' ' + action + ' ' + filename + ' ' + arg_string  )
748
749            cmd     = os.popen( self.binary + ' ' + action + ' ' + filename + ' ' + arg_string )
750            lines   = cmd.readlines()
751
752            cmd.close()
753
754            for line in lines:
755
756                if line.find( 'ERROR' ) != -1:
757
758                    error_msg = string.join( line.split( ' ' )[1:] )
759                    debug_msg( 8, error_msg )
760                    return 1
761
762        return 0
763
764class XMLProcessor:
765    """Skeleton class for XML processor's"""
766
767    def run( self ):
768        """Do main processing of XML here"""
769
770        pass
771
772class TorqueXMLProcessor( XMLProcessor ):
773    """Main class for processing XML and acting with it"""
774
775    def __init__( self, XMLSource, DataStore ):
776        """Setup initial XML connection and handlers"""
777
778        self.myXMLSource    = XMLSource
779        self.myXMLHandler    = TorqueXMLHandler( DataStore )
780        self.myXMLError        = XMLErrorHandler()
781
782        self.config        = GangliaConfigParser( GMETAD_CONF )
783
784    def run( self ):
785        """Main XML processing"""
786
787        debug_msg( 1, 'torque_xml_thread(): started.' )
788
789        while( 1 ):
790
791            #self.myXMLSource = self.mXMLGatherer.getFileObject()
792            debug_msg( 1, 'torque_xml_thread(): Retrieving XML data..' )
793
794            my_data    = self.myXMLSource.getData()
795            #print my_data
796            #print "size my data: %d" %len( my_data )
797
798            debug_msg( 1, 'torque_xml_thread(): Done retrieving.' )
799
800            if my_data:
801                debug_msg( 1, 'ganglia_parse_thread(): Parsing XML..' )
802
803                xml.sax.parseString( my_data, self.myXMLHandler, self.myXMLError )
804
805                debug_msg( 1, 'ganglia_parse_thread(): Done parsing.' )
806            else:
807                debug_msg( 1, 'torque_xml_thread(): Got no data.' )
808
809               
810            debug_msg( 1, 'torque_xml_thread(): Sleeping.. (%ss)' %(str( self.config.getLowestInterval() ) ) )
811            time.sleep( self.config.getLowestInterval() )
812
813class TorqueXMLHandler( xml.sax.handler.ContentHandler ):
814    """Parse Torque's jobinfo XML from our plugin"""
815
816    jobAttrs = { }
817
818    def __init__( self, datastore ):
819
820        #self.ds            = DataSQLStore( JOB_SQL_DBASE.split( '/' )[0], JOB_SQL_DBASE.split( '/' )[1] )
821        self.ds            = datastore
822        self.jobs_processed    = [ ]
823        self.jobs_to_store    = [ ]
824        debug_msg( 1, "XML: Handler created" )
825
826    def startDocument( self ):
827
828        self.heartbeat    = 0
829        self.elementct    = 0
830        debug_msg( 1, "XML: Start document" )
831
832    def startElement( self, name, attrs ):
833        """
834        This XML will be all gmetric XML
835        so there will be no specific start/end element
836        just one XML statement with all info
837        """
838       
839        jobinfo = { }
840
841        self.elementct    += 1
842
843        if name == 'CLUSTER':
844
845            self.clustername = str( attrs.get( 'NAME', "" ) )
846
847        elif name == 'METRIC' and self.clustername in ARCHIVE_DATASOURCES:
848
849            metricname = str( attrs.get( 'NAME', "" ) )
850
851            if metricname == 'zplugin_monarch_heartbeat':
852                self.heartbeat = str( attrs.get( 'VAL', "" ) )
853
854            elif metricname.find( 'zplugin_monarch_job' ) != -1:
855
856                job_id    = metricname.split( 'zplugin_monarch_job_' )[1].split( '_' )[1]
857                val    = str( attrs.get( 'VAL', "" ) )
858
859                if not job_id in self.jobs_processed:
860
861                    self.jobs_processed.append( job_id )
862
863                check_change = 0
864
865                if self.jobAttrs.has_key( job_id ):
866
867                    check_change = 1
868
869                valinfo = val.split( ' ' )
870
871                for myval in valinfo:
872
873                    if len( myval.split( '=' ) ) > 1:
874
875                        valname    = myval.split( '=' )[0]
876                        value    = myval.split( '=' )[1]
877
878                        if valname == 'nodes':
879                            value = value.split( ';' )
880
881                        jobinfo[ valname ] = value
882
883                if check_change:
884                    if self.jobinfoChanged( self.jobAttrs, job_id, jobinfo ) and self.jobAttrs[ job_id ]['status'] in [ 'R', 'Q' ]:
885                        self.jobAttrs[ job_id ]['stop_timestamp']    = ''
886                        self.jobAttrs[ job_id ]                = self.setJobAttrs( self.jobAttrs[ job_id ], jobinfo )
887                        if not job_id in self.jobs_to_store:
888                            self.jobs_to_store.append( job_id )
889
890                        debug_msg( 10, 'jobinfo for job %s has changed' %job_id )
891                else:
892                    self.jobAttrs[ job_id ] = jobinfo
893
894                    if not job_id in self.jobs_to_store:
895                        self.jobs_to_store.append( job_id )
896
897                    debug_msg( 10, 'jobinfo for job %s has changed' %job_id )
898                   
899    def endDocument( self ):
900        """When all metrics have gone, check if any jobs have finished"""
901
902        debug_msg( 1, "XML: Processed "+str(self.elementct)+ " elements - found "+str(len(self.jobs_to_store))+" (updated) jobs" )
903
904        if self.heartbeat:
905            for jobid, jobinfo in self.jobAttrs.items():
906
907                # This is an old job, not in current jobinfo list anymore
908                # it must have finished, since we _did_ get a new heartbeat
909                #
910                mytime = int( jobinfo['reported'] ) + int( jobinfo['poll_interval'] )
911
912                if (mytime < self.heartbeat) and (jobid not in self.jobs_processed) and (jobinfo['status'] == 'R'):
913
914                    if not jobid in self.jobs_processed:
915                        self.jobs_processed.append( jobid )
916
917                    self.jobAttrs[ jobid ]['status'] = 'F'
918                    self.jobAttrs[ jobid ]['stop_timestamp'] = str( self.heartbeat )
919
920                    if not jobid in self.jobs_to_store:
921                        self.jobs_to_store.append( jobid )
922
923            debug_msg( 1, 'torque_xml_thread(): Storing..' )
924
925            for jobid in self.jobs_to_store:
926                if self.jobAttrs[ jobid ]['status'] in [ 'R', 'F' ]:
927
928                    self.ds.storeJobInfo( jobid, self.jobAttrs[ jobid ] )
929
930                    if self.jobAttrs[ jobid ]['status'] == 'F':
931                        del self.jobAttrs[ jobid ]
932
933            debug_msg( 1, 'torque_xml_thread(): Done storing.' )
934
935            self.jobs_processed    = [ ]
936            self.jobs_to_store    = [ ]
937
938    def setJobAttrs( self, old, new ):
939        """
940        Set new job attributes in old, but not lose existing fields
941        if old attributes doesn't have those
942        """
943
944        for valname, value in new.items():
945            old[ valname ] = value
946
947        return old
948       
949
950    def jobinfoChanged( self, jobattrs, jobid, jobinfo ):
951        """
952        Check if jobinfo has changed from jobattrs[jobid]
953        if it's report time is bigger than previous one
954        and it is report time is recent (equal to heartbeat)
955        """
956
957        ignore_changes = [ 'reported' ]
958
959        if jobattrs.has_key( jobid ):
960
961            for valname, value in jobinfo.items():
962
963                if valname not in ignore_changes:
964
965                    if jobattrs[ jobid ].has_key( valname ):
966
967                        if value != jobattrs[ jobid ][ valname ]:
968
969                            if jobinfo['reported'] > jobattrs[ jobid ][ 'reported' ] and jobinfo['reported'] == self.heartbeat:
970                                return True
971
972                    else:
973                        return True
974
975        return False
976
977class GangliaXMLHandler( xml.sax.handler.ContentHandler ):
978    """Parse Ganglia's XML"""
979
980    def __init__( self, config, datastore ):
981        """Setup initial variables and gather info on existing rrd archive"""
982
983        self.config    = config
984        self.clusters    = { }
985        self.ds        = datastore
986
987        debug_msg( 1, 'Checking database..' )
988
989        global DEBUG_LEVEL
990
991        if DEBUG_LEVEL <= 2:
992            self.ds.checkStaleJobs()
993
994        debug_msg( 1, 'Check done.' )
995        debug_msg( 1, 'Checking rrd archive..' )
996        self.gatherClusters()
997        debug_msg( 1, 'Check done.' )
998
999    def gatherClusters( self ):
1000        """Find all existing clusters in archive dir"""
1001
1002        archive_dir    = check_dir(ARCHIVE_PATH)
1003
1004        hosts        = [ ]
1005
1006        if os.path.exists( archive_dir ):
1007
1008            dirlist    = os.listdir( archive_dir )
1009
1010            for cfgcluster in ARCHIVE_DATASOURCES:
1011
1012                if cfgcluster not in dirlist:
1013
1014                    # Autocreate a directory for this cluster
1015                    # assume it is new
1016                    #
1017                    cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), cfgcluster )
1018
1019                    os.mkdir( cluster_dir )
1020
1021                    dirlist.append( cfgcluster )
1022
1023            for item in dirlist:
1024
1025                clustername = item
1026
1027                if not self.clusters.has_key( clustername ) and clustername in ARCHIVE_DATASOURCES:
1028
1029                    self.clusters[ clustername ] = RRDHandler( self.config, clustername )
1030
1031        debug_msg( 9, "Found "+str(len(self.clusters.keys()))+" clusters" )
1032
1033    def startElement( self, name, attrs ):
1034        """Memorize appropriate data from xml start tags"""
1035
1036        if name == 'GANGLIA_XML':
1037
1038            self.XMLSource        = str( attrs.get( 'SOURCE', "" ) )
1039            self.gangliaVersion    = str( attrs.get( 'VERSION', "" ) )
1040
1041            debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
1042
1043        elif name == 'GRID':
1044
1045            self.gridName    = str( attrs.get( 'NAME', "" ) )
1046            self.time    = str( attrs.get( 'LOCALTIME', "" ) )
1047
1048            debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
1049
1050        elif name == 'CLUSTER':
1051
1052            self.clusterName    = str( attrs.get( 'NAME', "" ) )
1053            self.time        = str( attrs.get( 'LOCALTIME', "" ) )
1054
1055            if not self.clusters.has_key( self.clusterName ) and self.clusterName in ARCHIVE_DATASOURCES:
1056
1057                self.clusters[ self.clusterName ] = RRDHandler( self.config, self.clusterName )
1058
1059                debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
1060
1061        elif name == 'HOST' and self.clusterName in ARCHIVE_DATASOURCES:     
1062
1063            self.hostName        = str( attrs.get( 'NAME', "" ) )
1064            self.hostIp        = str( attrs.get( 'IP', "" ) )
1065            self.hostReported    = str( attrs.get( 'REPORTED', "" ) )
1066
1067            debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
1068
1069        elif name == 'METRIC' and self.clusterName in ARCHIVE_DATASOURCES:
1070
1071            type = str( attrs.get( 'TYPE', "" ) )
1072           
1073            exclude_metric = False
1074           
1075            for ex_metricstr in ARCHIVE_EXCLUDE_METRICS:
1076
1077                orig_name = str( attrs.get( 'NAME', "" ) )
1078
1079                if string.lower( orig_name ) == string.lower( ex_metricstr ):
1080               
1081                    exclude_metric = True
1082
1083                elif re.match( ex_metricstr, orig_name ):
1084
1085                    exclude_metric = True
1086
1087            if type not in UNSUPPORTED_ARCHIVE_TYPES and not exclude_metric:
1088
1089                myMetric        = { }
1090                myMetric['name']    = str( attrs.get( 'NAME', "" ) )
1091                myMetric['val']        = str( attrs.get( 'VAL', "" ) )
1092                myMetric['time']    = self.hostReported
1093
1094                self.clusters[ self.clusterName ].memMetric( self.hostName, myMetric )
1095
1096                debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
1097
1098    def storeMetrics( self ):
1099        """Store metrics of each cluster rrd handler"""
1100
1101        for clustername, rrdh in self.clusters.items():
1102
1103            ret = rrdh.storeMetrics()
1104
1105            if ret:
1106                debug_msg( 9, 'An error occured while storing metrics for cluster %s' %clustername )
1107                return 1
1108
1109        return 0
1110
1111class XMLErrorHandler( xml.sax.handler.ErrorHandler ):
1112
1113    def error( self, exception ):
1114        """Recoverable error"""
1115
1116        debug_msg( 0, 'Recoverable XML error ' + str( exception ) + ' ignored.' )
1117
1118    def fatalError( self, exception ):
1119        """Non-recoverable error"""
1120
1121        exception_str = str( exception )
1122
1123        # Ignore 'no element found' errors
1124        if exception_str.find( 'no element found' ) != -1:
1125            debug_msg( 0, 'No XML data found: Socket not (re)connected or datasource not available.' )
1126            return 0
1127
1128        debug_msg( 0, 'FATAL ERROR: Non-recoverable XML error ' + str( exception ) )
1129        sys.exit( 1 )
1130
1131    def warning( self, exception ):
1132        """Warning"""
1133
1134        debug_msg( 0, 'Warning ' + str( exception ) )
1135
1136class XMLGatherer:
1137    """Setup a connection and file object to Ganglia's XML"""
1138
1139    s        = None
1140    fd        = None
1141    data        = None
1142    slot        = None
1143
1144    # Time since the last update
1145    #
1146    LAST_UPDATE    = 0
1147
1148    # Minimum interval between updates
1149    #
1150    MIN_UPDATE_INT    = 10
1151
1152    # Is a update occuring now
1153    #
1154    update_now    = False
1155
1156    def __init__( self, host, port ):
1157        """Store host and port for connection"""
1158
1159        self.host    = host
1160        self.port    = port
1161        self.slot       = threading.Lock()
1162
1163        self.retrieveData()
1164
1165    def retrieveData( self ):
1166        """Setup connection to XML source"""
1167
1168        self.update_now    = True
1169
1170        self.slot.acquire()
1171
1172        self.data    = None
1173
1174        for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ):
1175
1176            af, socktype, proto, canonname, sa = res
1177
1178            try:
1179
1180                self.s = socket.socket( af, socktype, proto )
1181
1182            except ( socket.error, socket.gaierror, socket.herror, socket.timeout ), msg:
1183
1184                self.s = None
1185                continue
1186
1187            try:
1188
1189                self.s.connect( sa )
1190
1191            except ( socket.error, socket.gaierror, socket.herror, socket.timeout ), msg:
1192
1193                self.disconnect()
1194                continue
1195
1196            break
1197
1198        if self.s is None:
1199
1200            debug_msg( 0, 'FATAL ERROR: Could not open socket or unable to connect to datasource!' )
1201            self.update_now    = False
1202            #sys.exit( 1 )
1203
1204        else:
1205            #self.s.send( '\n' )
1206
1207            my_fp            = self.s.makefile( 'r' )
1208            my_data          = my_fp.readlines()
1209            my_data          = string.join( my_data, '' )
1210
1211            self.data        = my_data
1212
1213            self.LAST_UPDATE = time.time()
1214
1215        self.slot.release()
1216
1217        self.update_now    = False
1218
1219    def disconnect( self ):
1220        """Close socket"""
1221
1222        if self.s:
1223            #self.s.shutdown( 2 )
1224            self.s.close()
1225            self.s = None
1226
1227    def __del__( self ):
1228        """Kill the socket before we leave"""
1229
1230        self.disconnect()
1231
1232    def reGetData( self ):
1233        """Reconnect"""
1234
1235        while self.update_now:
1236
1237            # Must be another update in progress:
1238            # Wait until the update is complete
1239            #
1240            time.sleep( 1 )
1241
1242        if self.s:
1243            self.disconnect()
1244
1245        self.retrieveData()
1246
1247    def getData( self ):
1248
1249        """Return the XML data"""
1250
1251        # If more than MIN_UPDATE_INT seconds passed since last data update
1252        # update the XML first before returning it
1253        #
1254
1255        cur_time    = time.time()
1256
1257        if ( cur_time - self.LAST_UPDATE ) > self.MIN_UPDATE_INT:
1258
1259            self.reGetData()
1260
1261        while self.update_now:
1262
1263            # Must be another update in progress:
1264            # Wait until the update is complete
1265            #
1266            time.sleep( 1 )
1267           
1268        return self.data
1269
1270    def makeFileDescriptor( self ):
1271        """Make file descriptor that points to our socket connection"""
1272
1273        self.reconnect()
1274
1275        if self.s:
1276            self.fd = self.s.makefile( 'r' )
1277
1278    def getFileObject( self ):
1279        """Connect, and return a file object"""
1280
1281        self.makeFileDescriptor()
1282
1283        if self.fd:
1284            return self.fd
1285
1286class GangliaXMLProcessor( XMLProcessor ):
1287    """Main class for processing XML and acting with it"""
1288
1289    def __init__( self, XMLSource, DataStore ):
1290        """Setup initial XML connection and handlers"""
1291
1292        self.config        = GangliaConfigParser( GMETAD_CONF )
1293
1294        #self.myXMLGatherer    = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] )
1295        #self.myXMLSource    = self.myXMLGatherer.getFileObject()
1296        self.myXMLSource    = XMLSource
1297        self.ds            = DataStore
1298        self.myXMLHandler    = GangliaXMLHandler( self.config, self.ds )
1299        self.myXMLError        = XMLErrorHandler()
1300
1301    def run( self ):
1302        """Main XML processing; start a xml and storethread"""
1303
1304        xml_thread = threading.Thread( None, self.processXML, 'xmlthread' )
1305        store_thread = threading.Thread( None, self.storeMetrics, 'storethread' )
1306
1307        while( 1 ):
1308
1309            if not xml_thread.isAlive():
1310                # Gather XML at the same interval as gmetad
1311
1312                # threaded call to: self.processXML()
1313                #
1314                try:
1315                    xml_thread = threading.Thread( None, self.processXML, 'xml_thread' )
1316                    xml_thread.start()
1317                except thread.error, msg:
1318                    debug_msg( 0, 'ERROR: Unable to start xml_thread!: '+str(msg))
1319                    #return 1
1320
1321            if not store_thread.isAlive():
1322                # Store metrics every .. sec
1323
1324                # threaded call to: self.storeMetrics()
1325                #
1326                try:
1327                    store_thread = threading.Thread( None, self.storeMetrics, 'store_thread' )
1328                    store_thread.start()
1329                except thread.error, msg:
1330                    debug_msg( 0, 'ERROR: Unable to start store_thread!: '+str(msg))
1331                    #return 1
1332       
1333            # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway
1334            time.sleep( 1 )   
1335
1336    def storeMetrics( self ):
1337        """Store metrics retained in memory to disk"""
1338
1339        global DEBUG_LEVEL
1340
1341        # Store metrics somewhere between every 360 and 640 seconds
1342        #
1343        if DEBUG_LEVEL >= 1:
1344            STORE_INTERVAL = 60
1345            #STORE_INTERVAL = random.randint( 360, 640 )
1346        else:
1347            STORE_INTERVAL = random.randint( 360, 640 )
1348
1349        try:
1350            store_metric_thread = threading.Thread( None, self.storeThread, 'store_metric_thread' )
1351            store_metric_thread.start()
1352        except thread.error, msg:
1353            debug_msg( 0, 'ERROR: Unable to start ganglia_store_thread()!: '+str(msg) )
1354            return 1
1355
1356        debug_msg( 1, 'ganglia_store_thread(): started.' )
1357
1358        debug_msg( 1, 'ganglia_store_thread(): Sleeping.. (%ss)' %STORE_INTERVAL )
1359        time.sleep( STORE_INTERVAL )
1360        debug_msg( 1, 'ganglia_store_thread(): Done sleeping.' )
1361
1362        if store_metric_thread.isAlive():
1363
1364            debug_msg( 1, 'ganglia_store_thread(): storemetricthread() still running, waiting to terminate..' )
1365            store_metric_thread.join( STORE_TIMEOUT ) # Maximum time is for storing thread to finish
1366            debug_msg( 1, 'ganglia_store_thread(): Done waiting: terminated storemetricthread()' )
1367
1368        debug_msg( 1, 'ganglia_store_thread(): finished.' )
1369
1370        return 0
1371
1372    def storeThread( self ):
1373        """Actual metric storing thread"""
1374
1375        debug_msg( 1, 'ganglia_store_metric_thread(): started.' )
1376        debug_msg( 1, 'ganglia_store_metric_thread(): Storing data..' )
1377        ret = self.myXMLHandler.storeMetrics()
1378        if ret > 0:
1379            debug_msg( 0, 'ganglia_store_metric_thread(): UNKNOWN ERROR %s while storing Metrics!' %str(ret) )
1380        debug_msg( 1, 'ganglia_store_metric_thread(): Done storing.' )
1381        debug_msg( 1, 'ganglia_store_metric_thread(): finished.' )
1382       
1383        return 0
1384
1385    def processXML( self ):
1386        """Process XML"""
1387
1388        debug_msg( 5, "Entering processXML()")
1389
1390        try:
1391            parsethread = threading.Thread( None, self.parseThread, 'parsethread' )
1392            parsethread.start()
1393        except thread.error, msg:
1394            debug_msg( 0, 'ERROR: Unable to start ganglia_xml_thread()!: ' + str(msg) )
1395            return 1
1396
1397        debug_msg( 1, 'ganglia_xml_thread(): started.' )
1398
1399        debug_msg( 1, 'ganglia_xml_thread(): Sleeping.. (%ss)' %self.config.getLowestInterval() )
1400        time.sleep( float( self.config.getLowestInterval() ) )   
1401        debug_msg( 1, 'ganglia_xml_thread(): Done sleeping.' )
1402
1403        if parsethread.isAlive():
1404
1405            debug_msg( 1, 'ganglia_xml_thread(): parsethread() still running, waiting (%ss) to terminate..' %PARSE_TIMEOUT )
1406            parsethread.join( PARSE_TIMEOUT ) # Maximum time for XML thread to finish
1407            debug_msg( 1, 'ganglia_xml_thread(): Done waiting. parsethread() terminated' )
1408
1409        debug_msg( 1, 'ganglia_xml_thread(): finished.' )
1410
1411        debug_msg( 5, "Leaving processXML()")
1412
1413        return 0
1414
1415    def parseThread( self ):
1416        """Actual parsing thread"""
1417
1418        debug_msg( 1, 'ganglia_parse_thread(): started.' )
1419        debug_msg( 1, 'ganglia_parse_thread(): Retrieving XML data..' )
1420       
1421        my_data    = self.myXMLSource.getData()
1422        debug_msg( 1, 'ganglia_parse_thread(): data size %d.' %len(my_data) )
1423
1424        debug_msg( 1, 'ganglia_parse_thread(): Done retrieving.' )
1425
1426        if my_data:
1427            debug_msg( 1, 'ganglia_parse_thread(): Parsing XML..' )
1428            xml.sax.parseString( my_data, self.myXMLHandler, self.myXMLError )
1429            debug_msg( 1, 'ganglia_parse_thread(): Done parsing.' )
1430
1431        debug_msg( 1, 'ganglia_parse_thread(): finished.' )
1432
1433        return 0
1434
1435class GangliaConfigParser:
1436
1437    sources = [ ]
1438
1439    def __init__( self, config ):
1440        """Parse some stuff from our gmetad's config, such as polling interval"""
1441
1442        self.config = config
1443        self.parseValues()
1444
1445    def parseValues( self ):
1446        """Parse certain values from gmetad.conf"""
1447
1448        readcfg = open( self.config, 'r' )
1449
1450        for line in readcfg.readlines():
1451
1452            if line.count( '"' ) > 1:
1453
1454                if line.find( 'data_source' ) != -1 and line[0] != '#':
1455
1456                    source        = { }
1457                    source['name']    = line.split( '"' )[1]
1458                    source_words    = line.split( '"' )[2].split( ' ' )
1459
1460                    for word in source_words:
1461
1462                        valid_interval = 1
1463
1464                        for letter in word:
1465
1466                            if letter not in string.digits:
1467
1468                                valid_interval = 0
1469
1470                        if valid_interval and len(word) > 0:
1471
1472                            source['interval'] = word
1473                            debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
1474   
1475                    # No interval found, use Ganglia's default   
1476                    if not source.has_key( 'interval' ):
1477                        source['interval'] = 15
1478                        debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
1479
1480                    self.sources.append( source )
1481
1482    def getInterval( self, source_name ):
1483        """Return interval for source_name"""
1484
1485        for source in self.sources:
1486
1487            if source['name'] == source_name:
1488
1489                return source['interval']
1490
1491        return None
1492
1493    def getLowestInterval( self ):
1494        """Return the lowest interval of all clusters"""
1495
1496        lowest_interval = 0
1497
1498        for source in self.sources:
1499
1500            if not lowest_interval or source['interval'] <= lowest_interval:
1501
1502                lowest_interval = source['interval']
1503
1504        # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays
1505        if lowest_interval:
1506            return lowest_interval
1507        else:
1508            return 15
1509
1510class RRDHandler:
1511    """Class for handling RRD activity"""
1512
1513    myMetrics = { }
1514    lastStored = { }
1515    timeserials = { }
1516    slot = None
1517
1518    def __init__( self, config, cluster ):
1519        """Setup initial variables"""
1520
1521        global MODRRDTOOL
1522
1523        self.block    = 0
1524        self.cluster    = cluster
1525        self.config    = config
1526        self.slot    = threading.Lock()
1527
1528        if MODRRDTOOL:
1529
1530            self.rrdm    = RRDMutator()
1531        else:
1532            self.rrdm    = RRDMutator( RRDTOOL )
1533
1534        global DEBUG_LEVEL
1535
1536        if DEBUG_LEVEL <= 2:
1537            self.gatherLastUpdates()
1538
1539    def gatherLastUpdates( self ):
1540        """Populate the lastStored list, containing timestamps of all last updates"""
1541
1542        cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster )
1543
1544        hosts = [ ]
1545
1546        if os.path.exists( cluster_dir ):
1547
1548            dirlist = os.listdir( cluster_dir )
1549
1550            for dir in dirlist:
1551
1552                hosts.append( dir )
1553
1554        for host in hosts:
1555
1556            host_dir    = cluster_dir + '/' + host
1557            dirlist        = os.listdir( host_dir )
1558
1559            for dir in dirlist:
1560
1561                if not self.timeserials.has_key( host ):
1562
1563                    self.timeserials[ host ] = [ ]
1564
1565                self.timeserials[ host ].append( dir )
1566
1567            last_serial = self.getLastRrdTimeSerial( host )
1568
1569            if last_serial:
1570
1571                metric_dir = cluster_dir + '/' + host + '/' + last_serial
1572
1573                if os.path.exists( metric_dir ):
1574
1575                    dirlist = os.listdir( metric_dir )
1576
1577                    for file in dirlist:
1578
1579                        metricname = file.split( '.rrd' )[0]
1580
1581                        if not self.lastStored.has_key( host ):
1582
1583                            self.lastStored[ host ] = { }
1584
1585                        self.lastStored[ host ][ metricname ] = self.rrdm.grabLastUpdate( metric_dir + '/' + file )
1586
1587    def getClusterName( self ):
1588        """Return clustername"""
1589
1590        return self.cluster
1591
1592    def memMetric( self, host, metric ):
1593        """Store metric from host in memory"""
1594
1595        # <ATOMIC>
1596        #
1597        self.slot.acquire()
1598       
1599        if self.myMetrics.has_key( host ):
1600
1601            if self.myMetrics[ host ].has_key( metric['name'] ):
1602
1603                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
1604
1605                    if mymetric['time'] == metric['time']:
1606
1607                        # Allready have this metric, abort
1608                        self.slot.release()
1609                        return 1
1610            else:
1611                self.myMetrics[ host ][ metric['name'] ] = [ ]
1612        else:
1613            self.myMetrics[ host ]                = { }
1614            self.myMetrics[ host ][ metric['name'] ]    = [ ]
1615
1616        # Push new metric onto stack
1617        # atomic code; only 1 thread at a time may access the stack
1618
1619        self.myMetrics[ host ][ metric['name'] ].append( metric )
1620
1621        self.slot.release()
1622        #
1623        # </ATOMIC>
1624
1625    def makeUpdateList( self, host, metriclist ):
1626        """
1627        Make a list of update values for rrdupdate
1628        but only those that we didn't store before
1629        """
1630
1631        update_list    = [ ]
1632        metric        = None
1633
1634        while len( metriclist ) > 0:
1635
1636            metric = metriclist.pop( 0 )
1637
1638            if self.checkStoreMetric( host, metric ):
1639
1640                u_val    = str( metric['time'] ) + ':' + str( metric['val'] )
1641                #update_list.append( str('%s:%s') %( metric['time'], metric['val'] ) )
1642                update_list.append( u_val )
1643
1644        return update_list
1645
1646    def checkStoreMetric( self, host, metric ):
1647        """Check if supplied metric if newer than last one stored"""
1648
1649        if self.lastStored.has_key( host ):
1650
1651            if self.lastStored[ host ].has_key( metric['name'] ):
1652
1653                if metric['time'] <= self.lastStored[ host ][ metric['name'] ]:
1654
1655                    # This is old
1656                    return 0
1657
1658        return 1
1659
1660    def memLastUpdate( self, host, metricname, metriclist ):
1661        """
1662        Memorize the time of the latest metric from metriclist
1663        but only if it wasn't allready memorized
1664        """
1665
1666        if not self.lastStored.has_key( host ):
1667            self.lastStored[ host ] = { }
1668
1669        last_update_time = 0
1670
1671        for metric in metriclist:
1672
1673            if metric['name'] == metricname:
1674
1675                if metric['time'] > last_update_time:
1676
1677                    last_update_time = metric['time']
1678
1679        if self.lastStored[ host ].has_key( metricname ):
1680           
1681            if last_update_time <= self.lastStored[ host ][ metricname ]:
1682                return 1
1683
1684        self.lastStored[ host ][ metricname ] = last_update_time
1685
1686    def storeMetrics( self ):
1687        """
1688        Store all metrics from memory to disk
1689        and do it to the RRD's in appropriate timeperiod directory
1690        """
1691
1692        debug_msg( 5, "Entering storeMetrics()")
1693
1694        count_values    = 0
1695        count_metrics    = 0
1696        count_bits    = 0
1697
1698        for hostname, mymetrics in self.myMetrics.items():   
1699
1700            for metricname, mymetric in mymetrics.items():
1701
1702                count_metrics += 1
1703
1704                for dmetric in mymetric:
1705
1706                    count_values += 1
1707
1708                    count_bits    += len( dmetric['time'] )
1709                    count_bits    += len( dmetric['val'] )
1710
1711        count_bytes    = count_bits / 8
1712
1713        debug_msg( 5, "size of cluster '" + self.cluster + "': " + 
1714            str( len( self.myMetrics.keys() ) ) + " hosts " + 
1715            str( count_metrics ) + " metrics " + str( count_values ) + " values " +
1716            str( count_bits ) + " bits " + str( count_bytes ) + " bytes " )
1717
1718        for hostname, mymetrics in self.myMetrics.items():   
1719
1720            for metricname, mymetric in mymetrics.items():
1721
1722                metrics_to_store = [ ]
1723
1724                # Pop metrics from stack for storing until none is left
1725                # atomic code: only 1 thread at a time may access myMetrics
1726
1727                # <ATOMIC>
1728                #
1729                self.slot.acquire() 
1730
1731                while len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1732
1733                    if len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1734
1735                        try:
1736                            metrics_to_store.append( self.myMetrics[ hostname ][ metricname ].pop( 0 ) )
1737                        except IndexError, msg:
1738
1739                            # Somehow sometimes myMetrics[ hostname ][ metricname ]
1740                            # is still len 0 when the statement is executed.
1741                            # Just ignore indexerror's..
1742                            pass
1743
1744                self.slot.release()
1745                #
1746                # </ATOMIC>
1747
1748                # Create a mapping table, each metric to the period where it should be stored
1749                #
1750                metric_serial_table = self.determineSerials( hostname, metricname, metrics_to_store )
1751
1752                update_rets = [ ]
1753
1754                for period, pmetric in metric_serial_table.items():
1755
1756                    create_ret = self.createCheck( hostname, metricname, period )   
1757
1758                    update_ret = self.update( hostname, metricname, period, pmetric )
1759
1760                    if update_ret == 0:
1761
1762                        debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
1763                    else:
1764                        debug_msg( 9, 'metric update failed' )
1765
1766                    update_rets.append( create_ret )
1767                    update_rets.append( update_ret )
1768
1769                # Lets ignore errors here for now, we need to make sure last update time
1770                # is correct!
1771                #
1772                #if not (1) in update_rets:
1773
1774                self.memLastUpdate( hostname, metricname, metrics_to_store )
1775
1776        debug_msg( 5, "Leaving storeMetrics()")
1777
1778    def makeTimeSerial( self ):
1779        """Generate a time serial. Seconds since epoch"""
1780
1781        # Seconds since epoch
1782        mytime = int( time.time() )
1783
1784        return mytime
1785
1786    def makeRrdPath( self, host, metricname, timeserial ):
1787        """Make a RRD location/path and filename"""
1788
1789        rrd_dir        = '%s/%s/%s/%s'    %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
1790        rrd_file    = '%s/%s.rrd'    %( rrd_dir, metricname )
1791
1792        return rrd_dir, rrd_file
1793
1794    def getLastRrdTimeSerial( self, host ):
1795        """Find the last timeserial (directory) for this host"""
1796
1797        newest_timeserial = 0
1798
1799        for dir in self.timeserials[ host ]:
1800
1801            valid_dir = 1
1802
1803            for letter in dir:
1804                if letter not in string.digits:
1805                    valid_dir = 0
1806
1807            if valid_dir:
1808                timeserial = dir
1809                if timeserial > newest_timeserial:
1810                    newest_timeserial = timeserial
1811
1812        if newest_timeserial:
1813            return newest_timeserial
1814        else:
1815            return 0
1816
1817    def determinePeriod( self, host, check_serial ):
1818        """Determine to which period (directory) this time(serial) belongs"""
1819
1820        period_serial = 0
1821
1822        if self.timeserials.has_key( host ):
1823
1824            for serial in self.timeserials[ host ]:
1825
1826                if check_serial >= serial and period_serial < serial:
1827
1828                    period_serial = serial
1829
1830        return period_serial
1831
1832    def determineSerials( self, host, metricname, metriclist ):
1833        """
1834        Determine the correct serial and corresponding rrd to store
1835        for a list of metrics
1836        """
1837
1838        metric_serial_table = { }
1839
1840        for metric in metriclist:
1841
1842            if metric['name'] == metricname:
1843
1844                period        = self.determinePeriod( host, metric['time'] )   
1845
1846                archive_secs    = ARCHIVE_HOURS_PER_RRD * (60 * 60)
1847
1848                if (int( metric['time'] ) - int( period ) ) > archive_secs:
1849
1850                    # This one should get it's own new period
1851                    period = metric['time']
1852
1853                    if not self.timeserials.has_key( host ):
1854                        self.timeserials[ host ] = [ ]
1855
1856                    self.timeserials[ host ].append( period )
1857
1858                if not metric_serial_table.has_key( period ):
1859
1860                    metric_serial_table[ period ] = [ ]
1861
1862                metric_serial_table[ period ].append( metric )
1863
1864        return metric_serial_table
1865
1866    def createCheck( self, host, metricname, timeserial ):
1867        """Check if an rrd allready exists for this metric, create if not"""
1868
1869        debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1870       
1871        rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
1872
1873        if not os.path.exists( rrd_dir ):
1874
1875            try:
1876                os.makedirs( rrd_dir )
1877
1878            except os.OSError, msg:
1879
1880                if msg.find( 'File exists' ) != -1:
1881
1882                    # Ignore exists errors
1883                    pass
1884
1885                else:
1886
1887                    print msg
1888                    return
1889
1890            debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
1891
1892        if not os.path.exists( rrd_file ):
1893
1894            interval    = self.config.getInterval( self.cluster )
1895            heartbeat    = 8 * int( interval )
1896
1897            params        = [ ]
1898
1899            params.append( '--step' )
1900            params.append( str( interval ) )
1901
1902            params.append( '--start' )
1903            params.append( str( int( timeserial ) - 1 ) )
1904
1905            params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat )
1906            params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) )
1907
1908            self.rrdm.create( str(rrd_file), params )
1909
1910            debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
1911
1912    def update( self, host, metricname, timeserial, metriclist ):
1913        """
1914        Update rrd file for host with metricname
1915        in directory timeserial with metriclist
1916        """
1917
1918        debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1919
1920        rrd_dir, rrd_file    = self.makeRrdPath( host, metricname, timeserial )
1921
1922        update_list        = self.makeUpdateList( host, metriclist )
1923
1924        if len( update_list ) > 0:
1925            ret = self.rrdm.update( str(rrd_file), update_list )
1926
1927            if ret:
1928                return 1
1929       
1930            debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) )
1931
1932        return 0
1933
1934def daemon():
1935    """daemonized threading"""
1936
1937    # Fork the first child
1938    #
1939    pid = os.fork()
1940
1941    if pid > 0:
1942
1943        sys.exit(0)  # end parent
1944
1945    # creates a session and sets the process group ID
1946    #
1947    os.setsid()
1948
1949    # Fork the second child
1950    #
1951    pid = os.fork()
1952
1953    if pid > 0:
1954
1955        sys.exit(0)  # end parent
1956
1957    write_pidfile()
1958
1959    # Go to the root directory and set the umask
1960    #
1961    os.chdir('/')
1962    os.umask(0)
1963
1964    sys.stdin.close()
1965    sys.stdout.close()
1966    sys.stderr.close()
1967
1968    os.open('/dev/null', os.O_RDWR)
1969    os.dup2(0, 1)
1970    os.dup2(0, 2)
1971
1972    run()
1973
1974def run():
1975    """Threading start"""
1976
1977    config        = GangliaConfigParser( GMETAD_CONF )
1978    s_timeout    = int( config.getLowestInterval() - 1 )
1979
1980    socket.setdefaulttimeout( s_timeout )
1981
1982    myXMLSource        = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] )
1983    myDataStore        = DataSQLStore( JOB_SQL_DBASE.split( '/' )[0], JOB_SQL_DBASE.split( '/' )[1] )
1984
1985    myTorqueProcessor    = TorqueXMLProcessor( myXMLSource, myDataStore )
1986    myGangliaProcessor    = GangliaXMLProcessor( myXMLSource, myDataStore )
1987
1988    try:
1989        torque_xml_thread    = threading.Thread( None, myTorqueProcessor.run, 'torque_proc_thread' )
1990        ganglia_xml_thread    = threading.Thread( None, myGangliaProcessor.run, 'ganglia_proc_thread' )
1991
1992        torque_xml_thread.start()
1993        ganglia_xml_thread.start()
1994       
1995    except thread.error, msg:
1996        debug_msg( 0, 'FATAL ERROR: Unable to start main threads!: '+ str(msg) )
1997        syslog.closelog()
1998        sys.exit(1)
1999       
2000    debug_msg( 0, 'main threading started.' )
2001
2002def main():
2003    """Program startup"""
2004
2005    global DAEMONIZE, USE_SYSLOG
2006
2007    if not processArgs( sys.argv[1:] ):
2008        sys.exit( 1 )
2009
2010    if( DAEMONIZE and USE_SYSLOG ):
2011        syslog.openlog( 'jobarchived', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
2012
2013    if DAEMONIZE:
2014        daemon()
2015    else:
2016        run()
2017
2018#
2019# Global functions
2020#
2021
2022def check_dir( directory ):
2023    """Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"""
2024
2025    if directory[-1] == '/':
2026        directory = directory[:-1]
2027
2028    return directory
2029
2030def reqtime2epoch( rtime ):
2031
2032    (hours, minutes, seconds )    = rtime.split( ':' )
2033
2034    etime    = int(seconds)
2035    etime    = etime + ( int(minutes) * 60 )
2036    etime    = etime + ( int(hours) * 60 * 60 )
2037
2038    return etime
2039
2040def debug_msg( level, msg ):
2041    """Only print msg if correct levels"""
2042
2043    if (not DAEMONIZE and DEBUG_LEVEL >= level):
2044        sys.stderr.write( printTime() + ' - ' + msg + '\n' )
2045   
2046    if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
2047        syslog.syslog( msg )
2048
2049def printTime( ):
2050    """Print current time in human readable format"""
2051
2052    return time.strftime("%a %d %b %Y %H:%M:%S")
2053
2054def write_pidfile():
2055
2056    # Write pidfile if PIDFILE exists
2057    if PIDFILE:
2058
2059        pid     = os.getpid()
2060
2061        pidfile = open(PIDFILE, 'w')
2062
2063        pidfile.write( str( pid ) )
2064        pidfile.close()
2065
2066# Ooohh, someone started me! Let's go..
2067#
2068if __name__ == '__main__':
2069    main()
Note: See TracBrowser for help on using the repository browser.