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
Line 
1#!/usr/bin/env python
2
3from xml.sax import make_parser
4from xml.sax.handler import ContentHandler
5import socket
6import sys
7import rrdtool
8import string
9import os
10import os.path
11import time
12import re
13
14# Specify debugging level here;
15#
16# >10 = metric XML
17# >9  = host,cluster,grid,ganglia XML
18# >8  = RRD activity,gmetad config parsing
19#
20DEBUG_LEVEL = 8
21
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
34# Amount of hours to store in one single archived .rrd
35#
36ARCHIVE_HOURS_PER_RRD = 24
37
38######################
39#                    #
40# Configuration ends #
41#                    #
42######################
43
44# What XML data types not to store
45#
46UNSUPPORTED_ARCHIVE_TYPES = [ 'string' ]
47
48"""
49This is TOrque-GAnglia's data Daemon
50"""
51
52class GangliaXMLHandler( ContentHandler ):
53        "Parse Ganglia's XML"
54
55        metrics = [ ]
56
57        def startElement( self, name, attrs ):
58                "Store appropriate data from xml start tags"
59
60                if name == 'GANGLIA_XML':
61                        self.XMLSource = attrs.get('SOURCE',"")
62                        self.gangliaVersion = attrs.get('VERSION',"")
63                        debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
64
65                elif name == 'GRID':
66                        self.gridName = attrs.get('NAME',"")
67                        self.time = attrs.get('LOCALTIME',"")
68                        debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
69
70                elif name == 'CLUSTER':
71                        self.clusterName = attrs.get('NAME',"")
72                        self.time = attrs.get('LOCALTIME',"")
73                        self.rrd = RRDHandler( self.clusterName )
74                        debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
75
76                elif name == 'HOST' and self.clusterName in ARCHIVE_SOURCES:     
77                        self.hostName = attrs.get('NAME',"")
78                        self.hostIp = attrs.get('IP',"")
79                        self.hostReported = attrs.get('REPORTED',"")
80                        # Reset the metrics list for each host
81                        self.metrics = [ ]
82                        debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
83
84                elif name == 'METRIC' and self.clusterName in ARCHIVE_SOURCES:
85                        myMetric = { }
86                        myMetric['name'] = attrs.get('NAME',"")
87                        myMetric['val'] = attrs.get('VAL',"")
88                        myMetric['time'] = self.time
89                        myMetric['type'] = attrs.get('TYPE',"")
90
91                        self.metrics.append( myMetric ) 
92                        debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
93
94                return
95
96        def endElement( self, name ):
97                #if name == 'GANGLIA_XML':
98
99                #if name == 'GRID':
100
101                #if name == 'CLUSTER':
102
103                if name == 'HOST' and self.clusterName in ARCHIVE_SOURCES:     
104
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
110                #if name == 'METRIC':
111
112        def storeMetrics( self, hostname, timeserial ):
113
114                for metric in self.metrics:
115                        if metric['type'] not in UNSUPPORTED_ARCHIVE_TYPES:
116
117                                self.rrd.createCheck( hostname, metric, timeserial )   
118                                self.rrd.update( hostname, metric, timeserial )
119                                debug_msg( 9, 'stored metric %s for %s: %s' %( hostname, metric['name'], metric['val'] ) )
120                                sys.exit(1)
121       
122
123class GangliaXMLGatherer:
124        "Setup a connection and file object to Ganglia's XML"
125
126        s = None
127
128        def __init__( self, host, port ):
129                "Store host and port for connection"
130
131                self.host = host
132                self.port = port
133
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 ):
143                        af, socktype, proto, canonname, sa = res
144                        try:
145                                self.s = socket.socket( af, socktype, proto )
146                        except socket.error, msg:
147                                self.s = None
148                                continue
149                        try:
150                                self.s.connect( sa )
151                        except socket.error, msg:
152                                self.s.close()
153                                self.s = None
154                                continue
155                        break
156
157                if self.s is None:
158                        print 'Could not open socket'
159                        sys.exit(1)
160
161                return self.s.makefile( 'r' )
162
163class GangliaXMLProcessor:
164
165        def daemon( self ):
166                "Run as daemon forever"
167
168                self.DAEMON = 1
169
170                # Fork the first child
171                #
172                pid = os.fork()
173                if pid > 0:
174                        sys.exit(0)  # end parrent
175
176                # creates a session and sets the process group ID
177                #
178                os.setsid()
179
180                # Fork the second child
181                #
182                pid = os.fork()
183                if pid > 0:
184                        sys.exit(0)  # end parrent
185
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()
193                if (DEBUGLEVEL == 0):
194                        sys.stderr.close()
195
196                os.open('/dev/null', 0)
197                os.dup(0)
198                os.dup(0)
199
200                self.run()
201
202        def run( self ):
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
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
237                                if line.find( 'data_source' ) != -1 and line[0] != '#':
238
239                                        source = { }
240                                        source['name'] = line.split( '"' )[1]
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
251                                                if valid_interval and len(word) > 0:
252                                                        source['interval'] = word
253                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
254               
255                # No interval found, use Ganglia's default     
256                if not source.has_key( 'interval' ):
257                        source['interval'] = 15
258                        debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
259
260                self.sources.append( source )
261
262        def getInterval( self, source_name ):
263                for source in self.sources:
264                        if source['name'] == source_name:
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
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 )
287                rrd_file = '%s/%s.%s.rrd' %( rrd_dir, metric['name'], timeserial )
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
302                                        myre = re.match( '(\S+?).(\d+).rrd', file )
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:
316                        return newest_timeserial
317                else:
318                        return 0
319
320        def checkNewRrdPeriod( self, host, metric, current_timeserial ):
321
322                last_timeserial = int( self.getLastRrdTimeSerial( host, metric ) )
323                debug_msg( 8, 'last timeserial on %s of %s is %s' %( metric['name'], host, last_timeserial ) )
324
325                if not last_timeserial:
326                        serial = current_timeserial
327                else:
328
329                        archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60)
330
331                        if (current_timeserial - last_timeserial) >= archive_secs:
332                                serial = current_timeserial
333                        else:
334                                serial = last_timeserial
335
336                return serial
337
338        def createCheck( self, host, metric, current_timeserial ):
339                "Check if an .rrd allready exists for this metric, create if not"
340
341                timeserial = self.checkNewRrdPeriod( host, metric, current_timeserial )
342                debug_msg( 8, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metric['name'] ) )
343
344                rrd_dir, rrd_file = self.makeRrdPath( host, metric, timeserial )
345
346                if not os.path.exists( rrd_dir ):
347                        os.makedirs( rrd_dir )
348                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
349
350                if not os.path.exists( rrd_file ):
351
352                        interval = self.gmetad_conf.getInterval( self.cluster )
353                        heartbeat = 8 * int(interval)
354
355                        param_step1 = '--step'
356                        param_step2 = str( interval )
357
358                        param_start1 = '--start'
359                        param_start2 = str( int( metric['time'] ) - 1 )
360
361                        param_ds = 'DS:sum:GAUGE:%d:U:U' %heartbeat
362                        param_rra = 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240)
363
364                        rrdtool.create( str(rrd_file), param_step1, param_step2, param_start1, param_start2, param_ds, param_rra )
365
366                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
367
368        def update( self, host, metric, current_timeserial ):
369
370                timeserial = self.checkNewRrdPeriod( host, metric, current_timeserial )
371                debug_msg( 8, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metric['name'] ) )
372
373                rrd_dir, rrd_file = self.makeRrdPath( host, metric, timeserial )
374
375                timestamp = metric['time']
376                val = metric['val']
377
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
383def main():
384        "Program startup"
385
386        myProcessor = GangliaXMLProcessor()
387        myProcessor.processXML()
388
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
397def debug_msg( level, msg ):
398
399        if (DEBUG_LEVEL >= level):
400                sys.stderr.write( msg + '\n' )
401
402# Let's go
403if __name__ == '__main__':
404        main()
Note: See TracBrowser for help on using the repository browser.