source: trunk/daemon/togad.py @ 30

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

daemon/togad.py:

Changed debugging levels/messages

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