source: trunk/daemon/togad.py @ 18

Last change on this file since 18 was 18, checked in by bastiaans, 19 years ago

daemon/togad.py:

  • Changed timestamp'ing style to: disk_free.1111580431.rrd
  • Rewrote some timestamp handling
  • RRD updating now updates the RRD with the correct timestamp
File size: 9.5 KB
RevLine 
[3]1#!/usr/bin/env python
2
[5]3from xml.sax import make_parser
4from xml.sax.handler import ContentHandler
5import socket
6import sys
[9]7import rrdtool
8import string
[12]9import os
10import os.path
[17]11import time
12import re
[3]13
[8]14# Specify debugging level here;
15#
16# >10 = metric XML
17# >9  = host,cluster,grid,ganglia XML
[9]18# >8  = RRD activity,gmetad config parsing
[8]19#
[16]20DEBUG_LEVEL = 8
[6]21
[9]22# Where is the gmetad.conf located
23#
24GMETAD_CONF = '/etc/gmetad.conf'
25
26# Where to store the archived rrd's
27#
28ARCHIVE_PATH = '/data/toga/rrds'
29
30# List of data_source names to archive for
31#
32ARCHIVE_SOURCES = [ "LISA Cluster" ]
33
[13]34# Amount of hours to store in one single archived .rrd
[9]35#
[13]36ARCHIVE_HOURS_PER_RRD = 24
37
[17]38######################
39#                    #
40# Configuration ends #
41#                    #
42######################
[13]43
[17]44# What XML data types not to store
[13]45#
[17]46UNSUPPORTED_ARCHIVE_TYPES = [ 'string' ]
[9]47
[8]48"""
49This is TOrque-GAnglia's data Daemon
50"""
51
[6]52class GangliaXMLHandler( ContentHandler ):
[8]53        "Parse Ganglia's XML"
[3]54
[6]55        metrics = [ ]
56
57        def startElement( self, name, attrs ):
[8]58                "Store appropriate data from xml start tags"
[3]59
[7]60                if name == 'GANGLIA_XML':
61                        self.XMLSource = attrs.get('SOURCE',"")
62                        self.gangliaVersion = attrs.get('VERSION',"")
[12]63                        debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
[6]64
[7]65                elif name == 'GRID':
66                        self.gridName = attrs.get('NAME',"")
[12]67                        self.time = attrs.get('LOCALTIME',"")
68                        debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
[6]69
[7]70                elif name == 'CLUSTER':
71                        self.clusterName = attrs.get('NAME',"")
[12]72                        self.time = attrs.get('LOCALTIME',"")
[9]73                        self.rrd = RRDHandler( self.clusterName )
[12]74                        debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
[6]75
[14]76                elif name == 'HOST' and self.clusterName in ARCHIVE_SOURCES:     
[7]77                        self.hostName = attrs.get('NAME',"")
78                        self.hostIp = attrs.get('IP',"")
79                        self.hostReported = attrs.get('REPORTED',"")
[9]80                        # Reset the metrics list for each host
81                        self.metrics = [ ]
[12]82                        debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
[6]83
[14]84                elif name == 'METRIC' and self.clusterName in ARCHIVE_SOURCES:
[6]85                        myMetric = { }
[7]86                        myMetric['name'] = attrs.get('NAME',"")
87                        myMetric['val'] = attrs.get('VAL',"")
[12]88                        myMetric['time'] = self.time
[16]89                        myMetric['type'] = attrs.get('TYPE',"")
[6]90
91                        self.metrics.append( myMetric ) 
[12]92                        debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
[6]93
[5]94                return
[3]95
[9]96        def endElement( self, name ):
[12]97                #if name == 'GANGLIA_XML':
[3]98
[12]99                #if name == 'GRID':
[3]100
[12]101                #if name == 'CLUSTER':
[6]102
[14]103                if name == 'HOST' and self.clusterName in ARCHIVE_SOURCES:     
[6]104
[18]105                        # Determine time here, so all use same time in this run
106                        mytime = self.rrd.makeTimeSerial()
107
108                        self.storeMetrics( self.hostName, mytime )
109
[12]110                #if name == 'METRIC':
[6]111
[18]112        def storeMetrics( self, hostname, timeserial ):
[9]113
114                for metric in self.metrics:
[17]115                        if metric['type'] not in UNSUPPORTED_ARCHIVE_TYPES:
[16]116
[18]117                                self.rrd.createCheck( hostname, metric, timeserial )   
118                                self.rrd.update( hostname, metric, timeserial )
[16]119                                debug_msg( 9, 'stored metric %s for %s: %s' %( hostname, metric['name'], metric['val'] ) )
[17]120                                sys.exit(1)
[9]121       
122
[5]123class GangliaXMLGatherer:
[8]124        "Setup a connection and file object to Ganglia's XML"
[3]125
[8]126        s = None
127
128        def __init__( self, host, port ):
129                "Store host and port for connection"
130
[5]131                self.host = host
132                self.port = port
[3]133
[8]134        def __del__( self ):
135                "Kill the socket before we leave"
136
137                self.s.close()
138
139        def getFileObject( self ):
140                "Connect, and return a file object"
141
142                for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ):
[5]143                        af, socktype, proto, canonname, sa = res
144                        try:
[8]145                                self.s = socket.socket( af, socktype, proto )
[5]146                        except socket.error, msg:
[8]147                                self.s = None
[5]148                                continue
149                        try:
[8]150                                self.s.connect( sa )
[5]151                        except socket.error, msg:
[8]152                                self.s.close()
153                                self.s = None
[5]154                                continue
155                        break
[3]156
[8]157                if self.s is None:
158                        print 'Could not open socket'
[5]159                        sys.exit(1)
160
[8]161                return self.s.makefile( 'r' )
[5]162
[8]163class GangliaXMLProcessor:
[5]164
[9]165        def daemon( self ):
[8]166                "Run as daemon forever"
[5]167
[8]168                self.DAEMON = 1
[5]169
[8]170                # Fork the first child
171                #
172                pid = os.fork()
173                if pid > 0:
174                        sys.exit(0)  # end parrent
[7]175
[8]176                # creates a session and sets the process group ID
177                #
178                os.setsid()
[7]179
[8]180                # Fork the second child
181                #
182                pid = os.fork()
183                if pid > 0:
184                        sys.exit(0)  # end parrent
[5]185
[8]186                # Go to the root directory and set the umask
187                #
188                os.chdir('/')
189                os.umask(0)
190
191                sys.stdin.close()
192                sys.stdout.close()
[12]193                if (DEBUGLEVEL == 0):
194                        sys.stderr.close()
[8]195
196                os.open('/dev/null', 0)
197                os.dup(0)
198                os.dup(0)
199
200                self.run()
201
[9]202        def run( self ):
[8]203                "Main thread"
204
205                while ( 1 ):
206                        self.processXML()
207                        time.sleep( 5 )
208
209        def processXML( self ):
210                "Process XML"
211
212                myXMLGatherer = GangliaXMLGatherer( 'localhost', 8651 ) 
213
214                myParser = make_parser()   
215                myHandler = GangliaXMLHandler()
216                myParser.setContentHandler( myHandler )
217
218                myParser.parse( myXMLGatherer.getFileObject() )
219
[9]220class GangliaConfigParser:
221
222        sources = [ ]
223
224        def __init__( self, config ):
225                self.config = config
226                self.parseValues()
227
228        def parseValues(self):
229                "Parse certain values from gmetad.conf"
230
231                readcfg = open( self.config, 'r' )
232
233                for line in readcfg.readlines():
234
235                        if line.count( '"' ) > 1:
236
[10]237                                if line.find( 'data_source' ) != -1 and line[0] != '#':
[9]238
[11]239                                        source = { }
240                                        source['name'] = line.split( '"' )[1]
[9]241                                        source_words = line.split( '"' )[2].split( ' ' )
242
243                                        for word in source_words:
244
245                                                valid_interval = 1
246
247                                                for letter in word:
248                                                        if letter not in string.digits:
249                                                                valid_interval = 0
250
[10]251                                                if valid_interval and len(word) > 0:
[9]252                                                        source['interval'] = word
[12]253                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
[9]254               
255                # No interval found, use Ganglia's default     
256                if not source.has_key( 'interval' ):
257                        source['interval'] = 15
[12]258                        debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
[9]259
260                self.sources.append( source )
261
262        def getInterval( self, source_name ):
263                for source in self.sources:
[12]264                        if source['name'] == source_name:
[9]265                                return source['interval']
266                return None
267
268class RRDHandler:
269
270        def __init__( self, cluster ):
271                self.cluster = cluster
272                self.gmetad_conf = GangliaConfigParser( GMETAD_CONF )
273
[17]274        def makeTimeSerial( self ):
275
276                # YYYYMMDDhhmmss: 20050321143411
277                #mytime = time.strftime( "%Y%m%d%H%M%S" )
278
279                # Seconds since epoch
280                mytime = int( time.time() )
281
282                return mytime
283
284        def makeRrdPath( self, host, metric, timeserial='notime' ):
285
286                rrd_dir = '%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host )
[18]287                rrd_file = '%s/%s.%s.rrd' %( rrd_dir, metric['name'], timeserial )
[17]288
289                return rrd_dir, rrd_file
290
291        def getLastRrdTimeSerial( self, host, metric ):
292
293                rrd_dir, rrd_file = self.makeRrdPath( host, metric )
294
295                if os.path.exists( rrd_dir ):
296                        for root, dirs, files in os.walk( rrd_dir ):
297
298                                newest_timeserial = 0
299
300                                for file in files:
301
[18]302                                        myre = re.match( '(\S+?).(\d+).rrd', file )
[17]303
304                                        if not myre:
305                                                continue
306
307                                        mymetric = myre.group(1)
308
309                                        if mymetric == metric['name']:
310
311                                                timeserial = myre.group(2)
312                                                if timeserial > newest_timeserial:
313                                                        newest_timeserial = timeserial
314
315                if newest_timeserial:
[18]316                        return newest_timeserial
[17]317                else:
318                        return 0
319
[18]320        def checkNewRrdPeriod( self, host, metric, current_timeserial ):
[17]321
322                last_timeserial = int( self.getLastRrdTimeSerial( host, metric ) )
[18]323                debug_msg( 8, 'last timeserial on %s of %s is %s' %( metric['name'], host, last_timeserial ) )
[17]324
325                if not last_timeserial:
[18]326                        serial = current_timeserial
327                else:
[17]328
[18]329                        archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60)
[17]330
[18]331                        if (current_timeserial - last_timeserial) >= archive_secs:
332                                serial = current_timeserial
333                        else:
334                                serial = last_timeserial
[17]335
[18]336                return serial
337
338        def createCheck( self, host, metric, current_timeserial ):
[9]339                "Check if an .rrd allready exists for this metric, create if not"
340
[18]341                timeserial = self.checkNewRrdPeriod( host, metric, current_timeserial )
342                debug_msg( 8, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metric['name'] ) )
[9]343
[17]344                rrd_dir, rrd_file = self.makeRrdPath( host, metric, timeserial )
345
[9]346                if not os.path.exists( rrd_dir ):
347                        os.makedirs( rrd_dir )
[14]348                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
[9]349
[14]350                if not os.path.exists( rrd_file ):
[9]351
[14]352                        interval = self.gmetad_conf.getInterval( self.cluster )
353                        heartbeat = 8 * int(interval)
[9]354
[14]355                        param_step1 = '--step'
356                        param_step2 = str( interval )
[12]357
[14]358                        param_start1 = '--start'
359                        param_start2 = str( int( metric['time'] ) - 1 )
[12]360
[14]361                        param_ds = 'DS:sum:GAUGE:%d:U:U' %heartbeat
362                        param_rra = 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240)
[12]363
[14]364                        rrdtool.create( str(rrd_file), param_step1, param_step2, param_start1, param_start2, param_ds, param_rra )
[13]365
[14]366                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
367
[18]368        def update( self, host, metric, current_timeserial ):
[9]369
[18]370                timeserial = self.checkNewRrdPeriod( host, metric, current_timeserial )
371                debug_msg( 8, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metric['name'] ) )
[9]372
[18]373                rrd_dir, rrd_file = self.makeRrdPath( host, metric, timeserial )
374
[15]375                timestamp = metric['time']
376                val = metric['val']
[9]377
[15]378                update_string = '%s:%s' %(timestamp, val)
379
380                rrdtool.update( str(rrd_file), str(update_string) )
381                debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), update_string ) )
382
[8]383def main():
384        "Program startup"
385
386        myProcessor = GangliaXMLProcessor()
387        myProcessor.processXML()
388
[9]389def check_dir( directory ):
390        "Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"
391
392        if directory[-1] == '/':
393                directory = directory[:-1]
394
395        return directory
396
[12]397def debug_msg( level, msg ):
398
399        if (DEBUG_LEVEL >= level):
400                sys.stderr.write( msg + '\n' )
401
[5]402# Let's go
[9]403if __name__ == '__main__':
404        main()
Note: See TracBrowser for help on using the repository browser.