source: trunk/daemon/togad.py @ 63

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

daemon/togad.py:

Miscellanious code cleanup and additional pydocs

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