source: trunk/daemon/togad.py @ 38

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

daemon/togad.py:

Code cleanup and config for testing

File size: 15.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 string
8import os
9import os.path
10import time
11import re
12import threading
13import mutex
14import random
15
16# Specify debugging level here;
17#
18# 11 = XML: metrics
19# 10 = XML: host, cluster, grid, ganglia
20# 9  = RRD activity, gmetad config parsing
21# 8  = daemon threading
22#
23DEBUG_LEVEL = 8
24
25# Where is the gmetad.conf located
26#
27GMETAD_CONF = '/etc/gmetad.conf'
28
29# Where to store the archived rrd's
30#
31ARCHIVE_PATH = '/data/toga/rrds'
32
33# List of data_source names to archive for
34#
35ARCHIVE_SOURCES = [ "LISA Cluster" ]
36
37# Amount of hours to store in one single archived .rrd
38#
39ARCHIVE_HOURS_PER_RRD = 1
40
41# Wether or not to run as a daemon in background
42#
43DAEMONIZE = 0
44
45######################
46#                    #
47# Configuration ends #
48#                    #
49######################
50
51# What XML data types not to store
52#
53UNSUPPORTED_ARCHIVE_TYPES = [ 'string' ]
54
55"""
56This is TOrque-GAnglia's data Daemon
57"""
58
59class RRDMutator:
60        "A class for handling .rrd mutations"
61
62        binary = '/usr/bin/rrdtool'
63
64        def __init__( self, binary=None ):
65
66                if binary:
67                        self.binary = binary
68
69        def create( self, filename, args ):
70                return self.perform( 'create' + ' "' + filename + '"', args )
71
72        def update( self, filename, args ):
73                return self.perform( 'update' + ' "' + filename + '"', args )
74
75        def perform( self, action, args ):
76
77                arg_string = None
78
79                for arg in args:
80
81                        if not arg_string:
82
83                                arg_string = arg
84                        else:
85                                arg_string = arg_string + ' ' + arg
86
87                debug_msg( 9, 'rrdm.perform(): ' + self.binary + ' ' + action + ' ' + arg_string  )
88
89                for line in os.popen( self.binary + ' ' + action + ' ' + arg_string ).readlines():
90
91                        if line.find( 'ERROR' ) != -1:
92
93                                error_msg = string.join( line.split( ' ' )[1:] )
94                                debug_msg( 9, error_msg )
95                                return 1
96
97                return 0
98
99class GangliaXMLHandler( ContentHandler ):
100        "Parse Ganglia's XML"
101
102        def __init__( self, config ):
103                self.config = config
104                self.clusters = { }
105
106        def startElement( self, name, attrs ):
107                "Store appropriate data from xml start tags"
108
109                if name == 'GANGLIA_XML':
110
111                        self.XMLSource = attrs.get( 'SOURCE', "" )
112                        self.gangliaVersion = attrs.get( 'VERSION', "" )
113
114                        debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
115
116                elif name == 'GRID':
117
118                        self.gridName = attrs.get( 'NAME', "" )
119                        self.time = attrs.get( 'LOCALTIME', "" )
120
121                        debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
122
123                elif name == 'CLUSTER':
124
125                        self.clusterName = attrs.get( 'NAME', "" )
126                        self.time = attrs.get( 'LOCALTIME', "" )
127
128                        if not self.clusters.has_key( self.clusterName ) and self.clusterName in ARCHIVE_SOURCES:
129
130                                self.clusters[ self.clusterName ] = RRDHandler( self.config, self.clusterName )
131
132                                debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
133
134                elif name == 'HOST' and self.clusterName in ARCHIVE_SOURCES:     
135
136                        self.hostName = attrs.get( 'NAME', "" )
137                        self.hostIp = attrs.get( 'IP', "" )
138                        self.hostReported = attrs.get( 'REPORTED', "" )
139
140                        debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
141
142                elif name == 'METRIC' and self.clusterName in ARCHIVE_SOURCES:
143
144                        type = attrs.get( 'TYPE', "" )
145
146                        if type not in UNSUPPORTED_ARCHIVE_TYPES:
147
148                                myMetric = { }
149                                myMetric['name'] = attrs.get( 'NAME', "" )
150                                myMetric['val'] = attrs.get( 'VAL', "" )
151                                myMetric['time'] = self.hostReported
152
153                                self.clusters[ self.clusterName ].memMetric( self.hostName, myMetric )
154
155                                debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
156
157        def storeMetrics( self ):
158
159                for clustername, rrdh in self.clusters.items():
160
161                        ret = rrdh.storeMetrics()
162
163                        if ret:
164                                debug_msg( 9, 'An error occured while storing metrics for cluster %s' %clustername )
165                                return 1
166
167                return 0
168
169class GangliaXMLGatherer:
170        "Setup a connection and file object to Ganglia's XML"
171
172        s = None
173
174        def __init__( self, host, port ):
175                "Store host and port for connection"
176
177                self.host = host
178                self.port = port
179                self.connect()
180
181        def connect( self ):
182                "Setup connection to XML source"
183
184                for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ):
185
186                        af, socktype, proto, canonname, sa = res
187
188                        try:
189
190                                self.s = socket.socket( af, socktype, proto )
191
192                        except socket.error, msg:
193
194                                self.s = None
195                                continue
196
197                        try:
198
199                                self.s.connect( sa )
200
201                        except socket.error, msg:
202
203                                self.s.close()
204                                self.s = None
205                                continue
206
207                        break
208
209                if self.s is None:
210
211                        debug_msg( 0, 'Could not open socket' )
212                        sys.exit( 1 )
213
214        def disconnect( self ):
215                "Close socket"
216
217                if self.s:
218                        self.s.close()
219                        self.s = None
220
221        def __del__( self ):
222                "Kill the socket before we leave"
223
224                self.disconnect()
225
226        def getFileObject( self ):
227                "Connect, and return a file object"
228
229                if self.s:
230                        # Apearantly, only data is received when a connection is made
231                        # therefor, disconnect and connect
232                        #
233                        self.disconnect()
234                        self.connect()
235
236                return self.s.makefile( 'r' )
237
238class GangliaXMLProcessor:
239
240        def __init__( self ):
241                "Setup initial XML connection and handlers"
242
243                self.config = GangliaConfigParser( GMETAD_CONF )
244
245                self.myXMLGatherer = GangliaXMLGatherer( 'localhost', 8651 ) 
246                self.myParser = make_parser()   
247                self.myHandler = GangliaXMLHandler( self.config )
248                self.myParser.setContentHandler( self.myHandler )
249
250        def daemon( self ):
251                "Run as daemon forever"
252
253                self.DAEMON = 1
254
255                # Fork the first child
256                #
257                pid = os.fork()
258
259                if pid > 0:
260
261                        sys.exit(0)  # end parent
262
263                # creates a session and sets the process group ID
264                #
265                os.setsid()
266
267                # Fork the second child
268                #
269                pid = os.fork()
270
271                if pid > 0:
272
273                        sys.exit(0)  # end parent
274
275                # Go to the root directory and set the umask
276                #
277                os.chdir('/')
278                os.umask(0)
279
280                sys.stdin.close()
281                sys.stdout.close()
282                #sys.stderr.close()
283
284                os.open('/dev/null', 0)
285                os.dup(0)
286                os.dup(0)
287
288                self.run()
289
290        def printTime( self ):
291                "Print current time in human readable format"
292
293                return time.strftime("%a %d %b %Y %H:%M:%S")
294
295        def run( self ):
296                "Main thread"
297
298                xmlthread = threading.Thread( None, self.processXML, 'xmlthread' )
299                storethread = threading.Thread( None, self.storeMetrics, 'storethread' )
300
301                while( 1 ):
302
303                        if not xmlthread.isAlive():
304                                # Gather XML at the same interval as gmetad
305
306                                # threaded call to: self.processXML()
307                                #
308                                xmlthread = threading.Thread( None, self.processXML, 'xmlthread' )
309                                debug_msg( 8, self.printTime() + ' - mainthread() - xmlthread() started' )
310                                xmlthread.start()
311
312                        if not storethread.isAlive():
313                                # Store metrics every .. sec
314
315                                # threaded call to: self.storeMetrics()
316                                #
317                                storethread = threading.Thread( None, self.storeMetrics, 'storethread' )
318                                debug_msg( 8, self.printTime() + ' - mainthread() - storethread() started' )
319                                storethread.start()
320               
321                        # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway
322                        time.sleep( 1 ) 
323
324        def storeMetrics( self ):
325                "Store metrics retained in memory to disk"
326
327                # Store metrics somewhere between every 60 and 180 seconds
328                #
329                STORE_INTERVAL = random.randint( 60, 180 )
330
331                debug_msg( 8, self.printTime() + ' - storethread() - storemetricthread() started: Storing data..' )
332
333                # threaded call to: self.myHandler.storeMetrics()
334                #
335                storethread = threading.Thread( None, self.myHandler.storeMetrics(), 'storemetricthread' )
336                storethread.start()
337
338                debug_msg( 8, self.printTime() + ' - storethread() - Sleeping.. (%ss)' %STORE_INTERVAL )
339                time.sleep( STORE_INTERVAL )
340                debug_msg( 8, self.printTime() + ' - storethread() - Done sleeping.' )
341
342                if storethread.isAlive():
343
344                        debug_msg( 8, self.printTime() + ' - storethread() - storemetricthread() still running, waiting to finish..' )
345                        parsethread.join( 180 ) # Maximum time is 3 minutes for storing thread to finish - more then enough
346
347                debug_msg( 8, self.printTime() + ' - storethread() - storemetricthread() finished.' )
348
349                debug_msg( 8, self.printTime() + ' - storethread() finished' )
350
351                return 0
352
353        def processXML( self ):
354                "Process XML"
355
356                debug_msg( 8, self.printTime() + ' - xmlthread() - parsethread() started: Parsing..' )
357
358                # threaded call to: self.myParser.parse( self.myXMLGatherer.getFileObject() )
359                #
360                parsethread = threading.Thread( None, self.myParser.parse, 'parsethread', [ self.myXMLGatherer.getFileObject() ] )
361                parsethread.start()
362
363                debug_msg( 8, self.printTime() + ' - xmlthread() - Sleeping.. (%ss)' %self.config.getLowestInterval() )
364                time.sleep( float( self.config.getLowestInterval() ) ) 
365                debug_msg( 8, self.printTime() + ' - xmlthread() - Done sleeping.' )
366
367                if parsethread.isAlive():
368
369                        debug_msg( 8, self.printTime() + ' - xmlthread() - parsethread() still running, waiting to finish..' )
370                        parsethread.join( 180 ) # Maximum time is 3 minutes for XML thread to finish - more then enough
371
372                debug_msg( 8, self.printTime() + ' - xmlthread() - parsethread() finished.' )
373
374                debug_msg( 8, self.printTime() + ' - xmlthread() finished.' )
375
376                return 0
377
378class GangliaConfigParser:
379
380        sources = [ ]
381
382        def __init__( self, config ):
383
384                self.config = config
385                self.parseValues()
386
387        def parseValues( self ):
388                "Parse certain values from gmetad.conf"
389
390                readcfg = open( self.config, 'r' )
391
392                for line in readcfg.readlines():
393
394                        if line.count( '"' ) > 1:
395
396                                if line.find( 'data_source' ) != -1 and line[0] != '#':
397
398                                        source = { }
399                                        source['name'] = line.split( '"' )[1]
400                                        source_words = line.split( '"' )[2].split( ' ' )
401
402                                        for word in source_words:
403
404                                                valid_interval = 1
405
406                                                for letter in word:
407
408                                                        if letter not in string.digits:
409
410                                                                valid_interval = 0
411
412                                                if valid_interval and len(word) > 0:
413
414                                                        source['interval'] = word
415                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
416       
417                                        # No interval found, use Ganglia's default     
418                                        if not source.has_key( 'interval' ):
419                                                source['interval'] = 15
420                                                debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
421
422                                        self.sources.append( source )
423
424        def getInterval( self, source_name ):
425
426                for source in self.sources:
427
428                        if source['name'] == source_name:
429
430                                return source['interval']
431
432                return None
433
434        def getLowestInterval( self ):
435
436                lowest_interval = 0
437
438                for source in self.sources:
439
440                        if not lowest_interval or source['interval'] <= lowest_interval:
441
442                                lowest_interval = source['interval']
443
444                # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays
445                if lowest_interval:
446                        return lowest_interval
447                else:
448                        return 15
449
450class RRDHandler:
451
452        myMetrics = { }
453        slot = None
454
455        def __init__( self, config, cluster ):
456                self.cluster = cluster
457                self.config = config
458                self.slot = mutex.mutex()
459                self.rrdm = RRDMutator()
460
461        def getClusterName( self ):
462                return self.cluster
463
464        def memMetric( self, host, metric ):
465
466                if self.myMetrics.has_key( host ):
467
468                        if self.myMetrics[ host ].has_key( metric['name'] ):
469
470                                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
471
472                                        if mymetric['time'] == metric['time']:
473
474                                                # Allready have this metric, abort
475                                                return 1
476                        else:
477                                self.myMetrics[ host ][ metric['name'] ] = [ ]
478                else:
479                        self.myMetrics[ host ] = { }
480                        self.myMetrics[ host ][ metric['name'] ] = [ ]
481
482                self.slot.testandset()
483                self.myMetrics[ host ][ metric['name'] ].append( metric )
484                self.slot.unlock()
485
486        def makeUpdateList( self, host, metricname ):
487
488                update_list = [ ]
489
490                for metric in self.myMetrics[ host ][ metricname ]:
491
492                        update_list.append( '%s:%s' %( metric['time'], metric['val'] ) )
493
494                return update_list
495
496        def storeMetrics( self ):
497
498                for hostname, mymetrics in self.myMetrics.items():     
499
500                        for metricname, mymetric in mymetrics.items():
501
502                                mytime = self.makeTimeSerial()
503                                self.createCheck( hostname, metricname, mytime )       
504                                update_ret = self.update( hostname, metricname, mytime )
505
506                                if update_ret == 0:
507
508                                        self.slot.testandset()
509                                        del self.myMetrics[ hostname ][ metricname ]
510                                        self.slot.unlock()
511                                        debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
512                                else:
513                                        debug_msg( 9, 'metric update failed' )
514                                        return 1
515
516        def makeTimeSerial( self ):
517                "Generate a time serial. Seconds since epoch"
518
519                # Seconds since epoch
520                mytime = int( time.time() )
521
522                return mytime
523
524        def makeRrdPath( self, host, metricname=None, timeserial=None ):
525                """
526                Make a RRD location/path and filename
527                If a metric or timeserial are supplied the complete locations
528                will be made, else just the host directory
529                """
530
531                if not timeserial:     
532                        rrd_dir = '%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host )
533                else:
534                        rrd_dir = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
535                if metricname:
536                        rrd_file = '%s/%s.rrd' %( rrd_dir, metricname )
537                else:
538                        rrd_file = None
539
540                return rrd_dir, rrd_file
541
542        def getLastRrdTimeSerial( self, host ):
543                """
544                Find the last timeserial (directory) for this host
545                This is determined once every host
546                """
547
548                rrd_dir, rrd_file = self.makeRrdPath( host )
549
550                newest_timeserial = 0
551
552                if os.path.exists( rrd_dir ):
553
554                        for root, dirs, files in os.walk( rrd_dir ):
555
556                                for dir in dirs:
557
558                                        valid_dir = 1
559
560                                        for letter in dir:
561                                                if letter not in string.digits:
562                                                        valid_dir = 0
563
564                                        if valid_dir:
565                                                timeserial = dir
566                                                if timeserial > newest_timeserial:
567                                                        newest_timeserial = timeserial
568
569                if newest_timeserial:
570                        return newest_timeserial
571                else:
572                        return 0
573
574        def checkNewRrdPeriod( self, host, current_timeserial ):
575                """
576                Check if current timeserial belongs to recent time period
577                or should become a new period (and file).
578
579                Returns the serial of the correct time period
580                """
581
582                last_timeserial = int( self.getLastRrdTimeSerial( host ) )
583                debug_msg( 9, 'last timeserial of %s is %s' %( host, last_timeserial ) )
584
585                if not last_timeserial:
586                        serial = current_timeserial
587                else:
588
589                        archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60)
590
591                        if (current_timeserial - last_timeserial) >= archive_secs:
592                                serial = current_timeserial
593                        else:
594                                serial = last_timeserial
595
596                return serial
597
598        def getFirstTime( self, host, metricname ):
599                "Get the first time of a metric we know of"
600
601                first_time = 0
602
603                for metric in self.myMetrics[ host ][ metricname ]:
604
605                        if not first_time or metric['time'] <= first_time:
606
607                                first_time = metric['time']
608
609                return first_time
610
611        def createCheck( self, host, metricname, timeserial ):
612                "Check if an .rrd allready exists for this metric, create if not"
613
614                debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
615
616                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
617
618                if not os.path.exists( rrd_dir ):
619                        os.makedirs( rrd_dir )
620                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
621
622                if not os.path.exists( rrd_file ):
623
624                        interval = self.config.getInterval( self.cluster )
625                        heartbeat = 8 * int(interval)
626
627                        params = [ ]
628
629                        params.append( '--step' )
630                        params.append( str( interval ) )
631
632                        params.append( '--start' )
633                        params.append( str( int( self.getFirstTime( host, metricname ) ) - 1 ) )
634
635                        params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat )
636                        params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) )
637
638                        self.rrdm.create( str(rrd_file), params )
639
640                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
641
642        def update( self, host, metricname, timeserial ):
643
644                debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
645
646                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
647
648                update_list = self.makeUpdateList( host, metricname )
649
650                ret = self.rrdm.update( str(rrd_file), update_list )
651
652                if ret:
653                        return 1
654               
655                debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) )
656
657                return 0
658
659def main():
660        "Program startup"
661
662        myProcessor = GangliaXMLProcessor()
663
664        if DAEMONIZE:
665                myProcessor.daemon()
666        else:
667                myProcessor.run()
668
669def check_dir( directory ):
670        "Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"
671
672        if directory[-1] == '/':
673                directory = directory[:-1]
674
675        return directory
676
677def debug_msg( level, msg ):
678
679        if (DEBUG_LEVEL >= level):
680                sys.stderr.write( msg + '\n' )
681
682# Let's go
683if __name__ == '__main__':
684        main()
Note: See TracBrowser for help on using the repository browser.