source: trunk/daemon/togad.py @ 39

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

daemon/togad.py:

Changed threading debug msg'es to be more understandable

File size: 16.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 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                                xmlthread.start()
310
311                        if not storethread.isAlive():
312                                # Store metrics every .. sec
313
314                                # threaded call to: self.storeMetrics()
315                                #
316                                storethread = threading.Thread( None, self.storeMetrics, 'storethread' )
317                                storethread.start()
318               
319                        # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway
320                        time.sleep( 1 ) 
321
322        def storeMetrics( self ):
323                "Store metrics retained in memory to disk"
324
325                debug_msg( 8, self.printTime() + ' - storethread(): started.' )
326
327                # Store metrics somewhere between every 60 and 180 seconds
328                #
329                STORE_INTERVAL = random.randint( 60, 180 )
330
331                storethread = threading.Thread( None, self.storeThread, 'storemetricthread' )
332                storethread.start()
333
334                debug_msg( 8, self.printTime() + ' - storethread(): Sleeping.. (%ss)' %STORE_INTERVAL )
335                time.sleep( STORE_INTERVAL )
336                debug_msg( 8, self.printTime() + ' - storethread(): Done sleeping.' )
337
338                if storethread.isAlive():
339
340                        debug_msg( 8, self.printTime() + ' - storethread(): storemetricthread() still running, waiting to finish..' )
341                        parsethread.join( 180 ) # Maximum time is for storing thread to finish
342                        debug_msg( 8, self.printTime() + ' - storethread(): Done waiting.' )
343
344                debug_msg( 8, self.printTime() + ' - storethread(): finished.' )
345
346                return 0
347
348        def storeThread( self ):
349
350                debug_msg( 8, self.printTime() + ' - storemetricthread(): started.' )
351                debug_msg( 8, self.printTime() + ' - storemetricthread(): Storing data..' )
352                ret = self.myHandler.storeMetrics()
353                debug_msg( 8, self.printTime() + ' - storemetricthread(): Done storing.' )
354                debug_msg( 8, self.printTime() + ' - storemetricthread(): finished.' )
355               
356                return ret
357
358        def processXML( self ):
359                "Process XML"
360
361                debug_msg( 8, self.printTime() + ' - xmlthread(): started.' )
362
363                parsethread = threading.Thread( None, self.parseThread, 'parsethread' )
364                parsethread.start()
365
366                debug_msg( 8, self.printTime() + ' - xmlthread(): Sleeping.. (%ss)' %self.config.getLowestInterval() )
367                time.sleep( float( self.config.getLowestInterval() ) ) 
368                debug_msg( 8, self.printTime() + ' - xmlthread(): Done sleeping.' )
369
370                if parsethread.isAlive():
371
372                        debug_msg( 8, self.printTime() + ' - xmlthread(): parsethread() still running, waiting to finish..' )
373                        parsethread.join( 60 ) # Maximum time for XML thread to finish
374                        debug_msg( 8, self.printTime() + ' - xmlthread(): Done waiting.' )
375
376                debug_msg( 8, self.printTime() + ' - xmlthread(): finished.' )
377
378                return 0
379
380        def parseThread( self ):
381
382                debug_msg( 8, self.printTime() + ' - parsethread(): started.' )
383                debug_msg( 8, self.printTime() + ' - parsethread(): Parsing XML..' )
384                ret = self.myParser.parse( self.myXMLGatherer.getFileObject() )
385                debug_msg( 8, self.printTime() + ' - parsethread(): Done parsing.' )
386                debug_msg( 8, self.printTime() + ' - parsethread(): finished.' )
387
388                return ret
389
390class GangliaConfigParser:
391
392        sources = [ ]
393
394        def __init__( self, config ):
395
396                self.config = config
397                self.parseValues()
398
399        def parseValues( self ):
400                "Parse certain values from gmetad.conf"
401
402                readcfg = open( self.config, 'r' )
403
404                for line in readcfg.readlines():
405
406                        if line.count( '"' ) > 1:
407
408                                if line.find( 'data_source' ) != -1 and line[0] != '#':
409
410                                        source = { }
411                                        source['name'] = line.split( '"' )[1]
412                                        source_words = line.split( '"' )[2].split( ' ' )
413
414                                        for word in source_words:
415
416                                                valid_interval = 1
417
418                                                for letter in word:
419
420                                                        if letter not in string.digits:
421
422                                                                valid_interval = 0
423
424                                                if valid_interval and len(word) > 0:
425
426                                                        source['interval'] = word
427                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
428       
429                                        # No interval found, use Ganglia's default     
430                                        if not source.has_key( 'interval' ):
431                                                source['interval'] = 15
432                                                debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
433
434                                        self.sources.append( source )
435
436        def getInterval( self, source_name ):
437
438                for source in self.sources:
439
440                        if source['name'] == source_name:
441
442                                return source['interval']
443
444                return None
445
446        def getLowestInterval( self ):
447
448                lowest_interval = 0
449
450                for source in self.sources:
451
452                        if not lowest_interval or source['interval'] <= lowest_interval:
453
454                                lowest_interval = source['interval']
455
456                # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays
457                if lowest_interval:
458                        return lowest_interval
459                else:
460                        return 15
461
462class RRDHandler:
463
464        myMetrics = { }
465        slot = None
466
467        def __init__( self, config, cluster ):
468                self.cluster = cluster
469                self.config = config
470                self.slot = mutex.mutex()
471                self.rrdm = RRDMutator()
472
473        def getClusterName( self ):
474                return self.cluster
475
476        def memMetric( self, host, metric ):
477
478                if self.myMetrics.has_key( host ):
479
480                        if self.myMetrics[ host ].has_key( metric['name'] ):
481
482                                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
483
484                                        if mymetric['time'] == metric['time']:
485
486                                                # Allready have this metric, abort
487                                                return 1
488                        else:
489                                self.myMetrics[ host ][ metric['name'] ] = [ ]
490                else:
491                        self.myMetrics[ host ] = { }
492                        self.myMetrics[ host ][ metric['name'] ] = [ ]
493
494                self.slot.testandset()
495                self.myMetrics[ host ][ metric['name'] ].append( metric )
496                self.slot.unlock()
497
498        def makeUpdateList( self, host, metricname ):
499
500                update_list = [ ]
501
502                for metric in self.myMetrics[ host ][ metricname ]:
503
504                        update_list.append( '%s:%s' %( metric['time'], metric['val'] ) )
505
506                return update_list
507
508        def storeMetrics( self ):
509
510                for hostname, mymetrics in self.myMetrics.items():     
511
512                        for metricname, mymetric in mymetrics.items():
513
514                                mytime = self.makeTimeSerial()
515                                self.createCheck( hostname, metricname, mytime )       
516                                update_ret = self.update( hostname, metricname, mytime )
517
518                                if update_ret == 0:
519
520                                        self.slot.testandset()
521                                        del self.myMetrics[ hostname ][ metricname ]
522                                        self.slot.unlock()
523                                        debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
524                                else:
525                                        debug_msg( 9, 'metric update failed' )
526                                        return 1
527
528        def makeTimeSerial( self ):
529                "Generate a time serial. Seconds since epoch"
530
531                # Seconds since epoch
532                mytime = int( time.time() )
533
534                return mytime
535
536        def makeRrdPath( self, host, metricname=None, timeserial=None ):
537                """
538                Make a RRD location/path and filename
539                If a metric or timeserial are supplied the complete locations
540                will be made, else just the host directory
541                """
542
543                if not timeserial:     
544                        rrd_dir = '%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host )
545                else:
546                        rrd_dir = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
547                if metricname:
548                        rrd_file = '%s/%s.rrd' %( rrd_dir, metricname )
549                else:
550                        rrd_file = None
551
552                return rrd_dir, rrd_file
553
554        def getLastRrdTimeSerial( self, host ):
555                """
556                Find the last timeserial (directory) for this host
557                This is determined once every host
558                """
559
560                rrd_dir, rrd_file = self.makeRrdPath( host )
561
562                newest_timeserial = 0
563
564                if os.path.exists( rrd_dir ):
565
566                        for root, dirs, files in os.walk( rrd_dir ):
567
568                                for dir in dirs:
569
570                                        valid_dir = 1
571
572                                        for letter in dir:
573                                                if letter not in string.digits:
574                                                        valid_dir = 0
575
576                                        if valid_dir:
577                                                timeserial = dir
578                                                if timeserial > newest_timeserial:
579                                                        newest_timeserial = timeserial
580
581                if newest_timeserial:
582                        return newest_timeserial
583                else:
584                        return 0
585
586        def checkNewRrdPeriod( self, host, current_timeserial ):
587                """
588                Check if current timeserial belongs to recent time period
589                or should become a new period (and file).
590
591                Returns the serial of the correct time period
592                """
593
594                last_timeserial = int( self.getLastRrdTimeSerial( host ) )
595                debug_msg( 9, 'last timeserial of %s is %s' %( host, last_timeserial ) )
596
597                if not last_timeserial:
598                        serial = current_timeserial
599                else:
600
601                        archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60)
602
603                        if (current_timeserial - last_timeserial) >= archive_secs:
604                                serial = current_timeserial
605                        else:
606                                serial = last_timeserial
607
608                return serial
609
610        def getFirstTime( self, host, metricname ):
611                "Get the first time of a metric we know of"
612
613                first_time = 0
614
615                for metric in self.myMetrics[ host ][ metricname ]:
616
617                        if not first_time or metric['time'] <= first_time:
618
619                                first_time = metric['time']
620
621                return first_time
622
623        def createCheck( self, host, metricname, timeserial ):
624                "Check if an .rrd allready exists for this metric, create if not"
625
626                debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
627
628                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
629
630                if not os.path.exists( rrd_dir ):
631                        os.makedirs( rrd_dir )
632                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
633
634                if not os.path.exists( rrd_file ):
635
636                        interval = self.config.getInterval( self.cluster )
637                        heartbeat = 8 * int(interval)
638
639                        params = [ ]
640
641                        params.append( '--step' )
642                        params.append( str( interval ) )
643
644                        params.append( '--start' )
645                        params.append( str( int( self.getFirstTime( host, metricname ) ) - 1 ) )
646
647                        params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat )
648                        params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) )
649
650                        self.rrdm.create( str(rrd_file), params )
651
652                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
653
654        def update( self, host, metricname, timeserial ):
655
656                debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
657
658                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
659
660                update_list = self.makeUpdateList( host, metricname )
661
662                ret = self.rrdm.update( str(rrd_file), update_list )
663
664                if ret:
665                        return 1
666               
667                debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) )
668
669                return 0
670
671def main():
672        "Program startup"
673
674        myProcessor = GangliaXMLProcessor()
675
676        if DAEMONIZE:
677                myProcessor.daemon()
678        else:
679                myProcessor.run()
680
681def check_dir( directory ):
682        "Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"
683
684        if directory[-1] == '/':
685                directory = directory[:-1]
686
687        return directory
688
689def debug_msg( level, msg ):
690
691        if (DEBUG_LEVEL >= level):
692                sys.stderr.write( msg + '\n' )
693
694# Let's go
695if __name__ == '__main__':
696        main()
Note: See TracBrowser for help on using the repository browser.