source: trunk/daemon/togad.py @ 77

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

daemon/togad.py:

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