source: trunk/daemon/togad.py @ 73

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

daemon/togad.py:

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