source: trunk/jobarchived/jobarchived.py @ 288

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

jobarchived/jobarchived.py:

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