source: trunk/jobarchived/jobarchived.py @ 365

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

jobarchived/jobarchived.py:

  • rewritten to use py-rrdtool api and no more pipes
  • Property svn:keywords set to Id
File size: 41.2 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 365 2007-06-13 08:20:05Z 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 = attrs.get( 'NAME', "" )
587
588                elif name == 'METRIC' and self.clustername in ARCHIVE_DATASOURCES:
589
590                        metricname = attrs.get( 'NAME', "" )
591
592                        if metricname == 'MONARCH-HEARTBEAT':
593                                self.heartbeat = attrs.get( 'VAL', "" )
594
595                        elif metricname.find( 'MONARCH-JOB' ) != -1:
596
597                                job_id  = metricname.split( 'MONARCH-JOB-' )[1].split( '-' )[0]
598                                val     = 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))+" 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 item in dirlist:
752
753                                clustername = item
754
755                                if not self.clusters.has_key( clustername ) and clustername in ARCHIVE_DATASOURCES:
756
757                                        self.clusters[ clustername ] = RRDHandler( self.config, clustername )
758
759                debug_msg( 9, "Found "+str(len(self.clusters.keys()))+" clusters" )
760
761        def startElement( self, name, attrs ):
762                """Memorize appropriate data from xml start tags"""
763
764                if name == 'GANGLIA_XML':
765
766                        self.XMLSource          = attrs.get( 'SOURCE', "" )
767                        self.gangliaVersion     = attrs.get( 'VERSION', "" )
768
769                        debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
770
771                elif name == 'GRID':
772
773                        self.gridName   = attrs.get( 'NAME', "" )
774                        self.time       = attrs.get( 'LOCALTIME', "" )
775
776                        debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
777
778                elif name == 'CLUSTER':
779
780                        self.clusterName        = attrs.get( 'NAME', "" )
781                        self.time               = attrs.get( 'LOCALTIME', "" )
782
783                        if not self.clusters.has_key( self.clusterName ) and self.clusterName in ARCHIVE_DATASOURCES:
784
785                                self.clusters[ self.clusterName ] = RRDHandler( self.config, self.clusterName )
786
787                                debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
788
789                elif name == 'HOST' and self.clusterName in ARCHIVE_DATASOURCES:     
790
791                        self.hostName           = attrs.get( 'NAME', "" )
792                        self.hostIp             = attrs.get( 'IP', "" )
793                        self.hostReported       = attrs.get( 'REPORTED', "" )
794
795                        debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
796
797                elif name == 'METRIC' and self.clusterName in ARCHIVE_DATASOURCES:
798
799                        type = attrs.get( 'TYPE', "" )
800                       
801                        exclude_metric = False
802                       
803                        for ex_metricstr in ARCHIVE_EXCLUDE_METRICS:
804
805                                orig_name = attrs.get( 'NAME', "" )     
806
807                                if string.lower( orig_name ) == string.lower( ex_metricstr ):
808                               
809                                        exclude_metric = True
810
811                                elif re.match( ex_metricstr, orig_name ):
812
813                                        exclude_metric = True
814
815                        if type not in UNSUPPORTED_ARCHIVE_TYPES and not exclude_metric:
816
817                                myMetric                = { }
818                                myMetric['name']        = attrs.get( 'NAME', "" )
819                                myMetric['val']         = attrs.get( 'VAL', "" )
820                                myMetric['time']        = self.hostReported
821
822                                self.clusters[ self.clusterName ].memMetric( self.hostName, myMetric )
823
824                                debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
825
826        def storeMetrics( self ):
827                """Store metrics of each cluster rrd handler"""
828
829                for clustername, rrdh in self.clusters.items():
830
831                        ret = rrdh.storeMetrics()
832
833                        if ret:
834                                debug_msg( 9, 'An error occured while storing metrics for cluster %s' %clustername )
835                                return 1
836
837                return 0
838
839class XMLErrorHandler( xml.sax.handler.ErrorHandler ):
840
841        def error( self, exception ):
842                """Recoverable error"""
843
844                debug_msg( 0, 'Recoverable XML error ' + str( exception ) + ' ignored.' )
845
846        def fatalError( self, exception ):
847                """Non-recoverable error"""
848
849                exception_str = str( exception )
850
851                # Ignore 'no element found' errors
852                if exception_str.find( 'no element found' ) != -1:
853                        debug_msg( 0, 'No XML data found: Socket not (re)connected or datasource not available.' )
854                        return 0
855
856                debug_msg( 0, 'FATAL ERROR: Non-recoverable XML error ' + str( exception ) )
857                sys.exit( 1 )
858
859        def warning( self, exception ):
860                """Warning"""
861
862                debug_msg( 0, 'Warning ' + str( exception ) )
863
864class XMLGatherer:
865        """Setup a connection and file object to Ganglia's XML"""
866
867        s               = None
868        fd              = None
869        data            = None
870        slot            = None
871
872        # Time since the last update
873        #
874        LAST_UPDATE     = 0
875
876        # Minimum interval between updates
877        #
878        MIN_UPDATE_INT  = 10
879
880        # Is a update occuring now
881        #
882        update_now      = False
883
884        def __init__( self, host, port ):
885                """Store host and port for connection"""
886
887                self.host       = host
888                self.port       = port
889                self.slot       = threading.Lock()
890
891                self.retrieveData()
892
893        def retrieveData( self ):
894                """Setup connection to XML source"""
895
896                self.update_now = True
897
898                self.slot.acquire()
899
900                for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ):
901
902                        af, socktype, proto, canonname, sa = res
903
904                        try:
905
906                                self.s = socket.socket( af, socktype, proto )
907
908                        except socket.error, msg:
909
910                                self.s = None
911                                continue
912
913                        try:
914
915                                self.s.connect( sa )
916
917                        except socket.error, msg:
918
919                                self.disconnect()
920                                continue
921
922                        break
923
924                if self.s is None:
925
926                        debug_msg( 0, 'FATAL ERROR: Could not open socket or unable to connect to datasource!' )
927                        self.update_now = False
928                        sys.exit( 1 )
929
930                else:
931                        #self.s.send( '\n' )
932
933                        my_fp                   = self.s.makefile( 'r' )
934                        my_data                 = my_fp.readlines()
935                        my_data                 = string.join( my_data, '' )
936
937                        self.data               = my_data
938
939                        self.LAST_UPDATE        = time.time()
940
941                self.slot.release()
942
943                self.update_now = False
944
945        def disconnect( self ):
946                """Close socket"""
947
948                if self.s:
949                        #self.s.shutdown( 2 )
950                        self.s.close()
951                        self.s = None
952
953        def __del__( self ):
954                """Kill the socket before we leave"""
955
956                self.disconnect()
957
958        def reGetData( self ):
959                """Reconnect"""
960
961                while self.update_now:
962
963                        # Must be another update in progress:
964                        # Wait until the update is complete
965                        #
966                        time.sleep( 1 )
967
968                if self.s:
969                        self.disconnect()
970
971                self.retrieveData()
972
973        def getData( self ):
974
975                """Return the XML data"""
976
977                # If more than MIN_UPDATE_INT seconds passed since last data update
978                # update the XML first before returning it
979                #
980
981                cur_time        = time.time()
982
983                if ( cur_time - self.LAST_UPDATE ) > self.MIN_UPDATE_INT:
984
985                        self.reGetData()
986
987                while self.update_now:
988
989                        # Must be another update in progress:
990                        # Wait until the update is complete
991                        #
992                        time.sleep( 1 )
993                       
994                return self.data
995
996        def makeFileDescriptor( self ):
997                """Make file descriptor that points to our socket connection"""
998
999                self.reconnect()
1000
1001                if self.s:
1002                        self.fd = self.s.makefile( 'r' )
1003
1004        def getFileObject( self ):
1005                """Connect, and return a file object"""
1006
1007                self.makeFileDescriptor()
1008
1009                if self.fd:
1010                        return self.fd
1011
1012class GangliaXMLProcessor( XMLProcessor ):
1013        """Main class for processing XML and acting with it"""
1014
1015        def __init__( self, XMLSource, DataStore ):
1016                """Setup initial XML connection and handlers"""
1017
1018                self.config             = GangliaConfigParser( GMETAD_CONF )
1019
1020                #self.myXMLGatherer     = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] )
1021                #self.myXMLSource       = self.myXMLGatherer.getFileObject()
1022                self.myXMLSource        = XMLSource
1023                self.ds                 = DataStore
1024                self.myXMLHandler       = GangliaXMLHandler( self.config, self.ds )
1025                self.myXMLError         = XMLErrorHandler()
1026
1027        def run( self ):
1028                """Main XML processing; start a xml and storethread"""
1029
1030                xml_thread = threading.Thread( None, self.processXML, 'xmlthread' )
1031                store_thread = threading.Thread( None, self.storeMetrics, 'storethread' )
1032
1033                while( 1 ):
1034
1035                        if not xml_thread.isAlive():
1036                                # Gather XML at the same interval as gmetad
1037
1038                                # threaded call to: self.processXML()
1039                                #
1040                                try:
1041                                        xml_thread = threading.Thread( None, self.processXML, 'xml_thread' )
1042                                        xml_thread.start()
1043                                except thread.error, msg:
1044                                        debug_msg( 0, 'ERROR: Unable to start xml_thread!: '+str(msg))
1045                                        #return 1
1046
1047                        if not store_thread.isAlive():
1048                                # Store metrics every .. sec
1049
1050                                # threaded call to: self.storeMetrics()
1051                                #
1052                                try:
1053                                        store_thread = threading.Thread( None, self.storeMetrics, 'store_thread' )
1054                                        store_thread.start()
1055                                except thread.error, msg:
1056                                        debug_msg( 0, 'ERROR: Unable to start store_thread!: '+str(msg))
1057                                        #return 1
1058               
1059                        # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway
1060                        time.sleep( 1 ) 
1061
1062        def storeMetrics( self ):
1063                """Store metrics retained in memory to disk"""
1064
1065                global DEBUG_LEVEL
1066
1067                # Store metrics somewhere between every 360 and 640 seconds
1068                #
1069                if DEBUG_LEVEL > 2:
1070                        #STORE_INTERVAL = 60
1071                        STORE_INTERVAL = random.randint( 360, 640 )
1072                else:
1073                        STORE_INTERVAL = random.randint( 360, 640 )
1074
1075                try:
1076                        store_metric_thread = threading.Thread( None, self.storeThread, 'store_metric_thread' )
1077                        store_metric_thread.start()
1078                except thread.error, msg:
1079                        debug_msg( 0, 'ERROR: Unable to start ganglia_store_thread()!: '+str(msg) )
1080                        return 1
1081
1082                debug_msg( 1, 'ganglia_store_thread(): started.' )
1083
1084                debug_msg( 1, 'ganglia_store_thread(): Sleeping.. (%ss)' %STORE_INTERVAL )
1085                time.sleep( STORE_INTERVAL )
1086                debug_msg( 1, 'ganglia_store_thread(): Done sleeping.' )
1087
1088                if store_metric_thread.isAlive():
1089
1090                        debug_msg( 1, 'ganglia_store_thread(): storemetricthread() still running, waiting to finish..' )
1091                        store_metric_thread.join( STORE_TIMEOUT ) # Maximum time is for storing thread to finish
1092                        debug_msg( 1, 'ganglia_store_thread(): Done waiting.' )
1093
1094                debug_msg( 1, 'ganglia_store_thread(): finished.' )
1095
1096                return 0
1097
1098        def storeThread( self ):
1099                """Actual metric storing thread"""
1100
1101                debug_msg( 1, 'ganglia_store_metric_thread(): started.' )
1102                debug_msg( 1, 'ganglia_store_metric_thread(): Storing data..' )
1103                ret = self.myXMLHandler.storeMetrics()
1104                if ret > 0:
1105                        debug_msg( 0, 'ganglia_store_metric_thread(): UNKNOWN ERROR %s while storing Metrics!' %str(ret) )
1106                debug_msg( 1, 'ganglia_store_metric_thread(): Done storing.' )
1107                debug_msg( 1, 'ganglia_store_metric_thread(): finished.' )
1108               
1109                return 0
1110
1111        def processXML( self ):
1112                """Process XML"""
1113
1114                try:
1115                        parsethread = threading.Thread( None, self.parseThread, 'parsethread' )
1116                        parsethread.start()
1117                except thread.error, msg:
1118                        debug_msg( 0, 'ERROR: Unable to start ganglia_xml_thread()!: ' + str(msg) )
1119                        return 1
1120
1121                debug_msg( 1, 'ganglia_xml_thread(): started.' )
1122
1123                debug_msg( 1, 'ganglia_xml_thread(): Sleeping.. (%ss)' %self.config.getLowestInterval() )
1124                time.sleep( float( self.config.getLowestInterval() ) ) 
1125                debug_msg( 1, 'ganglia_xml_thread(): Done sleeping.' )
1126
1127                if parsethread.isAlive():
1128
1129                        debug_msg( 1, 'ganglia_xml_thread(): parsethread() still running, waiting (%ss) to finish..' %PARSE_TIMEOUT )
1130                        parsethread.join( PARSE_TIMEOUT ) # Maximum time for XML thread to finish
1131                        debug_msg( 1, 'ganglia_xml_thread(): Done waiting.' )
1132
1133                debug_msg( 1, 'ganglia_xml_thread(): finished.' )
1134
1135                return 0
1136
1137        def parseThread( self ):
1138                """Actual parsing thread"""
1139
1140                debug_msg( 1, 'ganglia_parse_thread(): started.' )
1141                debug_msg( 1, 'ganglia_parse_thread(): Parsing XML..' )
1142                #self.myXMLSource = self.myXMLGatherer.getFileObject()
1143               
1144                my_data = self.myXMLSource.getData()
1145
1146                #print my_data
1147
1148                try:
1149                        xml.sax.parseString( my_data, self.myXMLHandler, self.myXMLError )
1150                except socket.error, msg:
1151                        debug_msg( 0, 'ERROR: Socket error in connect to datasource!: %s' %msg )
1152
1153                debug_msg( 1, 'ganglia_parse_thread(): Done parsing.' )
1154                debug_msg( 1, 'ganglia_parse_thread(): finished.' )
1155
1156                return 0
1157
1158class GangliaConfigParser:
1159
1160        sources = [ ]
1161
1162        def __init__( self, config ):
1163                """Parse some stuff from our gmetad's config, such as polling interval"""
1164
1165                self.config = config
1166                self.parseValues()
1167
1168        def parseValues( self ):
1169                """Parse certain values from gmetad.conf"""
1170
1171                readcfg = open( self.config, 'r' )
1172
1173                for line in readcfg.readlines():
1174
1175                        if line.count( '"' ) > 1:
1176
1177                                if line.find( 'data_source' ) != -1 and line[0] != '#':
1178
1179                                        source          = { }
1180                                        source['name']  = line.split( '"' )[1]
1181                                        source_words    = line.split( '"' )[2].split( ' ' )
1182
1183                                        for word in source_words:
1184
1185                                                valid_interval = 1
1186
1187                                                for letter in word:
1188
1189                                                        if letter not in string.digits:
1190
1191                                                                valid_interval = 0
1192
1193                                                if valid_interval and len(word) > 0:
1194
1195                                                        source['interval'] = word
1196                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
1197       
1198                                        # No interval found, use Ganglia's default     
1199                                        if not source.has_key( 'interval' ):
1200                                                source['interval'] = 15
1201                                                debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
1202
1203                                        self.sources.append( source )
1204
1205        def getInterval( self, source_name ):
1206                """Return interval for source_name"""
1207
1208                for source in self.sources:
1209
1210                        if source['name'] == source_name:
1211
1212                                return source['interval']
1213
1214                return None
1215
1216        def getLowestInterval( self ):
1217                """Return the lowest interval of all clusters"""
1218
1219                lowest_interval = 0
1220
1221                for source in self.sources:
1222
1223                        if not lowest_interval or source['interval'] <= lowest_interval:
1224
1225                                lowest_interval = source['interval']
1226
1227                # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays
1228                if lowest_interval:
1229                        return lowest_interval
1230                else:
1231                        return 15
1232
1233class RRDHandler:
1234        """Class for handling RRD activity"""
1235
1236        myMetrics = { }
1237        lastStored = { }
1238        timeserials = { }
1239        slot = None
1240
1241        def __init__( self, config, cluster ):
1242                """Setup initial variables"""
1243
1244                self.block      = 0
1245                self.cluster    = cluster
1246                self.config     = config
1247                self.slot       = threading.Lock()
1248                self.rrdm       = RRDMutator( RRDTOOL )
1249
1250                global DEBUG_LEVEL
1251
1252                if DEBUG_LEVEL <= 2:
1253                        self.gatherLastUpdates()
1254
1255        def gatherLastUpdates( self ):
1256                """Populate the lastStored list, containing timestamps of all last updates"""
1257
1258                cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster )
1259
1260                hosts = [ ]
1261
1262                if os.path.exists( cluster_dir ):
1263
1264                        dirlist = os.listdir( cluster_dir )
1265
1266                        for dir in dirlist:
1267
1268                                hosts.append( dir )
1269
1270                for host in hosts:
1271
1272                        host_dir        = cluster_dir + '/' + host
1273                        dirlist         = os.listdir( host_dir )
1274
1275                        for dir in dirlist:
1276
1277                                if not self.timeserials.has_key( host ):
1278
1279                                        self.timeserials[ host ] = [ ]
1280
1281                                self.timeserials[ host ].append( dir )
1282
1283                        last_serial = self.getLastRrdTimeSerial( host )
1284
1285                        if last_serial:
1286
1287                                metric_dir = cluster_dir + '/' + host + '/' + last_serial
1288
1289                                if os.path.exists( metric_dir ):
1290
1291                                        dirlist = os.listdir( metric_dir )
1292
1293                                        for file in dirlist:
1294
1295                                                metricname = file.split( '.rrd' )[0]
1296
1297                                                if not self.lastStored.has_key( host ):
1298
1299                                                        self.lastStored[ host ] = { }
1300
1301                                                self.lastStored[ host ][ metricname ] = self.rrdm.grabLastUpdate( metric_dir + '/' + file )
1302
1303        def getClusterName( self ):
1304                """Return clustername"""
1305
1306                return self.cluster
1307
1308        def memMetric( self, host, metric ):
1309                """Store metric from host in memory"""
1310
1311                # <ATOMIC>
1312                #
1313                self.slot.acquire()
1314               
1315                if self.myMetrics.has_key( host ):
1316
1317                        if self.myMetrics[ host ].has_key( metric['name'] ):
1318
1319                                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
1320
1321                                        if mymetric['time'] == metric['time']:
1322
1323                                                # Allready have this metric, abort
1324                                                self.slot.release()
1325                                                return 1
1326                        else:
1327                                self.myMetrics[ host ][ metric['name'] ] = [ ]
1328                else:
1329                        self.myMetrics[ host ]                          = { }
1330                        self.myMetrics[ host ][ metric['name'] ]        = [ ]
1331
1332                # Push new metric onto stack
1333                # atomic code; only 1 thread at a time may access the stack
1334
1335                self.myMetrics[ host ][ metric['name'] ].append( metric )
1336
1337                self.slot.release()
1338                #
1339                # </ATOMIC>
1340
1341        def makeUpdateList( self, host, metriclist ):
1342                """
1343                Make a list of update values for rrdupdate
1344                but only those that we didn't store before
1345                """
1346
1347                update_list     = [ ]
1348                metric          = None
1349
1350                while len( metriclist ) > 0:
1351
1352                        metric = metriclist.pop( 0 )
1353
1354                        if self.checkStoreMetric( host, metric ):
1355
1356                                u_val   = str( metric['time'] ) + ':' + str( metric['val'] )
1357                                #update_list.append( str('%s:%s') %( metric['time'], metric['val'] ) )
1358                                update_list.append( u_val )
1359
1360                return update_list
1361
1362        def checkStoreMetric( self, host, metric ):
1363                """Check if supplied metric if newer than last one stored"""
1364
1365                if self.lastStored.has_key( host ):
1366
1367                        if self.lastStored[ host ].has_key( metric['name'] ):
1368
1369                                if metric['time'] <= self.lastStored[ host ][ metric['name'] ]:
1370
1371                                        # This is old
1372                                        return 0
1373
1374                return 1
1375
1376        def memLastUpdate( self, host, metricname, metriclist ):
1377                """
1378                Memorize the time of the latest metric from metriclist
1379                but only if it wasn't allready memorized
1380                """
1381
1382                if not self.lastStored.has_key( host ):
1383                        self.lastStored[ host ] = { }
1384
1385                last_update_time = 0
1386
1387                for metric in metriclist:
1388
1389                        if metric['name'] == metricname:
1390
1391                                if metric['time'] > last_update_time:
1392
1393                                        last_update_time = metric['time']
1394
1395                if self.lastStored[ host ].has_key( metricname ):
1396                       
1397                        if last_update_time <= self.lastStored[ host ][ metricname ]:
1398                                return 1
1399
1400                self.lastStored[ host ][ metricname ] = last_update_time
1401
1402        def storeMetrics( self ):
1403                """
1404                Store all metrics from memory to disk
1405                and do it to the RRD's in appropriate timeperiod directory
1406                """
1407
1408                debug_msg( 5, "Entering storeMetrics()")
1409
1410                count_values    = 0
1411                count_metrics   = 0
1412                count_bits      = 0
1413
1414                for hostname, mymetrics in self.myMetrics.items():     
1415
1416                        for metricname, mymetric in mymetrics.items():
1417
1418                                count_metrics += 1
1419
1420                                for dmetric in mymetric:
1421
1422                                        count_values += 1
1423
1424                                        count_bits      += len( dmetric['time'] )
1425                                        count_bits      += len( dmetric['val'] )
1426
1427                count_bytes     = count_bits / 8
1428
1429                debug_msg( 5, "size of cluster '" + self.cluster + "': " + 
1430                        str( len( self.myMetrics.keys() ) ) + " hosts " + 
1431                        str( count_metrics ) + " metrics " + str( count_values ) + " values " +
1432                        str( count_bits ) + " bits " + str( count_bytes ) + " bytes " )
1433
1434                for hostname, mymetrics in self.myMetrics.items():     
1435
1436                        for metricname, mymetric in mymetrics.items():
1437
1438                                metrics_to_store = [ ]
1439
1440                                # Pop metrics from stack for storing until none is left
1441                                # atomic code: only 1 thread at a time may access myMetrics
1442
1443                                # <ATOMIC>
1444                                #
1445                                self.slot.acquire() 
1446
1447                                while len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1448
1449                                        if len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1450
1451                                                try:
1452                                                        metrics_to_store.append( self.myMetrics[ hostname ][ metricname ].pop( 0 ) )
1453                                                except IndexError, msg:
1454
1455                                                        # Somehow sometimes myMetrics[ hostname ][ metricname ]
1456                                                        # is still len 0 when the statement is executed.
1457                                                        # Just ignore indexerror's..
1458                                                        pass
1459
1460                                self.slot.release()
1461                                #
1462                                # </ATOMIC>
1463
1464                                # Create a mapping table, each metric to the period where it should be stored
1465                                #
1466                                metric_serial_table = self.determineSerials( hostname, metricname, metrics_to_store )
1467
1468                                update_rets = [ ]
1469
1470                                for period, pmetric in metric_serial_table.items():
1471
1472                                        create_ret = self.createCheck( hostname, metricname, period )   
1473
1474                                        update_ret = self.update( hostname, metricname, period, pmetric )
1475
1476                                        if update_ret == 0:
1477
1478                                                debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
1479                                        else:
1480                                                debug_msg( 9, 'metric update failed' )
1481
1482                                        update_rets.append( create_ret )
1483                                        update_rets.append( update_ret )
1484
1485                                # Lets ignore errors here for now, we need to make sure last update time
1486                                # is correct!
1487                                #
1488                                #if not (1) in update_rets:
1489
1490                                self.memLastUpdate( hostname, metricname, metrics_to_store )
1491
1492                debug_msg( 5, "Leaving storeMetrics()")
1493
1494        def makeTimeSerial( self ):
1495                """Generate a time serial. Seconds since epoch"""
1496
1497                # Seconds since epoch
1498                mytime = int( time.time() )
1499
1500                return mytime
1501
1502        def makeRrdPath( self, host, metricname, timeserial ):
1503                """Make a RRD location/path and filename"""
1504
1505                rrd_dir         = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
1506                rrd_file        = '%s/%s.rrd'   %( rrd_dir, metricname )
1507
1508                return rrd_dir, rrd_file
1509
1510        def getLastRrdTimeSerial( self, host ):
1511                """Find the last timeserial (directory) for this host"""
1512
1513                newest_timeserial = 0
1514
1515                for dir in self.timeserials[ host ]:
1516
1517                        valid_dir = 1
1518
1519                        for letter in dir:
1520                                if letter not in string.digits:
1521                                        valid_dir = 0
1522
1523                        if valid_dir:
1524                                timeserial = dir
1525                                if timeserial > newest_timeserial:
1526                                        newest_timeserial = timeserial
1527
1528                if newest_timeserial:
1529                        return newest_timeserial
1530                else:
1531                        return 0
1532
1533        def determinePeriod( self, host, check_serial ):
1534                """Determine to which period (directory) this time(serial) belongs"""
1535
1536                period_serial = 0
1537
1538                if self.timeserials.has_key( host ):
1539
1540                        for serial in self.timeserials[ host ]:
1541
1542                                if check_serial >= serial and period_serial < serial:
1543
1544                                        period_serial = serial
1545
1546                return period_serial
1547
1548        def determineSerials( self, host, metricname, metriclist ):
1549                """
1550                Determine the correct serial and corresponding rrd to store
1551                for a list of metrics
1552                """
1553
1554                metric_serial_table = { }
1555
1556                for metric in metriclist:
1557
1558                        if metric['name'] == metricname:
1559
1560                                period          = self.determinePeriod( host, metric['time'] ) 
1561
1562                                archive_secs    = ARCHIVE_HOURS_PER_RRD * (60 * 60)
1563
1564                                if (int( metric['time'] ) - int( period ) ) > archive_secs:
1565
1566                                        # This one should get it's own new period
1567                                        period = metric['time']
1568
1569                                        if not self.timeserials.has_key( host ):
1570                                                self.timeserials[ host ] = [ ]
1571
1572                                        self.timeserials[ host ].append( period )
1573
1574                                if not metric_serial_table.has_key( period ):
1575
1576                                        metric_serial_table[ period ] = [ ]
1577
1578                                metric_serial_table[ period ].append( metric )
1579
1580                return metric_serial_table
1581
1582        def createCheck( self, host, metricname, timeserial ):
1583                """Check if an rrd allready exists for this metric, create if not"""
1584
1585                debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1586               
1587                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
1588
1589                if not os.path.exists( rrd_dir ):
1590
1591                        try:
1592                                os.makedirs( rrd_dir )
1593
1594                        except os.OSError, msg:
1595
1596                                if msg.find( 'File exists' ) != -1:
1597
1598                                        # Ignore exists errors
1599                                        pass
1600
1601                                else:
1602
1603                                        print msg
1604                                        return
1605
1606                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
1607
1608                if not os.path.exists( rrd_file ):
1609
1610                        interval        = self.config.getInterval( self.cluster )
1611                        heartbeat       = 8 * int( interval )
1612
1613                        params          = [ ]
1614
1615                        params.append( '--step' )
1616                        params.append( str( interval ) )
1617
1618                        params.append( '--start' )
1619                        params.append( str( int( timeserial ) - 1 ) )
1620
1621                        params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat )
1622                        params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) )
1623
1624                        self.rrdm.create( str(rrd_file), params )
1625
1626                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
1627
1628        def update( self, host, metricname, timeserial, metriclist ):
1629                """
1630                Update rrd file for host with metricname
1631                in directory timeserial with metriclist
1632                """
1633
1634                debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1635
1636                rrd_dir, rrd_file       = self.makeRrdPath( host, metricname, timeserial )
1637
1638                update_list             = self.makeUpdateList( host, metriclist )
1639
1640                if len( update_list ) > 0:
1641                        ret = self.rrdm.update( str(rrd_file), update_list )
1642
1643                        if ret:
1644                                return 1
1645               
1646                        debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) )
1647
1648                return 0
1649
1650def daemon():
1651        """daemonized threading"""
1652
1653        # Fork the first child
1654        #
1655        pid = os.fork()
1656
1657        if pid > 0:
1658
1659                sys.exit(0)  # end parent
1660
1661        # creates a session and sets the process group ID
1662        #
1663        os.setsid()
1664
1665        # Fork the second child
1666        #
1667        pid = os.fork()
1668
1669        if pid > 0:
1670
1671                sys.exit(0)  # end parent
1672
1673        # Go to the root directory and set the umask
1674        #
1675        os.chdir('/')
1676        os.umask(0)
1677
1678        sys.stdin.close()
1679        sys.stdout.close()
1680        sys.stderr.close()
1681
1682        os.open('/dev/null', os.O_RDWR)
1683        os.dup2(0, 1)
1684        os.dup2(0, 2)
1685
1686        run()
1687
1688def run():
1689        """Threading start"""
1690
1691        myXMLSource             = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] )
1692        myDataStore             = DataSQLStore( JOB_SQL_DBASE.split( '/' )[0], JOB_SQL_DBASE.split( '/' )[1] )
1693
1694        myTorqueProcessor       = TorqueXMLProcessor( myXMLSource, myDataStore )
1695        myGangliaProcessor      = GangliaXMLProcessor( myXMLSource, myDataStore )
1696
1697        try:
1698                torque_xml_thread       = threading.Thread( None, myTorqueProcessor.run, 'torque_proc_thread' )
1699                ganglia_xml_thread      = threading.Thread( None, myGangliaProcessor.run, 'ganglia_proc_thread' )
1700
1701                torque_xml_thread.start()
1702                ganglia_xml_thread.start()
1703               
1704        except thread.error, msg:
1705                debug_msg( 0, 'FATAL ERROR: Unable to start main threads!: '+ str(msg) )
1706                syslog.closelog()
1707                sys.exit(1)
1708               
1709        debug_msg( 0, 'main threading started.' )
1710
1711def main():
1712        """Program startup"""
1713
1714        if not processArgs( sys.argv[1:] ):
1715                sys.exit( 1 )
1716
1717        if( DAEMONIZE and USE_SYSLOG ):
1718                syslog.openlog( 'jobarchived', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
1719
1720        if DAEMONIZE:
1721                daemon()
1722        else:
1723                run()
1724
1725#
1726# Global functions
1727#
1728
1729def check_dir( directory ):
1730        """Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"""
1731
1732        if directory[-1] == '/':
1733                directory = directory[:-1]
1734
1735        return directory
1736
1737def reqtime2epoch( rtime ):
1738
1739        (hours, minutes, seconds )      = rtime.split( ':' )
1740
1741        etime   = int(seconds)
1742        etime   = etime + ( int(minutes) * 60 )
1743        etime   = etime + ( int(hours) * 60 * 60 )
1744
1745        return etime
1746
1747def debug_msg( level, msg ):
1748        """Only print msg if correct levels"""
1749
1750        if (not DAEMONIZE and DEBUG_LEVEL >= level):
1751                sys.stderr.write( printTime() + ' - ' + msg + '\n' )
1752       
1753        if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
1754                syslog.syslog( msg )
1755
1756def printTime( ):
1757        """Print current time in human readable format"""
1758
1759        return time.strftime("%a %d %b %Y %H:%M:%S")
1760
1761# Ooohh, someone started me! Let's go..
1762if __name__ == '__main__':
1763        main()
Note: See TracBrowser for help on using the repository browser.