source: trunk/daemon/togad.py @ 33

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

daemon/togad.py:

  • Rewrote classes to be reusable
  • Seperated storing from gathering
  • Setup RRD creation/updating to use in-memory metrics
File size: 13.1 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 - NOTE: Daemon will 'halt on all errors' from this level
21#
22DEBUG_LEVEL = 9
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# Wether or not to run as a daemon in background
41#
42DAEMONIZE = 0
43
44######################
45#                    #
46# Configuration ends #
47#                    #
48######################
49
50# What XML data types not to store
51#
52UNSUPPORTED_ARCHIVE_TYPES = [ 'string' ]
53
54"""
55This is TOrque-GAnglia's data Daemon
56"""
57
58class GangliaXMLHandler( ContentHandler ):
59        "Parse Ganglia's XML"
60
61        clusters = { }
62        config = None
63
64        def __init__( self, config ):
65                self.config = config
66
67        def startElement( self, name, attrs ):
68                "Store appropriate data from xml start tags"
69
70                if name == 'GANGLIA_XML':
71
72                        self.XMLSource = attrs.get( 'SOURCE', "" )
73                        self.gangliaVersion = attrs.get( 'VERSION', "" )
74
75                        debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
76
77                elif name == 'GRID':
78
79                        self.gridName = attrs.get( 'NAME', "" )
80                        self.time = attrs.get( 'LOCALTIME', "" )
81
82                        debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
83
84                elif name == 'CLUSTER':
85
86                        self.clusterName = attrs.get( 'NAME', "" )
87                        self.time = attrs.get( 'LOCALTIME', "" )
88
89                        if not self.clusters.has_key( self.clusterName ):
90
91                                self.clusters[ self.clusterName ] = RRDHandler( self.clusterName )
92
93                        debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
94
95                elif name == 'HOST' and self.clusterName in ARCHIVE_SOURCES:     
96
97                        self.hostName = attrs.get( 'NAME', "" )
98                        self.hostIp = attrs.get( 'IP', "" )
99                        self.hostReported = attrs.get( 'REPORTED', "" )
100
101                        debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
102
103                elif name == 'METRIC' and self.clusterName in ARCHIVE_SOURCES:
104
105                        type = attrs.get( 'TYPE', "" )
106
107                        if type not in UNSUPPORTED_ARCHIVE_TYPES:
108
109                                myMetric = { }
110                                myMetric['name'] = attrs.get( 'NAME', "" )
111                                myMetric['val'] = attrs.get( 'VAL', "" )
112                                myMetric['time'] = self.hostReported
113
114                                self.clusters[ self.clusterName ].memMetric( self.hostname, myMetric )
115
116                        debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
117
118        def storeMetrics( self, hostname, timeserial ):
119
120                for cluster in self.clusters:
121
122                        cluster.storeMetrics()
123
124class GangliaXMLGatherer:
125        "Setup a connection and file object to Ganglia's XML"
126
127        s = None
128
129        def __init__( self, host, port ):
130                "Store host and port for connection"
131
132                self.host = host
133                self.port = port
134                self.connect()
135
136        def connect( self ):
137                "Setup connection to XML source"
138
139                for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ):
140
141                        af, socktype, proto, canonname, sa = res
142
143                        try:
144
145                                self.s = socket.socket( af, socktype, proto )
146
147                        except socket.error, msg:
148
149                                self.s = None
150                                continue
151
152                        try:
153
154                                self.s.connect( sa )
155
156                        except socket.error, msg:
157
158                                self.s.close()
159                                self.s = None
160                                continue
161
162                        break
163
164                if self.s is None:
165
166                        debug_msg( 0, 'Could not open socket' )
167                        sys.exit( 1 )
168
169        def disconnect( self ):
170                "Close socket"
171
172                if self.s:
173                        self.s.close()
174                        self.s = None
175
176        def __del__( self ):
177                "Kill the socket before we leave"
178
179                self.disconnect()
180
181        def getFileObject( self ):
182                "Connect, and return a file object"
183
184                if not self.s:
185                        self.connect()
186
187                return self.s.makefile( 'r' )
188
189class GangliaXMLProcessor:
190
191        def __init__( self ):
192                "Setup initial XML connection and handlers"
193
194                self.config = GangliaConfigParser( GMETAD_CONF )
195
196                self.myXMLGatherer = GangliaXMLGatherer( 'localhost', 8651 ) 
197                self.myParser = make_parser()   
198                self.myHandler = GangliaXMLHandler( self.config )
199                self.myParser.setContentHandler( self.myHandler )
200
201        def daemon( self ):
202                "Run as daemon forever"
203
204                self.DAEMON = 1
205
206                # Fork the first child
207                #
208                pid = os.fork()
209
210                if pid > 0:
211
212                        sys.exit(0)  # end parent
213
214                # creates a session and sets the process group ID
215                #
216                os.setsid()
217
218                # Fork the second child
219                #
220                pid = os.fork()
221
222                if pid > 0:
223
224                        sys.exit(0)  # end parent
225
226                # Go to the root directory and set the umask
227                #
228                os.chdir('/')
229                os.umask(0)
230
231                sys.stdin.close()
232                sys.stdout.close()
233                sys.stderr.close()
234
235                os.open('/dev/null', 0)
236                os.dup(0)
237                os.dup(0)
238
239                self.run()
240
241        def printTime( self ):
242                "Print current time in human readable format"
243
244                return time.strftime("%a %d %b %Y %H:%M:%S")
245
246        def grabXML( self ):
247
248                debug_msg( 7, self.printTime() + ' - mainthread() - xmlthread() started' )
249                pid = os.fork()
250
251                if pid == 0:
252                        # Child - XML Thread
253                        #
254                        # Process XML and exit
255
256                        debug_msg( 7, self.printTime() + ' - xmlthread()  - Start XML processing..' )
257                        self.processXML()
258                        debug_msg( 7, self.printTime() + ' - xmlthread()  - Done processing; exiting.' )
259                        sys.exit( 0 )
260
261                elif pid > 0:
262                        # Parent - Time/sleep Thread
263                        #
264                        # Make sure XML is processed on time and at regular intervals
265
266                        debug_msg( 7, self.printTime() + ' - mainthread() - Sleep '+ str( self.config.getInterval() ) +'s: zzzzz..' )
267                        time.sleep( self.config.getInterval() )
268                        debug_msg( 7, self.printTime() + ' - mainthread() - Awoken: waiting for XML thread..' )
269
270                        r = os.wait()
271                        ret = r[1]
272                        if ret != 0:
273                                debug_msg( 7, self.printTime() + ' - mainthread() - Done waiting: ERROR! xmlthread() exited with status %d' %(ret) )
274                                if DEBUG_LEVEL>=7: sys.exit( 1 )
275                        else:
276
277                                debug_msg( 7, self.printTime() + ' - mainthread() - Done waiting: xmlthread() finished succesfully' )
278
279        def run( self ):
280                "Main thread"
281
282                # Daemonized not working yet
283                if DAEMONIZE:
284                        pid = os.fork()
285
286                        # Handle XML grabbing in Child
287                        if pid == 0:
288
289                                while( 1 ):
290                                        self.grabXML()
291
292                        # Do scheduled RRD storing in Parent
293                        #elif pid > ):
294
295                else:
296                        self.grabXML()
297                        self.storeMetrics()
298
299        def storeMetrics( self ):
300                "Store metrics retained in memory to disk"
301
302                self.myHandler.storeMetrics()
303
304        def processXML( self ):
305                "Process XML"
306
307                self.myParser.parse( self.myXMLGatherer.getFileObject() )
308
309class GangliaConfigParser:
310
311        sources = { }
312
313        def __init__( self, config ):
314
315                self.config = config
316                self.parseValues()
317
318        def parseValues( self ):
319                "Parse certain values from gmetad.conf"
320
321                readcfg = open( self.config, 'r' )
322
323                for line in readcfg.readlines():
324
325                        if line.count( '"' ) > 1:
326
327                                if line.find( 'data_source' ) != -1 and line[0] != '#':
328
329                                        source = { }
330                                        source['name'] = line.split( '"' )[1]
331                                        source_words = line.split( '"' )[2].split( ' ' )
332
333                                        for word in source_words:
334
335                                                valid_interval = 1
336
337                                                for letter in word:
338
339                                                        if letter not in string.digits:
340
341                                                                valid_interval = 0
342
343                                                if valid_interval and len(word) > 0:
344
345                                                        source['interval'] = word
346                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
347       
348                                        # No interval found, use Ganglia's default     
349                                        if not source.has_key( 'interval' ):
350                                                source['interval'] = 15
351                                                debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
352
353                                        self.sources.append( source )
354
355        def getInterval( self, source_name ):
356
357                for source in self.sources:
358
359                        if source['name'] == source_name:
360
361                                return source['interval']
362
363                return None
364
365class RRDHandler:
366
367        myMetrics = { }
368
369        def __init__( self, config, cluster ):
370                self.cluster = cluster
371                self.config = config
372
373        def getClusterName( self ):
374                return self.cluster
375
376        def memMetric( self, host, metric ):
377
378                for m in self.myMetrics[ host ]:
379
380                        if m['time'] == metric['time']:
381
382                                # Allready have this metric, abort
383                                return 1
384
385                if not self.myMetrics.has_key( host ):
386
387                        self.myMetrics[ host ] = { }
388
389                if not self.myMetrics[ host ].has_key( metric['name'] ):
390
391                        self.myMetrics[ host ][ metric['name'] ] = [ ]
392
393                self.myMetrics[ host ][ metric['name'] ].append( metric )
394
395        def makeUpdateString( self, host, metric ):
396
397                update_string = ''
398
399                for m in self.myMetrics[ host ][ metric['name'] ]:
400
401                        update_string = update_string + ' %s:%s' %( metric['time'], metric['val'] )
402
403                return update_string
404
405        def storeMetrics( self ):
406
407                for hostname, mymetrics in self.myMetrics.items():     
408
409                        for metricname, mymetric in mymetrics.items():
410
411                                self.rrd.createCheck( hostname, metricname, timeserial )       
412                                update_okay = self.rrd.update( hostname, metricname, timeserial )
413
414                                if not update_okay:
415
416                                        del self.myMetrics[ hostname ][ metricname ]
417                                        debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
418                                else:
419                                        debug_msg( 9, 'metric update failed' )
420
421                                sys.exit(1)
422
423        def makeTimeSerial( self ):
424                "Generate a time serial. Seconds since epoch"
425
426                # Seconds since epoch
427                mytime = int( time.time() )
428
429                return mytime
430
431        def makeRrdPath( self, host, metricname=None, timeserial=None ):
432                """
433                Make a RRD location/path and filename
434                If a metric or timeserial are supplied the complete locations
435                will be made, else just the host directory
436                """
437
438                if not timeserial:     
439                        rrd_dir = '%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host )
440                else:
441                        rrd_dir = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
442                if metric:
443                        rrd_file = '%s/%s.rrd' %( rrd_dir, metricname )
444                else:
445                        rrd_file = None
446
447                return rrd_dir, rrd_file
448
449        def getLastRrdTimeSerial( self, host ):
450                """
451                Find the last timeserial (directory) for this host
452                This is determined once every host
453                """
454
455                rrd_dir, rrd_file = self.makeRrdPath( host )
456
457                newest_timeserial = 0
458
459                if os.path.exists( rrd_dir ):
460
461                        for root, dirs, files in os.walk( rrd_dir ):
462
463                                for dir in dirs:
464
465                                        valid_dir = 1
466
467                                        for letter in dir:
468                                                if letter not in string.digits:
469                                                        valid_dir = 0
470
471                                        if valid_dir:
472                                                timeserial = dir
473                                                if timeserial > newest_timeserial:
474                                                        newest_timeserial = timeserial
475
476                if newest_timeserial:
477                        return newest_timeserial
478                else:
479                        return 0
480
481        def checkNewRrdPeriod( self, host, current_timeserial ):
482                """
483                Check if current timeserial belongs to recent time period
484                or should become a new period (and file).
485
486                Returns the serial of the correct time period
487                """
488
489                last_timeserial = int( self.getLastRrdTimeSerial( host ) )
490                debug_msg( 9, 'last timeserial of %s is %s' %( host, last_timeserial ) )
491
492                if not last_timeserial:
493                        serial = current_timeserial
494                else:
495
496                        archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60)
497
498                        if (current_timeserial - last_timeserial) >= archive_secs:
499                                serial = current_timeserial
500                        else:
501                                serial = last_timeserial
502
503                return serial
504
505        def getFirstTime( self, host, metricname ):
506                "Get the first time of a metric we know of"
507
508                first_time = 0
509
510                for metric in self.myMetrics[ host ][ metricname ]:
511
512                        if not first_time or metric['time'] <= first_time:
513
514                                first_time = metric['time']
515
516        def createCheck( self, host, metricname, timeserial ):
517                "Check if an .rrd allready exists for this metric, create if not"
518
519                debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metric['name'] ) )
520
521                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
522
523                if not os.path.exists( rrd_dir ):
524                        os.makedirs( rrd_dir )
525                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
526
527                if not os.path.exists( rrd_file ):
528
529                        interval = self.config.getInterval( self.cluster )
530                        heartbeat = 8 * int(interval)
531
532                        param_step1 = '--step'
533                        param_step2 = str( interval )
534
535                        param_start1 = '--start'
536                        param_start2 = str( int( self.getFirstTime( host, metricname ) ) - 1 )
537
538                        param_ds = 'DS:sum:GAUGE:%d:U:U' %heartbeat
539                        param_rra = 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240)
540
541                        rrdtool.create( str(rrd_file), param_step1, param_step2, param_start1, param_start2, param_ds, param_rra )
542
543                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
544
545        def update( self, host, metricname, timeserial ):
546
547                debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metric['name'] ) )
548
549                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
550
551                #timestamp = metric['time']
552                #val = metric['val']
553
554                #update_string = '%s:%s' %(timestamp, val)
555                update_string = self.makeUpdateString( host, metricname )
556
557                try:
558
559                        rrdtool.update( str(rrd_file), str(update_string) )
560
561                except rrdtool.error, detail:
562
563                        debug_msg( 0, 'EXCEPTION! While trying to update rrd:' )
564                        debug_msg( 0, '\trrd %s with %s' %( str(rrd_file), update_string ) )
565                        debug_msg( 0, str(detail) )
566
567                        return 1
568               
569                debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), update_string ) )
570
571def main():
572        "Program startup"
573
574        myProcessor = GangliaXMLProcessor()
575
576        if DAEMONIZE:
577                myProcessor.daemon()
578        else:
579                myProcessor.run()
580
581def check_dir( directory ):
582        "Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"
583
584        if directory[-1] == '/':
585                directory = directory[:-1]
586
587        return directory
588
589def debug_msg( level, msg ):
590
591        if (DEBUG_LEVEL >= level):
592                sys.stderr.write( msg + '\n' )
593
594# Let's go
595if __name__ == '__main__':
596        main()
Note: See TracBrowser for help on using the repository browser.