source: trunk/jobarchived/jobarchived.py @ 285

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

jobarchived/jobarchived.py:

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