source: trunk/jobarchived/jobarchived.py @ 289

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

jobarchived/jobarchived.py:

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