source: trunk/daemon/togad.py @ 34

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

daemon/togad.py:

  • Numerous bugfixes Data is still not written, storeMetrics doesn't run
File size: 13.7 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 = 10
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.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                if not self.s:
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                # Daemonized not working yet
284                if DAEMONIZE:
285                        pid = os.fork()
286
287                        # Handle XML grabbing in Child
288                        if pid == 0:
289
290                                while( 1 ):
291                                        self.grabXML()
292
293                        # Do scheduled RRD storing in Parent
294                        #elif pid > ):
295
296                else:
297                        self.grabXML()
298                        self.storeMetrics()
299
300        def storeMetrics( self ):
301                "Store metrics retained in memory to disk"
302
303                self.myHandler.storeMetrics()
304
305        def processXML( self ):
306                "Process XML"
307
308                self.myParser.parse( self.myXMLGatherer.getFileObject() )
309
310class GangliaConfigParser:
311
312        sources = [ ]
313
314        def __init__( self, config ):
315
316                self.config = config
317                self.parseValues()
318
319        def parseValues( self ):
320                "Parse certain values from gmetad.conf"
321
322                readcfg = open( self.config, 'r' )
323
324                for line in readcfg.readlines():
325
326                        if line.count( '"' ) > 1:
327
328                                if line.find( 'data_source' ) != -1 and line[0] != '#':
329
330                                        source = { }
331                                        source['name'] = line.split( '"' )[1]
332                                        source_words = line.split( '"' )[2].split( ' ' )
333
334                                        for word in source_words:
335
336                                                valid_interval = 1
337
338                                                for letter in word:
339
340                                                        if letter not in string.digits:
341
342                                                                valid_interval = 0
343
344                                                if valid_interval and len(word) > 0:
345
346                                                        source['interval'] = word
347                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
348       
349                                        # No interval found, use Ganglia's default     
350                                        if not source.has_key( 'interval' ):
351                                                source['interval'] = 15
352                                                debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
353
354                                        self.sources.append( source )
355
356        def getInterval( self, source_name ):
357
358                for source in self.sources:
359
360                        if source['name'] == source_name:
361
362                                return source['interval']
363
364                return None
365
366        def getLowestInterval( self ):
367
368                lowest_interval = 0
369
370                for source in self.sources:
371
372                        if not lowest_interval or source['interval'] <= lowest_interval:
373
374                                lowest_interval = source['interval']
375
376                # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays
377                if lowest_interval:
378                        return lowest_interval
379                else:
380                        return 15
381
382class RRDHandler:
383
384        myMetrics = { }
385
386        def __init__( self, config, cluster ):
387                self.cluster = cluster
388                self.config = config
389
390        def getClusterName( self ):
391                return self.cluster
392
393        def memMetric( self, host, metric ):
394
395                if self.myMetrics.has_key( host ):
396
397                        if self.myMetrics[ host ].has_key( metric['name'] ):
398
399                                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
400
401                                        if mymetric['time'] == metric['time']:
402
403                                                # Allready have this metric, abort
404                                                return 1
405                        else:
406                                self.myMetrics[ host ][ metric['name'] ] = [ ]
407                else:
408                        self.myMetrics[ host ] = { }
409                        self.myMetrics[ host ][ metric['name'] ] = [ ]
410
411
412                self.myMetrics[ host ][ metric['name'] ].append( metric )
413
414        def makeUpdateString( self, host, metric ):
415
416                update_string = ''
417
418                for m in self.myMetrics[ host ][ metric['name'] ]:
419
420                        update_string = update_string + ' %s:%s' %( metric['time'], metric['val'] )
421
422                return update_string
423
424        def storeMetrics( self ):
425
426                for hostname, mymetrics in self.myMetrics.items():     
427
428                        for metricname, mymetric in mymetrics.items():
429
430                                self.rrd.createCheck( hostname, metricname, timeserial )       
431                                update_okay = self.rrd.update( hostname, metricname, timeserial )
432
433                                if not update_okay:
434
435                                        del self.myMetrics[ hostname ][ metricname ]
436                                        debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
437                                else:
438                                        debug_msg( 9, 'metric update failed' )
439
440                                sys.exit(1)
441
442        def makeTimeSerial( self ):
443                "Generate a time serial. Seconds since epoch"
444
445                # Seconds since epoch
446                mytime = int( time.time() )
447
448                return mytime
449
450        def makeRrdPath( self, host, metricname=None, timeserial=None ):
451                """
452                Make a RRD location/path and filename
453                If a metric or timeserial are supplied the complete locations
454                will be made, else just the host directory
455                """
456
457                if not timeserial:     
458                        rrd_dir = '%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host )
459                else:
460                        rrd_dir = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
461                if metric:
462                        rrd_file = '%s/%s.rrd' %( rrd_dir, metricname )
463                else:
464                        rrd_file = None
465
466                return rrd_dir, rrd_file
467
468        def getLastRrdTimeSerial( self, host ):
469                """
470                Find the last timeserial (directory) for this host
471                This is determined once every host
472                """
473
474                rrd_dir, rrd_file = self.makeRrdPath( host )
475
476                newest_timeserial = 0
477
478                if os.path.exists( rrd_dir ):
479
480                        for root, dirs, files in os.walk( rrd_dir ):
481
482                                for dir in dirs:
483
484                                        valid_dir = 1
485
486                                        for letter in dir:
487                                                if letter not in string.digits:
488                                                        valid_dir = 0
489
490                                        if valid_dir:
491                                                timeserial = dir
492                                                if timeserial > newest_timeserial:
493                                                        newest_timeserial = timeserial
494
495                if newest_timeserial:
496                        return newest_timeserial
497                else:
498                        return 0
499
500        def checkNewRrdPeriod( self, host, current_timeserial ):
501                """
502                Check if current timeserial belongs to recent time period
503                or should become a new period (and file).
504
505                Returns the serial of the correct time period
506                """
507
508                last_timeserial = int( self.getLastRrdTimeSerial( host ) )
509                debug_msg( 9, 'last timeserial of %s is %s' %( host, last_timeserial ) )
510
511                if not last_timeserial:
512                        serial = current_timeserial
513                else:
514
515                        archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60)
516
517                        if (current_timeserial - last_timeserial) >= archive_secs:
518                                serial = current_timeserial
519                        else:
520                                serial = last_timeserial
521
522                return serial
523
524        def getFirstTime( self, host, metricname ):
525                "Get the first time of a metric we know of"
526
527                first_time = 0
528
529                for metric in self.myMetrics[ host ][ metricname ]:
530
531                        if not first_time or metric['time'] <= first_time:
532
533                                first_time = metric['time']
534
535        def createCheck( self, host, metricname, timeserial ):
536                "Check if an .rrd allready exists for this metric, create if not"
537
538                debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metric['name'] ) )
539
540                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
541
542                if not os.path.exists( rrd_dir ):
543                        os.makedirs( rrd_dir )
544                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
545
546                if not os.path.exists( rrd_file ):
547
548                        interval = self.config.getInterval( self.cluster )
549                        heartbeat = 8 * int(interval)
550
551                        param_step1 = '--step'
552                        param_step2 = str( interval )
553
554                        param_start1 = '--start'
555                        param_start2 = str( int( self.getFirstTime( host, metricname ) ) - 1 )
556
557                        param_ds = 'DS:sum:GAUGE:%d:U:U' %heartbeat
558                        param_rra = 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240)
559
560                        rrdtool.create( str(rrd_file), param_step1, param_step2, param_start1, param_start2, param_ds, param_rra )
561
562                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
563
564        def update( self, host, metricname, timeserial ):
565
566                debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metric['name'] ) )
567
568                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
569
570                #timestamp = metric['time']
571                #val = metric['val']
572
573                #update_string = '%s:%s' %(timestamp, val)
574                update_string = self.makeUpdateString( host, metricname )
575
576                try:
577
578                        rrdtool.update( str(rrd_file), str(update_string) )
579
580                except rrdtool.error, detail:
581
582                        debug_msg( 0, 'EXCEPTION! While trying to update rrd:' )
583                        debug_msg( 0, '\trrd %s with %s' %( str(rrd_file), update_string ) )
584                        debug_msg( 0, str(detail) )
585
586                        return 1
587               
588                debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), update_string ) )
589
590def main():
591        "Program startup"
592
593        myProcessor = GangliaXMLProcessor()
594
595        if DAEMONIZE:
596                myProcessor.daemon()
597        else:
598                myProcessor.run()
599
600def check_dir( directory ):
601        "Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"
602
603        if directory[-1] == '/':
604                directory = directory[:-1]
605
606        return directory
607
608def debug_msg( level, msg ):
609
610        if (DEBUG_LEVEL >= level):
611                sys.stderr.write( msg + '\n' )
612
613# Let's go
614if __name__ == '__main__':
615        main()
Note: See TracBrowser for help on using the repository browser.