source: trunk/jobarchived/jobarchived.py @ 287

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

jobarchived/jobarchived.py:

  • changed XML retrieval to work with new gmetad
  • gather XML in same way as webfrontend now
  • use the same XMLGatherer for both XML processors to prevent unnecessary reconnecting
  • 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 287 2006-12-21 09:33:19Z 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
[287]818                        print self.s
819
[5]820                        try:
[32]821
[8]822                                self.s.connect( sa )
[32]823
[5]824                        except socket.error, msg:
[32]825
[70]826                                self.disconnect()
[5]827                                continue
[32]828
[5]829                        break
[3]830
[287]831                print self.s
832
[8]833                if self.s is None:
[32]834
[170]835                        debug_msg( 0, 'FATAL ERROR: Could not open socket or unable to connect to datasource!' )
[287]836                        self.update_now = False
[33]837                        sys.exit( 1 )
[5]838
[287]839                else:
840                        self.s.send( '\n' )
841
842                        my_fp                   = self.s.makefile( 'r' )
843                        my_data                 = my_fp.readlines()
844                        my_data                 = string.join( my_data, '' )
845
846                        self.data               = my_data
847
848                        self.LAST_UPDATE        = time.time()
849
850                self.update_now = False
851
[33]852        def disconnect( self ):
[63]853                """Close socket"""
[33]854
855                if self.s:
[287]856                        #self.s.shutdown( 2 )
[33]857                        self.s.close()
858                        self.s = None
859
860        def __del__( self ):
[63]861                """Kill the socket before we leave"""
[33]862
863                self.disconnect()
864
[287]865        def reGetData( self ):
[70]866                """Reconnect"""
[33]867
[287]868                while self.update_now:
869
870                        # Must be another update in progress:
871                        # Wait until the update is complete
872                        #
873                        time.sleep( 1 )
874
[38]875                if self.s:
876                        self.disconnect()
[33]877
[287]878                self.retrieveData()
[5]879
[287]880        def getData( self ):
881
882                """Return the XML data"""
883
884                # If more than MIN_UPDATE_INT seconds passed since last data update
885                # update the XML first before returning it
886                #
887
888                cur_time        = time.time()
889
890                if ( cur_time - self.LAST_UPDATE ) > self.MIN_UPDATE_INT:
891
892                        self.reGetData()
893
894                while self.update_now:
895
896                        # Must be another update in progress:
897                        # Wait until the update is complete
898                        #
899                        time.sleep( 1 )
900                       
901                return self.data
902
[70]903        def makeFileDescriptor( self ):
904                """Make file descriptor that points to our socket connection"""
905
906                self.reconnect()
907
908                if self.s:
909                        self.fd = self.s.makefile( 'r' )
910
911        def getFileObject( self ):
912                """Connect, and return a file object"""
913
[78]914                self.makeFileDescriptor()
915
[70]916                if self.fd:
917                        return self.fd
918
[78]919class GangliaXMLProcessor( XMLProcessor ):
[63]920        """Main class for processing XML and acting with it"""
[5]921
[287]922        def __init__( self, XMLSource ):
[63]923                """Setup initial XML connection and handlers"""
[33]924
[287]925                self.config             = GangliaConfigParser( GMETAD_CONF )
[33]926
[287]927                self.myXMLGatherer      = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] ) 
928                #self.myXMLSource       = self.myXMLGatherer.getFileObject()
929                self.myXMLSource        = XMLSource
930                print self.myXMLSource
931                self.myXMLHandler       = GangliaXMLHandler( self.config )
932                self.myXMLError         = XMLErrorHandler()
[73]933
[9]934        def run( self ):
[63]935                """Main XML processing; start a xml and storethread"""
[8]936
[102]937                xml_thread = threading.Thread( None, self.processXML, 'xmlthread' )
938                store_thread = threading.Thread( None, self.storeMetrics, 'storethread' )
[22]939
[36]940                while( 1 ):
941
[102]942                        if not xml_thread.isAlive():
[36]943                                # Gather XML at the same interval as gmetad
944
945                                # threaded call to: self.processXML()
946                                #
[169]947                                try:
948                                        xml_thread = threading.Thread( None, self.processXML, 'xml_thread' )
949                                        xml_thread.start()
[176]950                                except thread.error, msg:
[169]951                                        debug_msg( 0, 'ERROR: Unable to start xml_thread!: '+str(msg))
952                                        #return 1
[36]953
[102]954                        if not store_thread.isAlive():
[55]955                                # Store metrics every .. sec
[36]956
[55]957                                # threaded call to: self.storeMetrics()
958                                #
[169]959                                try:
960                                        store_thread = threading.Thread( None, self.storeMetrics, 'store_thread' )
961                                        store_thread.start()
[176]962                                except thread.error, msg:
[169]963                                        debug_msg( 0, 'ERROR: Unable to start store_thread!: '+str(msg))
964                                        #return 1
[36]965               
966                        # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway
967                        time.sleep( 1 ) 
968
[33]969        def storeMetrics( self ):
[63]970                """Store metrics retained in memory to disk"""
[22]971
[63]972                # Store metrics somewhere between every 360 and 640 seconds
[38]973                #
[55]974                STORE_INTERVAL = random.randint( 360, 640 )
[22]975
[169]976                try:
977                        store_metric_thread = threading.Thread( None, self.storeThread, 'store_metric_thread' )
978                        store_metric_thread.start()
[176]979                except thread.error, msg:
[169]980                        debug_msg( 0, 'ERROR: Unable to start ganglia_store_thread()!: '+str(msg) )
981                        return 1
[36]982
[169]983                debug_msg( 1, 'ganglia_store_thread(): started.' )
984
985                debug_msg( 1, 'ganglia_store_thread(): Sleeping.. (%ss)' %STORE_INTERVAL )
[36]986                time.sleep( STORE_INTERVAL )
[169]987                debug_msg( 1, 'ganglia_store_thread(): Done sleeping.' )
[36]988
[102]989                if store_metric_thread.isAlive():
[36]990
[169]991                        debug_msg( 1, 'ganglia_store_thread(): storemetricthread() still running, waiting to finish..' )
[136]992                        store_metric_thread.join( STORE_TIMEOUT ) # Maximum time is for storing thread to finish
[169]993                        debug_msg( 1, 'ganglia_store_thread(): Done waiting.' )
[36]994
[169]995                debug_msg( 1, 'ganglia_store_thread(): finished.' )
[36]996
997                return 0
998
[39]999        def storeThread( self ):
[63]1000                """Actual metric storing thread"""
[39]1001
[169]1002                debug_msg( 1, 'ganglia_store_metric_thread(): started.' )
1003                debug_msg( 1, 'ganglia_store_metric_thread(): Storing data..' )
[78]1004                ret = self.myXMLHandler.storeMetrics()
[176]1005                if ret > 0:
1006                        debug_msg( 0, 'ganglia_store_metric_thread(): UNKNOWN ERROR %s while storing Metrics!' %str(ret) )
[169]1007                debug_msg( 1, 'ganglia_store_metric_thread(): Done storing.' )
1008                debug_msg( 1, 'ganglia_store_metric_thread(): finished.' )
[39]1009               
[176]1010                return 0
[39]1011
[8]1012        def processXML( self ):
[63]1013                """Process XML"""
[8]1014
[169]1015                try:
1016                        parsethread = threading.Thread( None, self.parseThread, 'parsethread' )
1017                        parsethread.start()
[176]1018                except thread.error, msg:
[169]1019                        debug_msg( 0, 'ERROR: Unable to start ganglia_xml_thread()!: ' + str(msg) )
1020                        return 1
[8]1021
[169]1022                debug_msg( 1, 'ganglia_xml_thread(): started.' )
[36]1023
[169]1024                debug_msg( 1, 'ganglia_xml_thread(): Sleeping.. (%ss)' %self.config.getLowestInterval() )
[36]1025                time.sleep( float( self.config.getLowestInterval() ) ) 
[169]1026                debug_msg( 1, 'ganglia_xml_thread(): Done sleeping.' )
[36]1027
1028                if parsethread.isAlive():
1029
[169]1030                        debug_msg( 1, 'ganglia_xml_thread(): parsethread() still running, waiting (%ss) to finish..' %PARSE_TIMEOUT )
[47]1031                        parsethread.join( PARSE_TIMEOUT ) # Maximum time for XML thread to finish
[169]1032                        debug_msg( 1, 'ganglia_xml_thread(): Done waiting.' )
[36]1033
[169]1034                debug_msg( 1, 'ganglia_xml_thread(): finished.' )
[36]1035
1036                return 0
1037
[39]1038        def parseThread( self ):
[63]1039                """Actual parsing thread"""
[39]1040
[169]1041                debug_msg( 1, 'ganglia_parse_thread(): started.' )
1042                debug_msg( 1, 'ganglia_parse_thread(): Parsing XML..' )
[287]1043                #self.myXMLSource = self.myXMLGatherer.getFileObject()
1044               
1045                my_data = self.myXMLSource.getData()
[176]1046
1047                try:
[287]1048                        xml.sax.parseString( my_data, self.myXMLHandler, self.myXMLError )
[176]1049                except socket.error, msg:
1050                        debug_msg( 0, 'ERROR: Socket error in connect to datasource!: %s' %msg )
1051
[169]1052                debug_msg( 1, 'ganglia_parse_thread(): Done parsing.' )
1053                debug_msg( 1, 'ganglia_parse_thread(): finished.' )
[39]1054
[176]1055                return 0
[39]1056
[9]1057class GangliaConfigParser:
1058
[34]1059        sources = [ ]
[9]1060
1061        def __init__( self, config ):
[63]1062                """Parse some stuff from our gmetad's config, such as polling interval"""
[32]1063
[9]1064                self.config = config
1065                self.parseValues()
1066
[32]1067        def parseValues( self ):
[63]1068                """Parse certain values from gmetad.conf"""
[9]1069
1070                readcfg = open( self.config, 'r' )
1071
1072                for line in readcfg.readlines():
1073
1074                        if line.count( '"' ) > 1:
1075
[10]1076                                if line.find( 'data_source' ) != -1 and line[0] != '#':
[9]1077
[11]1078                                        source = { }
1079                                        source['name'] = line.split( '"' )[1]
[9]1080                                        source_words = line.split( '"' )[2].split( ' ' )
1081
1082                                        for word in source_words:
1083
1084                                                valid_interval = 1
1085
1086                                                for letter in word:
[32]1087
[9]1088                                                        if letter not in string.digits:
[32]1089
[9]1090                                                                valid_interval = 0
1091
[10]1092                                                if valid_interval and len(word) > 0:
[32]1093
[9]1094                                                        source['interval'] = word
[12]1095                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
[33]1096       
1097                                        # No interval found, use Ganglia's default     
1098                                        if not source.has_key( 'interval' ):
1099                                                source['interval'] = 15
1100                                                debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
[32]1101
[33]1102                                        self.sources.append( source )
[9]1103
1104        def getInterval( self, source_name ):
[63]1105                """Return interval for source_name"""
[32]1106
[9]1107                for source in self.sources:
[32]1108
[12]1109                        if source['name'] == source_name:
[32]1110
[9]1111                                return source['interval']
[32]1112
[9]1113                return None
1114
[34]1115        def getLowestInterval( self ):
[63]1116                """Return the lowest interval of all clusters"""
[34]1117
1118                lowest_interval = 0
1119
1120                for source in self.sources:
1121
1122                        if not lowest_interval or source['interval'] <= lowest_interval:
1123
1124                                lowest_interval = source['interval']
1125
1126                # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays
1127                if lowest_interval:
1128                        return lowest_interval
1129                else:
1130                        return 15
1131
[9]1132class RRDHandler:
[63]1133        """Class for handling RRD activity"""
[9]1134
[32]1135        myMetrics = { }
[40]1136        lastStored = { }
[47]1137        timeserials = { }
[36]1138        slot = None
[32]1139
[33]1140        def __init__( self, config, cluster ):
[63]1141                """Setup initial variables"""
[78]1142
[44]1143                self.block = 0
[9]1144                self.cluster = cluster
[33]1145                self.config = config
[40]1146                self.slot = threading.Lock()
[277]1147                self.rrdm = RRDMutator( RRDTOOL )
[42]1148                self.gatherLastUpdates()
[9]1149
[42]1150        def gatherLastUpdates( self ):
[63]1151                """Populate the lastStored list, containing timestamps of all last updates"""
[42]1152
1153                cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster )
1154
1155                hosts = [ ]
1156
1157                if os.path.exists( cluster_dir ):
1158
[44]1159                        dirlist = os.listdir( cluster_dir )
[42]1160
[44]1161                        for dir in dirlist:
[42]1162
[44]1163                                hosts.append( dir )
[42]1164
1165                for host in hosts:
1166
[47]1167                        host_dir = cluster_dir + '/' + host
1168                        dirlist = os.listdir( host_dir )
1169
1170                        for dir in dirlist:
1171
1172                                if not self.timeserials.has_key( host ):
1173
1174                                        self.timeserials[ host ] = [ ]
1175
1176                                self.timeserials[ host ].append( dir )
1177
[42]1178                        last_serial = self.getLastRrdTimeSerial( host )
1179                        if last_serial:
1180
1181                                metric_dir = cluster_dir + '/' + host + '/' + last_serial
1182                                if os.path.exists( metric_dir ):
1183
[44]1184                                        dirlist = os.listdir( metric_dir )
[42]1185
[44]1186                                        for file in dirlist:
[42]1187
[44]1188                                                metricname = file.split( '.rrd' )[0]
[42]1189
[44]1190                                                if not self.lastStored.has_key( host ):
[42]1191
[44]1192                                                        self.lastStored[ host ] = { }
[42]1193
[44]1194                                                self.lastStored[ host ][ metricname ] = self.rrdm.grabLastUpdate( metric_dir + '/' + file )
[42]1195
[32]1196        def getClusterName( self ):
[63]1197                """Return clustername"""
1198
[32]1199                return self.cluster
1200
1201        def memMetric( self, host, metric ):
[63]1202                """Store metric from host in memory"""
[32]1203
[179]1204                # <ATOMIC>
1205                #
1206                self.slot.acquire()
1207               
[34]1208                if self.myMetrics.has_key( host ):
[32]1209
[34]1210                        if self.myMetrics[ host ].has_key( metric['name'] ):
[32]1211
[34]1212                                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
[32]1213
[34]1214                                        if mymetric['time'] == metric['time']:
[32]1215
[34]1216                                                # Allready have this metric, abort
[179]1217                                                self.slot.release()
[34]1218                                                return 1
1219                        else:
1220                                self.myMetrics[ host ][ metric['name'] ] = [ ]
1221                else:
[32]1222                        self.myMetrics[ host ] = { }
[34]1223                        self.myMetrics[ host ][ metric['name'] ] = [ ]
[32]1224
[63]1225                # Push new metric onto stack
1226                # atomic code; only 1 thread at a time may access the stack
1227
[32]1228                self.myMetrics[ host ][ metric['name'] ].append( metric )
1229
[40]1230                self.slot.release()
[53]1231                #
1232                # </ATOMIC>
[40]1233
[47]1234        def makeUpdateList( self, host, metriclist ):
[63]1235                """
1236                Make a list of update values for rrdupdate
1237                but only those that we didn't store before
1238                """
[37]1239
1240                update_list = [ ]
[41]1241                metric = None
[37]1242
[47]1243                while len( metriclist ) > 0:
[37]1244
[53]1245                        metric = metriclist.pop( 0 )
[37]1246
[53]1247                        if self.checkStoreMetric( host, metric ):
1248                                update_list.append( '%s:%s' %( metric['time'], metric['val'] ) )
[40]1249
[37]1250                return update_list
1251
[49]1252        def checkStoreMetric( self, host, metric ):
[63]1253                """Check if supplied metric if newer than last one stored"""
[40]1254
1255                if self.lastStored.has_key( host ):
1256
[47]1257                        if self.lastStored[ host ].has_key( metric['name'] ):
[40]1258
[47]1259                                if metric['time'] <= self.lastStored[ host ][ metric['name'] ]:
[40]1260
[50]1261                                        # This is old
[40]1262                                        return 0
1263
[50]1264                return 1
1265
[54]1266        def memLastUpdate( self, host, metricname, metriclist ):
[63]1267                """
1268                Memorize the time of the latest metric from metriclist
1269                but only if it wasn't allready memorized
1270                """
[50]1271
[54]1272                if not self.lastStored.has_key( host ):
1273                        self.lastStored[ host ] = { }
1274
[50]1275                last_update_time = 0
1276
1277                for metric in metriclist:
1278
[54]1279                        if metric['name'] == metricname:
[50]1280
[54]1281                                if metric['time'] > last_update_time:
[50]1282
[54]1283                                        last_update_time = metric['time']
[40]1284
[54]1285                if self.lastStored[ host ].has_key( metricname ):
[52]1286                       
[54]1287                        if last_update_time <= self.lastStored[ host ][ metricname ]:
[52]1288                                return 1
[40]1289
[54]1290                self.lastStored[ host ][ metricname ] = last_update_time
[52]1291
[33]1292        def storeMetrics( self ):
[63]1293                """
1294                Store all metrics from memory to disk
1295                and do it to the RRD's in appropriate timeperiod directory
1296                """
[33]1297
1298                for hostname, mymetrics in self.myMetrics.items():     
1299
1300                        for metricname, mymetric in mymetrics.items():
1301
[53]1302                                metrics_to_store = [ ]
1303
[63]1304                                # Pop metrics from stack for storing until none is left
1305                                # atomic code: only 1 thread at a time may access myMetrics
1306
[53]1307                                # <ATOMIC>
[50]1308                                #
[47]1309                                self.slot.acquire() 
[33]1310
[54]1311                                while len( self.myMetrics[ hostname ][ metricname ] ) > 0:
[53]1312
[54]1313                                        if len( self.myMetrics[ hostname ][ metricname ] ) > 0:
[53]1314
[176]1315                                                try:
1316                                                        metrics_to_store.append( self.myMetrics[ hostname ][ metricname ].pop( 0 ) )
1317                                                except IndexError, msg:
1318
[179]1319                                                        # Somehow sometimes myMetrics[ hostname ][ metricname ]
1320                                                        # is still len 0 when the statement is executed.
1321                                                        # Just ignore indexerror's..
[176]1322                                                        pass
1323
[53]1324                                self.slot.release()
1325                                #
1326                                # </ATOMIC>
1327
[47]1328                                # Create a mapping table, each metric to the period where it should be stored
1329                                #
[53]1330                                metric_serial_table = self.determineSerials( hostname, metricname, metrics_to_store )
[33]1331
[50]1332                                update_rets = [ ]
1333
[47]1334                                for period, pmetric in metric_serial_table.items():
1335
[146]1336                                        create_ret = self.createCheck( hostname, metricname, period )   
[47]1337
1338                                        update_ret = self.update( hostname, metricname, period, pmetric )
1339
1340                                        if update_ret == 0:
1341
1342                                                debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
1343                                        else:
1344                                                debug_msg( 9, 'metric update failed' )
1345
[146]1346                                        update_rets.append( create_ret )
[50]1347                                        update_rets.append( update_ret )
[47]1348
[179]1349                                # Lets ignore errors here for now, we need to make sure last update time
1350                                # is correct!
1351                                #
1352                                #if not (1) in update_rets:
[50]1353
[179]1354                                self.memLastUpdate( hostname, metricname, metrics_to_store )
[50]1355
[17]1356        def makeTimeSerial( self ):
[63]1357                """Generate a time serial. Seconds since epoch"""
[17]1358
1359                # Seconds since epoch
1360                mytime = int( time.time() )
1361
1362                return mytime
1363
[50]1364        def makeRrdPath( self, host, metricname, timeserial ):
[63]1365                """Make a RRD location/path and filename"""
[17]1366
[50]1367                rrd_dir = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
1368                rrd_file = '%s/%s.rrd' %( rrd_dir, metricname )
[17]1369
1370                return rrd_dir, rrd_file
1371
[20]1372        def getLastRrdTimeSerial( self, host ):
[63]1373                """Find the last timeserial (directory) for this host"""
[17]1374
[19]1375                newest_timeserial = 0
1376
[47]1377                for dir in self.timeserials[ host ]:
[32]1378
[47]1379                        valid_dir = 1
[17]1380
[47]1381                        for letter in dir:
1382                                if letter not in string.digits:
1383                                        valid_dir = 0
[17]1384
[47]1385                        if valid_dir:
1386                                timeserial = dir
1387                                if timeserial > newest_timeserial:
1388                                        newest_timeserial = timeserial
[17]1389
1390                if newest_timeserial:
[18]1391                        return newest_timeserial
[17]1392                else:
1393                        return 0
1394
[47]1395        def determinePeriod( self, host, check_serial ):
[63]1396                """Determine to which period (directory) this time(serial) belongs"""
[47]1397
1398                period_serial = 0
1399
[56]1400                if self.timeserials.has_key( host ):
[47]1401
[56]1402                        for serial in self.timeserials[ host ]:
[47]1403
[56]1404                                if check_serial >= serial and period_serial < serial:
[47]1405
[56]1406                                        period_serial = serial
1407
[47]1408                return period_serial
1409
1410        def determineSerials( self, host, metricname, metriclist ):
1411                """
1412                Determine the correct serial and corresponding rrd to store
1413                for a list of metrics
1414                """
1415
1416                metric_serial_table = { }
1417
1418                for metric in metriclist:
1419
1420                        if metric['name'] == metricname:
1421
1422                                period = self.determinePeriod( host, metric['time'] )   
1423
1424                                archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60)
1425
[49]1426                                if (int( metric['time'] ) - int( period ) ) > archive_secs:
[47]1427
1428                                        # This one should get it's own new period
1429                                        period = metric['time']
[57]1430
1431                                        if not self.timeserials.has_key( host ):
1432                                                self.timeserials[ host ] = [ ]
1433
[50]1434                                        self.timeserials[ host ].append( period )
[47]1435
1436                                if not metric_serial_table.has_key( period ):
1437
[49]1438                                        metric_serial_table[ period ] = [ ]
[47]1439
1440                                metric_serial_table[ period ].append( metric )
1441
1442                return metric_serial_table
1443
[33]1444        def createCheck( self, host, metricname, timeserial ):
[63]1445                """Check if an rrd allready exists for this metric, create if not"""
[9]1446
[35]1447                debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
[47]1448               
[33]1449                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
[17]1450
[9]1451                if not os.path.exists( rrd_dir ):
[58]1452
1453                        try:
1454                                os.makedirs( rrd_dir )
1455
[169]1456                        except os.OSError, msg:
[58]1457
1458                                if msg.find( 'File exists' ) != -1:
1459
1460                                        # Ignore exists errors
1461                                        pass
1462
1463                                else:
1464
1465                                        print msg
1466                                        return
1467
[14]1468                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
[9]1469
[14]1470                if not os.path.exists( rrd_file ):
[9]1471
[33]1472                        interval = self.config.getInterval( self.cluster )
[47]1473                        heartbeat = 8 * int( interval )
[9]1474
[37]1475                        params = [ ]
[12]1476
[37]1477                        params.append( '--step' )
1478                        params.append( str( interval ) )
[12]1479
[37]1480                        params.append( '--start' )
[47]1481                        params.append( str( int( timeserial ) - 1 ) )
[12]1482
[37]1483                        params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat )
1484                        params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) )
[13]1485
[37]1486                        self.rrdm.create( str(rrd_file), params )
1487
[14]1488                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
1489
[47]1490        def update( self, host, metricname, timeserial, metriclist ):
[63]1491                """
1492                Update rrd file for host with metricname
1493                in directory timeserial with metriclist
1494                """
[9]1495
[35]1496                debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
[9]1497
[33]1498                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
[18]1499
[47]1500                update_list = self.makeUpdateList( host, metriclist )
[15]1501
[41]1502                if len( update_list ) > 0:
1503                        ret = self.rrdm.update( str(rrd_file), update_list )
[32]1504
[41]1505                        if ret:
1506                                return 1
[27]1507               
[41]1508                        debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) )
[15]1509
[36]1510                return 0
1511
[169]1512def daemon():
1513        """daemonized threading"""
[8]1514
[169]1515        # Fork the first child
1516        #
1517        pid = os.fork()
1518
1519        if pid > 0:
1520
1521                sys.exit(0)  # end parent
1522
1523        # creates a session and sets the process group ID
1524        #
1525        os.setsid()
1526
1527        # Fork the second child
1528        #
1529        pid = os.fork()
1530
1531        if pid > 0:
1532
1533                sys.exit(0)  # end parent
1534
1535        # Go to the root directory and set the umask
1536        #
1537        os.chdir('/')
1538        os.umask(0)
1539
1540        sys.stdin.close()
1541        sys.stdout.close()
1542        sys.stderr.close()
1543
[273]1544        os.open('/dev/null', os.O_RDWR)
1545        os.dup2(0, 1)
1546        os.dup2(0, 2)
[169]1547
1548        run()
1549
1550def run():
1551        """Threading start"""
1552
[287]1553        myXMLSource             = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] )
[8]1554
[287]1555        myTorqueProcessor       = TorqueXMLProcessor( myXMLSource )
1556        myGangliaProcessor      = GangliaXMLProcessor( myXMLSource )
1557
[169]1558        try:
[102]1559                torque_xml_thread = threading.Thread( None, myTorqueProcessor.run, 'torque_proc_thread' )
1560                ganglia_xml_thread = threading.Thread( None, myGangliaProcessor.run, 'ganglia_proc_thread' )
[22]1561
[169]1562                torque_xml_thread.start()
1563                ganglia_xml_thread.start()
1564               
[176]1565        except thread.error, msg:
[169]1566                debug_msg( 0, 'FATAL ERROR: Unable to start main threads!: '+ str(msg) )
1567                syslog.closelog()
1568                sys.exit(1)
1569               
1570        debug_msg( 0, 'main threading started.' )
[78]1571
[169]1572def main():
1573        """Program startup"""
1574
[214]1575        if not processArgs( sys.argv[1:] ):
1576                sys.exit( 1 )
1577
[169]1578        if( DAEMONIZE and USE_SYSLOG ):
1579                syslog.openlog( 'jobarchived', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
1580
1581        if DAEMONIZE:
1582                daemon()
1583        else:
1584                run()
1585
1586#
[81]1587# Global functions
[169]1588#
[81]1589
[9]1590def check_dir( directory ):
[63]1591        """Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"""
[9]1592
1593        if directory[-1] == '/':
1594                directory = directory[:-1]
1595
1596        return directory
1597
[12]1598def debug_msg( level, msg ):
[169]1599        """Only print msg if correct levels"""
[12]1600
[169]1601        if (not DAEMONIZE and DEBUG_LEVEL >= level):
1602                sys.stderr.write( printTime() + ' - ' + msg + '\n' )
1603       
1604        if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
1605                syslog.syslog( msg )
[12]1606
[46]1607def printTime( ):
[63]1608        """Print current time in human readable format"""
[46]1609
1610        return time.strftime("%a %d %b %Y %H:%M:%S")
1611
[63]1612# Ooohh, someone started me! Let's go..
[9]1613if __name__ == '__main__':
1614        main()
Note: See TracBrowser for help on using the repository browser.