source: trunk/daemon/togad.py @ 50

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

daemon/togad.py:

Well it seems to be working now.

  • Code cleanup
  • Split checkStoreMetric into 2 functions, mem and check
  • Will now remember last update only when all entries for a file have been processed (read: after each rrd.update
File size: 19.7 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 string
[12]8import os
9import os.path
[17]10import time
11import re
[36]12import threading
13import mutex
[38]14import random
[40]15from types import *
[3]16
[8]17# Specify debugging level here;
18#
[38]19# 11 = XML: metrics
20# 10 = XML: host, cluster, grid, ganglia
21# 9  = RRD activity, gmetad config parsing
[40]22# 8  = RRD file activity
23# 7  = daemon threading
[8]24#
[50]25DEBUG_LEVEL = 7
[6]26
[9]27# Where is the gmetad.conf located
28#
29GMETAD_CONF = '/etc/gmetad.conf'
30
31# Where to store the archived rrd's
32#
33ARCHIVE_PATH = '/data/toga/rrds'
34
35# List of data_source names to archive for
36#
37ARCHIVE_SOURCES = [ "LISA Cluster" ]
38
[13]39# Amount of hours to store in one single archived .rrd
[9]40#
[43]41ARCHIVE_HOURS_PER_RRD = 12
[13]42
[22]43# Wether or not to run as a daemon in background
44#
45DAEMONIZE = 0
46
[17]47######################
48#                    #
49# Configuration ends #
50#                    #
51######################
[13]52
[17]53# What XML data types not to store
[13]54#
[17]55UNSUPPORTED_ARCHIVE_TYPES = [ 'string' ]
[9]56
[47]57# Maximum time (in seconds) a parsethread may run
58#
59PARSE_TIMEOUT = 60
60
61# Maximum time (in seconds) a storethread may run
62#
63STORE_TIMEOUT = 360
64
[8]65"""
66This is TOrque-GAnglia's data Daemon
67"""
68
[37]69class RRDMutator:
[38]70        "A class for handling .rrd mutations"
[37]71
72        binary = '/usr/bin/rrdtool'
73
74        def __init__( self, binary=None ):
75
76                if binary:
77                        self.binary = binary
78
79        def create( self, filename, args ):
[40]80                return self.perform( 'create', '"' + filename + '"', args )
[37]81
82        def update( self, filename, args ):
[40]83                return self.perform( 'update', '"' + filename + '"', args )
[37]84
[42]85        def grabLastUpdate( self, filename ):
86
87                last_update = 0
88
89                for line in os.popen( self.binary + ' info "' + filename + '"' ).readlines():
90
91                        if line.find( 'last_update') != -1:
92
93                                last_update = line.split( ' = ' )[1]
94
95                if last_update:
96                        return last_update
97                else:
98                        return 0
99
[40]100        def perform( self, action, filename, args ):
[37]101
102                arg_string = None
103
[40]104                if type( args ) is not ListType:
105                        debug_msg( 8, 'Arguments needs to be of type List' )
106                        return 1
107
[37]108                for arg in args:
109
110                        if not arg_string:
111
112                                arg_string = arg
113                        else:
114                                arg_string = arg_string + ' ' + arg
115
[40]116                debug_msg( 8, 'rrdm.perform(): ' + self.binary + ' ' + action + ' ' + filename + ' ' + arg_string  )
[37]117
[40]118                for line in os.popen( self.binary + ' ' + action + ' ' + filename + ' ' + arg_string ).readlines():
[37]119
120                        if line.find( 'ERROR' ) != -1:
121
122                                error_msg = string.join( line.split( ' ' )[1:] )
[40]123                                debug_msg( 8, error_msg )
[37]124                                return 1
125
126                return 0
127
[6]128class GangliaXMLHandler( ContentHandler ):
[8]129        "Parse Ganglia's XML"
[3]130
[33]131        def __init__( self, config ):
132                self.config = config
[35]133                self.clusters = { }
[48]134                debug_msg( 0, printTime() + ' Checking existing toga rrd archive..' )
[44]135                self.gatherClusters()
[48]136                debug_msg( 0, printTime() + ' Check done.' )
[33]137
[44]138        def gatherClusters( self ):
139
[45]140                archive_dir = check_dir(ARCHIVE_PATH)
[44]141
142                hosts = [ ]
143
144                if os.path.exists( archive_dir ):
145
146                        dirlist = os.listdir( archive_dir )
147
148                        for item in dirlist:
149
150                                clustername = item
151
152                                if not self.clusters.has_key( clustername ) and clustername in ARCHIVE_SOURCES:
153
154                                        self.clusters[ clustername ] = RRDHandler( self.config, clustername )
155
[6]156        def startElement( self, name, attrs ):
[8]157                "Store appropriate data from xml start tags"
[3]158
[7]159                if name == 'GANGLIA_XML':
[32]160
161                        self.XMLSource = attrs.get( 'SOURCE', "" )
162                        self.gangliaVersion = attrs.get( 'VERSION', "" )
163
[12]164                        debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
[6]165
[7]166                elif name == 'GRID':
[32]167
168                        self.gridName = attrs.get( 'NAME', "" )
169                        self.time = attrs.get( 'LOCALTIME', "" )
170
[12]171                        debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
[6]172
[7]173                elif name == 'CLUSTER':
[32]174
175                        self.clusterName = attrs.get( 'NAME', "" )
176                        self.time = attrs.get( 'LOCALTIME', "" )
177
[35]178                        if not self.clusters.has_key( self.clusterName ) and self.clusterName in ARCHIVE_SOURCES:
[32]179
[34]180                                self.clusters[ self.clusterName ] = RRDHandler( self.config, self.clusterName )
[33]181
[35]182                                debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
[6]183
[14]184                elif name == 'HOST' and self.clusterName in ARCHIVE_SOURCES:     
[32]185
186                        self.hostName = attrs.get( 'NAME', "" )
187                        self.hostIp = attrs.get( 'IP', "" )
188                        self.hostReported = attrs.get( 'REPORTED', "" )
189
[12]190                        debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
[6]191
[14]192                elif name == 'METRIC' and self.clusterName in ARCHIVE_SOURCES:
[6]193
[32]194                        type = attrs.get( 'TYPE', "" )
[6]195
[32]196                        if type not in UNSUPPORTED_ARCHIVE_TYPES:
[3]197
[32]198                                myMetric = { }
199                                myMetric['name'] = attrs.get( 'NAME', "" )
200                                myMetric['val'] = attrs.get( 'VAL', "" )
201                                myMetric['time'] = self.hostReported
[3]202
[34]203                                self.clusters[ self.clusterName ].memMetric( self.hostName, myMetric )
[3]204
[34]205                                debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
[6]206
[34]207        def storeMetrics( self ):
[9]208
[34]209                for clustername, rrdh in self.clusters.items():
[16]210
[38]211                        ret = rrdh.storeMetrics()
[9]212
[38]213                        if ret:
214                                debug_msg( 9, 'An error occured while storing metrics for cluster %s' %clustername )
215                                return 1
216
217                return 0
218
[5]219class GangliaXMLGatherer:
[8]220        "Setup a connection and file object to Ganglia's XML"
[3]221
[8]222        s = None
223
224        def __init__( self, host, port ):
225                "Store host and port for connection"
226
[5]227                self.host = host
228                self.port = port
[33]229                self.connect()
[3]230
[33]231        def connect( self ):
232                "Setup connection to XML source"
[8]233
234                for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ):
[32]235
[5]236                        af, socktype, proto, canonname, sa = res
[32]237
[5]238                        try:
[32]239
[8]240                                self.s = socket.socket( af, socktype, proto )
[32]241
[5]242                        except socket.error, msg:
[32]243
[8]244                                self.s = None
[5]245                                continue
[32]246
[5]247                        try:
[32]248
[8]249                                self.s.connect( sa )
[32]250
[5]251                        except socket.error, msg:
[32]252
[8]253                                self.s.close()
254                                self.s = None
[5]255                                continue
[32]256
[5]257                        break
[3]258
[8]259                if self.s is None:
[32]260
[33]261                        debug_msg( 0, 'Could not open socket' )
262                        sys.exit( 1 )
[5]263
[33]264        def disconnect( self ):
265                "Close socket"
266
267                if self.s:
268                        self.s.close()
269                        self.s = None
270
271        def __del__( self ):
272                "Kill the socket before we leave"
273
274                self.disconnect()
275
276        def getFileObject( self ):
277                "Connect, and return a file object"
278
[38]279                if self.s:
280                        # Apearantly, only data is received when a connection is made
281                        # therefor, disconnect and connect
282                        #
283                        self.disconnect()
284                        self.connect()
[33]285
[8]286                return self.s.makefile( 'r' )
[5]287
[8]288class GangliaXMLProcessor:
[5]289
[33]290        def __init__( self ):
291                "Setup initial XML connection and handlers"
292
293                self.config = GangliaConfigParser( GMETAD_CONF )
294
295                self.myXMLGatherer = GangliaXMLGatherer( 'localhost', 8651 ) 
296                self.myParser = make_parser()   
297                self.myHandler = GangliaXMLHandler( self.config )
298                self.myParser.setContentHandler( self.myHandler )
299
[9]300        def daemon( self ):
[8]301                "Run as daemon forever"
[5]302
[8]303                self.DAEMON = 1
[5]304
[8]305                # Fork the first child
306                #
307                pid = os.fork()
[32]308
[8]309                if pid > 0:
[7]310
[32]311                        sys.exit(0)  # end parent
312
[8]313                # creates a session and sets the process group ID
314                #
315                os.setsid()
[7]316
[8]317                # Fork the second child
318                #
319                pid = os.fork()
[32]320
[8]321                if pid > 0:
[5]322
[32]323                        sys.exit(0)  # end parent
324
[8]325                # Go to the root directory and set the umask
326                #
327                os.chdir('/')
328                os.umask(0)
329
330                sys.stdin.close()
331                sys.stdout.close()
[36]332                #sys.stderr.close()
[8]333
334                os.open('/dev/null', 0)
335                os.dup(0)
336                os.dup(0)
337
338                self.run()
339
[22]340        def printTime( self ):
[33]341                "Print current time in human readable format"
[22]342
[33]343                return time.strftime("%a %d %b %Y %H:%M:%S")
[22]344
[9]345        def run( self ):
[8]346                "Main thread"
347
[36]348                xmlthread = threading.Thread( None, self.processXML, 'xmlthread' )
349                storethread = threading.Thread( None, self.storeMetrics, 'storethread' )
[22]350
[36]351                while( 1 ):
352
353                        if not xmlthread.isAlive():
354                                # Gather XML at the same interval as gmetad
355
356                                # threaded call to: self.processXML()
357                                #
358                                xmlthread = threading.Thread( None, self.processXML, 'xmlthread' )
359                                xmlthread.start()
360
361                        if not storethread.isAlive():
362                                # Store metrics every .. sec
363
364                                # threaded call to: self.storeMetrics()
365                                #
366                                storethread = threading.Thread( None, self.storeMetrics, 'storethread' )
367                                storethread.start()
368               
369                        # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway
370                        time.sleep( 1 ) 
371
[33]372        def storeMetrics( self ):
373                "Store metrics retained in memory to disk"
[22]374
[40]375                debug_msg( 7, self.printTime() + ' - storethread(): started.' )
[39]376
[38]377                # Store metrics somewhere between every 60 and 180 seconds
378                #
[44]379                #STORE_INTERVAL = random.randint( 360, 640 )
[50]380                STORE_INTERVAL = random.randint( 90, 120 )
[22]381
[39]382                storethread = threading.Thread( None, self.storeThread, 'storemetricthread' )
[36]383                storethread.start()
384
[40]385                debug_msg( 7, self.printTime() + ' - storethread(): Sleeping.. (%ss)' %STORE_INTERVAL )
[36]386                time.sleep( STORE_INTERVAL )
[40]387                debug_msg( 7, self.printTime() + ' - storethread(): Done sleeping.' )
[36]388
389                if storethread.isAlive():
390
[40]391                        debug_msg( 7, self.printTime() + ' - storethread(): storemetricthread() still running, waiting to finish..' )
[47]392                        storethread.join( STORE_TIMEOUT ) # Maximum time is for storing thread to finish
[40]393                        debug_msg( 7, self.printTime() + ' - storethread(): Done waiting.' )
[36]394
[40]395                debug_msg( 7, self.printTime() + ' - storethread(): finished.' )
[36]396
397                return 0
398
[39]399        def storeThread( self ):
400
[40]401                debug_msg( 7, self.printTime() + ' - storemetricthread(): started.' )
402                debug_msg( 7, self.printTime() + ' - storemetricthread(): Storing data..' )
[39]403                ret = self.myHandler.storeMetrics()
[40]404                debug_msg( 7, self.printTime() + ' - storemetricthread(): Done storing.' )
405                debug_msg( 7, self.printTime() + ' - storemetricthread(): finished.' )
[39]406               
407                return ret
408
[8]409        def processXML( self ):
410                "Process XML"
411
[40]412                debug_msg( 7, self.printTime() + ' - xmlthread(): started.' )
[8]413
[39]414                parsethread = threading.Thread( None, self.parseThread, 'parsethread' )
[36]415                parsethread.start()
416
[40]417                debug_msg( 7, self.printTime() + ' - xmlthread(): Sleeping.. (%ss)' %self.config.getLowestInterval() )
[36]418                time.sleep( float( self.config.getLowestInterval() ) ) 
[40]419                debug_msg( 7, self.printTime() + ' - xmlthread(): Done sleeping.' )
[36]420
421                if parsethread.isAlive():
422
[40]423                        debug_msg( 7, self.printTime() + ' - xmlthread(): parsethread() still running, waiting to finish..' )
[47]424                        parsethread.join( PARSE_TIMEOUT ) # Maximum time for XML thread to finish
[40]425                        debug_msg( 7, self.printTime() + ' - xmlthread(): Done waiting.' )
[36]426
[40]427                debug_msg( 7, self.printTime() + ' - xmlthread(): finished.' )
[36]428
429                return 0
430
[39]431        def parseThread( self ):
432
[40]433                debug_msg( 7, self.printTime() + ' - parsethread(): started.' )
434                debug_msg( 7, self.printTime() + ' - parsethread(): Parsing XML..' )
[39]435                ret = self.myParser.parse( self.myXMLGatherer.getFileObject() )
[40]436                debug_msg( 7, self.printTime() + ' - parsethread(): Done parsing.' )
437                debug_msg( 7, self.printTime() + ' - parsethread(): finished.' )
[39]438
439                return ret
440
[9]441class GangliaConfigParser:
442
[34]443        sources = [ ]
[9]444
445        def __init__( self, config ):
[32]446
[9]447                self.config = config
448                self.parseValues()
449
[32]450        def parseValues( self ):
[9]451                "Parse certain values from gmetad.conf"
452
453                readcfg = open( self.config, 'r' )
454
455                for line in readcfg.readlines():
456
457                        if line.count( '"' ) > 1:
458
[10]459                                if line.find( 'data_source' ) != -1 and line[0] != '#':
[9]460
[11]461                                        source = { }
462                                        source['name'] = line.split( '"' )[1]
[9]463                                        source_words = line.split( '"' )[2].split( ' ' )
464
465                                        for word in source_words:
466
467                                                valid_interval = 1
468
469                                                for letter in word:
[32]470
[9]471                                                        if letter not in string.digits:
[32]472
[9]473                                                                valid_interval = 0
474
[10]475                                                if valid_interval and len(word) > 0:
[32]476
[9]477                                                        source['interval'] = word
[12]478                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
[33]479       
480                                        # No interval found, use Ganglia's default     
481                                        if not source.has_key( 'interval' ):
482                                                source['interval'] = 15
483                                                debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
[32]484
[33]485                                        self.sources.append( source )
[9]486
487        def getInterval( self, source_name ):
[32]488
[9]489                for source in self.sources:
[32]490
[12]491                        if source['name'] == source_name:
[32]492
[9]493                                return source['interval']
[32]494
[9]495                return None
496
[34]497        def getLowestInterval( self ):
498
499                lowest_interval = 0
500
501                for source in self.sources:
502
503                        if not lowest_interval or source['interval'] <= lowest_interval:
504
505                                lowest_interval = source['interval']
506
507                # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays
508                if lowest_interval:
509                        return lowest_interval
510                else:
511                        return 15
512
[9]513class RRDHandler:
514
[32]515        myMetrics = { }
[40]516        lastStored = { }
[47]517        timeserials = { }
[36]518        slot = None
[32]519
[33]520        def __init__( self, config, cluster ):
[44]521                self.block = 0
[9]522                self.cluster = cluster
[33]523                self.config = config
[40]524                self.slot = threading.Lock()
[37]525                self.rrdm = RRDMutator()
[42]526                self.gatherLastUpdates()
[9]527
[42]528        def gatherLastUpdates( self ):
529                "Populate the lastStored list, containing timestamps of all last updates"
530
531                cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster )
532
533                hosts = [ ]
534
535                if os.path.exists( cluster_dir ):
536
[44]537                        dirlist = os.listdir( cluster_dir )
[42]538
[44]539                        for dir in dirlist:
[42]540
[44]541                                hosts.append( dir )
[42]542
543                for host in hosts:
544
[47]545                        host_dir = cluster_dir + '/' + host
546                        dirlist = os.listdir( host_dir )
547
548                        for dir in dirlist:
549
550                                if not self.timeserials.has_key( host ):
551
552                                        self.timeserials[ host ] = [ ]
553
554                                self.timeserials[ host ].append( dir )
555
[42]556                        last_serial = self.getLastRrdTimeSerial( host )
557                        if last_serial:
558
559                                metric_dir = cluster_dir + '/' + host + '/' + last_serial
560                                if os.path.exists( metric_dir ):
561
[44]562                                        dirlist = os.listdir( metric_dir )
[42]563
[44]564                                        for file in dirlist:
[42]565
[44]566                                                metricname = file.split( '.rrd' )[0]
[42]567
[44]568                                                if not self.lastStored.has_key( host ):
[42]569
[44]570                                                        self.lastStored[ host ] = { }
[42]571
[44]572                                                self.lastStored[ host ][ metricname ] = self.rrdm.grabLastUpdate( metric_dir + '/' + file )
[42]573
[32]574        def getClusterName( self ):
575                return self.cluster
576
577        def memMetric( self, host, metric ):
578
[34]579                if self.myMetrics.has_key( host ):
[32]580
[34]581                        if self.myMetrics[ host ].has_key( metric['name'] ):
[32]582
[34]583                                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
[32]584
[34]585                                        if mymetric['time'] == metric['time']:
[32]586
[34]587                                                # Allready have this metric, abort
588                                                return 1
589                        else:
590                                self.myMetrics[ host ][ metric['name'] ] = [ ]
591                else:
[32]592                        self.myMetrics[ host ] = { }
[34]593                        self.myMetrics[ host ][ metric['name'] ] = [ ]
[32]594
[40]595                # Ah, psst, push it
596                #
597                # <atomic>
598                self.slot.acquire()
599
[32]600                self.myMetrics[ host ][ metric['name'] ].append( metric )
601
[40]602                self.slot.release()
603                # </atomic>
604
[47]605        def makeUpdateList( self, host, metriclist ):
[37]606
607                update_list = [ ]
[41]608                metric = None
[37]609
[47]610                while len( metriclist ) > 0:
[37]611
[40]612                        # Kabouter pop
613                        #
614                        # <atomic>     
[47]615                        #self.slot.acquire()
[37]616
[41]617                        # len might have changed since loop start
618                        #
[47]619                        if len( metriclist ) > 0:
620                                metric = metriclist.pop( 0 )
[40]621
[47]622                        #self.slot.release()
[40]623                        # </atomic>
624
[41]625                        if metric:
[47]626                                if self.checkStoreMetric( host, metric ):
[41]627                                        update_list.append( '%s:%s' %( metric['time'], metric['val'] ) )
[40]628
[37]629                return update_list
630
[49]631        def checkStoreMetric( self, host, metric ):
[40]632
633                if self.lastStored.has_key( host ):
634
[47]635                        if self.lastStored[ host ].has_key( metric['name'] ):
[40]636
[47]637                                if metric['time'] <= self.lastStored[ host ][ metric['name'] ]:
[40]638
[50]639                                        # This is old
[40]640                                        return 0
641
[50]642                return 1
643
644        def memLastUpdate( self, host, metriclist ):
645
646                last_update_time = 0
647
648                for metric in metriclist:
649
650                        if metric['time'] > last_update_time:
651
652                                last_update_time = metric['time']
653
654                if not self.lastStored.has_key( host ):
[40]655                        self.lastStored[ host ] = { }
656
[50]657                if last_update_time > self.lastStored[ host ][ metric['name'] ]:
658                        self.lastStored[ host ][ metric['name'] ] = last_update_time
[40]659
[33]660        def storeMetrics( self ):
661
662                for hostname, mymetrics in self.myMetrics.items():     
663
664                        for metricname, mymetric in mymetrics.items():
665
[50]666                                # Atomic: Don't want other threads messing around now
667                                #
[47]668                                self.slot.acquire() 
[33]669
[47]670                                # Create a mapping table, each metric to the period where it should be stored
671                                #
672                                metric_serial_table = self.determineSerials( hostname, metricname, mymetric )
673                                self.myMetrics[ hostname ][ metricname ] = [ ]
[33]674
[50]675                                self.slot.release() # Atomic end
[43]676
[50]677                                update_rets = [ ]
678
[47]679                                for period, pmetric in metric_serial_table.items():
680
681                                        self.createCheck( hostname, metricname, period )       
682
683                                        update_ret = self.update( hostname, metricname, period, pmetric )
684
685                                        if update_ret == 0:
686
687                                                debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
688                                        else:
689                                                debug_msg( 9, 'metric update failed' )
690
[50]691                                        update_rets.append( update_ret )
[47]692
[50]693                                if not (1) in update_rets:
694
695                                        self.memLastUpdate( hostname, mymetric )
696
[17]697        def makeTimeSerial( self ):
[32]698                "Generate a time serial. Seconds since epoch"
[17]699
700                # Seconds since epoch
701                mytime = int( time.time() )
702
703                return mytime
704
[50]705        def makeRrdPath( self, host, metricname, timeserial ):
[32]706                """
707                Make a RRD location/path and filename
708                If a metric or timeserial are supplied the complete locations
709                will be made, else just the host directory
710                """
[17]711
[50]712                rrd_dir = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
713                rrd_file = '%s/%s.rrd' %( rrd_dir, metricname )
[17]714
715                return rrd_dir, rrd_file
716
[20]717        def getLastRrdTimeSerial( self, host ):
[32]718                """
719                Find the last timeserial (directory) for this host
720                This is determined once every host
721                """
[17]722
[19]723                newest_timeserial = 0
724
[47]725                for dir in self.timeserials[ host ]:
[32]726
[47]727                        valid_dir = 1
[17]728
[47]729                        for letter in dir:
730                                if letter not in string.digits:
731                                        valid_dir = 0
[17]732
[47]733                        if valid_dir:
734                                timeserial = dir
735                                if timeserial > newest_timeserial:
736                                        newest_timeserial = timeserial
[17]737
738                if newest_timeserial:
[18]739                        return newest_timeserial
[17]740                else:
741                        return 0
742
[47]743        def determinePeriod( self, host, check_serial ):
744
745                period_serial = 0
746
747                for serial in self.timeserials[ host ]:
748
749                        if check_serial >= serial and period_serial < serial:
750
751                                period_serial = serial
752
753                return period_serial
754
755        def determineSerials( self, host, metricname, metriclist ):
756                """
757                Determine the correct serial and corresponding rrd to store
758                for a list of metrics
759                """
760
761                metric_serial_table = { }
762
763                for metric in metriclist:
764
765                        if metric['name'] == metricname:
766
767                                period = self.determinePeriod( host, metric['time'] )   
768
769                                archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60)
770
[49]771                                if (int( metric['time'] ) - int( period ) ) > archive_secs:
[47]772
773                                        # This one should get it's own new period
774                                        period = metric['time']
[50]775                                        self.timeserials[ host ].append( period )
[47]776
777                                if not metric_serial_table.has_key( period ):
778
[49]779                                        metric_serial_table[ period ] = [ ]
[47]780
781                                metric_serial_table[ period ].append( metric )
782
783                print metric_serial_table
784
785                return metric_serial_table
786
[33]787        def createCheck( self, host, metricname, timeserial ):
[9]788                "Check if an .rrd allready exists for this metric, create if not"
789
[35]790                debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
[47]791               
[33]792                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
[17]793
[9]794                if not os.path.exists( rrd_dir ):
795                        os.makedirs( rrd_dir )
[14]796                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
[9]797
[14]798                if not os.path.exists( rrd_file ):
[9]799
[33]800                        interval = self.config.getInterval( self.cluster )
[47]801                        heartbeat = 8 * int( interval )
[9]802
[37]803                        params = [ ]
[12]804
[37]805                        params.append( '--step' )
806                        params.append( str( interval ) )
[12]807
[37]808                        params.append( '--start' )
[47]809                        params.append( str( int( timeserial ) - 1 ) )
[12]810
[37]811                        params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat )
812                        params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) )
[13]813
[37]814                        self.rrdm.create( str(rrd_file), params )
815
[14]816                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
817
[47]818        def update( self, host, metricname, timeserial, metriclist ):
[9]819
[35]820                debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
[9]821
[33]822                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
[18]823
[47]824                update_list = self.makeUpdateList( host, metriclist )
[15]825
[41]826                if len( update_list ) > 0:
827                        ret = self.rrdm.update( str(rrd_file), update_list )
[32]828
[41]829                        if ret:
830                                return 1
[27]831               
[41]832                        debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) )
[15]833
[36]834                return 0
835
[8]836def main():
837        "Program startup"
838
839        myProcessor = GangliaXMLProcessor()
840
[22]841        if DAEMONIZE:
842                myProcessor.daemon()
843        else:
844                myProcessor.run()
845
[9]846def check_dir( directory ):
847        "Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"
848
849        if directory[-1] == '/':
850                directory = directory[:-1]
851
852        return directory
853
[12]854def debug_msg( level, msg ):
855
856        if (DEBUG_LEVEL >= level):
857                sys.stderr.write( msg + '\n' )
858
[46]859def printTime( ):
860        "Print current time in human readable format"
861
862        return time.strftime("%a %d %b %Y %H:%M:%S")
863
[5]864# Let's go
[9]865if __name__ == '__main__':
866        main()
Note: See TracBrowser for help on using the repository browser.