source: trunk/daemon/togad.py @ 36

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

daemon/togad.py:

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