source: trunk/daemon/togad.py @ 33

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

daemon/togad.py:

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