source: trunk/jobarchived/jobarchived.py @ 372

Last change on this file since 372 was 372, checked in by bastiaans, 17 years ago

jobarchived/jobarchived.py:

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