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
Line 
1#!/usr/bin/env python
2
3from xml.sax import make_parser
4from xml.sax.handler import ContentHandler
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( 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
193class GangliaXMLHandler( ContentHandler ):
194        """Parse Ganglia's XML"""
195
196        def __init__( self, config ):
197                """Setup initial variables and gather info on existing rrd archive"""
198
199                self.config = config
200                self.clusters = { }
201                debug_msg( 0, printTime() + ' - Checking existing toga rrd archive..' )
202                self.gatherClusters()
203                debug_msg( 0, printTime() + ' - Check done.' )
204
205        def gatherClusters( self ):
206                """Find all existing clusters in archive dir"""
207
208                archive_dir = check_dir(ARCHIVE_PATH)
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
220                                if not self.clusters.has_key( clustername ) and clustername in ARCHIVE_DATASOURCES:
221
222                                        self.clusters[ clustername ] = RRDHandler( self.config, clustername )
223
224        def startElement( self, name, attrs ):
225                """Memorize appropriate data from xml start tags"""
226
227                if name == 'GANGLIA_XML':
228
229                        self.XMLSource = attrs.get( 'SOURCE', "" )
230                        self.gangliaVersion = attrs.get( 'VERSION', "" )
231
232                        debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
233
234                elif name == 'GRID':
235
236                        self.gridName = attrs.get( 'NAME', "" )
237                        self.time = attrs.get( 'LOCALTIME', "" )
238
239                        debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
240
241                elif name == 'CLUSTER':
242
243                        self.clusterName = attrs.get( 'NAME', "" )
244                        self.time = attrs.get( 'LOCALTIME', "" )
245
246                        if not self.clusters.has_key( self.clusterName ) and self.clusterName in ARCHIVE_DATASOURCES:
247
248                                self.clusters[ self.clusterName ] = RRDHandler( self.config, self.clusterName )
249
250                                debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
251
252                elif name == 'HOST' and self.clusterName in ARCHIVE_DATASOURCES:     
253
254                        self.hostName = attrs.get( 'NAME', "" )
255                        self.hostIp = attrs.get( 'IP', "" )
256                        self.hostReported = attrs.get( 'REPORTED', "" )
257
258                        debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
259
260                elif name == 'METRIC' and self.clusterName in ARCHIVE_DATASOURCES:
261
262                        type = attrs.get( 'TYPE', "" )
263
264                        if type not in UNSUPPORTED_ARCHIVE_TYPES:
265
266                                myMetric = { }
267                                myMetric['name'] = attrs.get( 'NAME', "" )
268                                myMetric['val'] = attrs.get( 'VAL', "" )
269                                myMetric['time'] = self.hostReported
270
271                                self.clusters[ self.clusterName ].memMetric( self.hostName, myMetric )
272
273                                debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
274
275        def storeMetrics( self ):
276                """Store metrics of each cluster rrd handler"""
277
278                for clustername, rrdh in self.clusters.items():
279
280                        ret = rrdh.storeMetrics()
281
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
288class GangliaXMLGatherer:
289        """Setup a connection and file object to Ganglia's XML"""
290
291        s = None
292
293        def __init__( self, host, port ):
294                """Store host and port for connection"""
295
296                self.host = host
297                self.port = port
298                self.connect()
299
300        def connect( self ):
301                """Setup connection to XML source"""
302
303                for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ):
304
305                        af, socktype, proto, canonname, sa = res
306
307                        try:
308
309                                self.s = socket.socket( af, socktype, proto )
310
311                        except socket.error, msg:
312
313                                self.s = None
314                                continue
315
316                        try:
317
318                                self.s.connect( sa )
319
320                        except socket.error, msg:
321
322                                self.s.close()
323                                self.s = None
324                                continue
325
326                        break
327
328                if self.s is None:
329
330                        debug_msg( 0, 'Could not open socket' )
331                        sys.exit( 1 )
332
333        def disconnect( self ):
334                """Close socket"""
335
336                if self.s:
337                        self.s.close()
338                        self.s = None
339
340        def __del__( self ):
341                """Kill the socket before we leave"""
342
343                self.disconnect()
344
345        def getFileObject( self ):
346                """Connect, and return a file object"""
347
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()
354
355                return self.s.makefile( 'r' )
356
357class GangliaXMLProcessor:
358        """Main class for processing XML and acting with it"""
359
360        def __init__( self ):
361                """Setup initial XML connection and handlers"""
362
363                self.config = GangliaConfigParser( GMETAD_CONF )
364
365                self.myXMLGatherer = GangliaXMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] ) 
366                self.myParser = make_parser()   
367                self.myHandler = GangliaXMLHandler( self.config )
368                self.myParser.setContentHandler( self.myHandler )
369
370        def daemon( self ):
371                """Run as daemon forever"""
372
373                # Fork the first child
374                #
375                pid = os.fork()
376
377                if pid > 0:
378
379                        sys.exit(0)  # end parent
380
381                # creates a session and sets the process group ID
382                #
383                os.setsid()
384
385                # Fork the second child
386                #
387                pid = os.fork()
388
389                if pid > 0:
390
391                        sys.exit(0)  # end parent
392
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()
400                #sys.stderr.close()
401
402                os.open('/dev/null', 0)
403                os.dup(0)
404                os.dup(0)
405
406                self.run()
407
408        def printTime( self ):
409                """Print current time in human readable format for logging"""
410
411                return time.strftime("%a %d %b %Y %H:%M:%S")
412
413        def run( self ):
414                """Main XML processing; start a xml and storethread"""
415
416                xmlthread = threading.Thread( None, self.processXML, 'xmlthread' )
417                storethread = threading.Thread( None, self.storeMetrics, 'storethread' )
418
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
429                        if not storethread.isAlive():
430                                # Store metrics every .. sec
431
432                                # threaded call to: self.storeMetrics()
433                                #
434                                storethread = threading.Thread( None, self.storeMetrics, 'storethread' )
435                                storethread.start()
436               
437                        # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway
438                        time.sleep( 1 ) 
439
440        def storeMetrics( self ):
441                """Store metrics retained in memory to disk"""
442
443                debug_msg( 7, self.printTime() + ' - storethread(): started.' )
444
445                # Store metrics somewhere between every 360 and 640 seconds
446                #
447                STORE_INTERVAL = random.randint( 360, 640 )
448
449                storethread = threading.Thread( None, self.storeThread, 'storemetricthread' )
450                storethread.start()
451
452                debug_msg( 7, self.printTime() + ' - storethread(): Sleeping.. (%ss)' %STORE_INTERVAL )
453                time.sleep( STORE_INTERVAL )
454                debug_msg( 7, self.printTime() + ' - storethread(): Done sleeping.' )
455
456                if storethread.isAlive():
457
458                        debug_msg( 7, self.printTime() + ' - storethread(): storemetricthread() still running, waiting to finish..' )
459                        storethread.join( STORE_TIMEOUT ) # Maximum time is for storing thread to finish
460                        debug_msg( 7, self.printTime() + ' - storethread(): Done waiting.' )
461
462                debug_msg( 7, self.printTime() + ' - storethread(): finished.' )
463
464                return 0
465
466        def storeThread( self ):
467                """Actual metric storing thread"""
468
469                debug_msg( 7, self.printTime() + ' - storemetricthread(): started.' )
470                debug_msg( 7, self.printTime() + ' - storemetricthread(): Storing data..' )
471                ret = self.myHandler.storeMetrics()
472                debug_msg( 7, self.printTime() + ' - storemetricthread(): Done storing.' )
473                debug_msg( 7, self.printTime() + ' - storemetricthread(): finished.' )
474               
475                return ret
476
477        def processXML( self ):
478                """Process XML"""
479
480                debug_msg( 7, self.printTime() + ' - xmlthread(): started.' )
481
482                parsethread = threading.Thread( None, self.parseThread, 'parsethread' )
483                parsethread.start()
484
485                debug_msg( 7, self.printTime() + ' - xmlthread(): Sleeping.. (%ss)' %self.config.getLowestInterval() )
486                time.sleep( float( self.config.getLowestInterval() ) ) 
487                debug_msg( 7, self.printTime() + ' - xmlthread(): Done sleeping.' )
488
489                if parsethread.isAlive():
490
491                        debug_msg( 7, self.printTime() + ' - xmlthread(): parsethread() still running, waiting to finish..' )
492                        parsethread.join( PARSE_TIMEOUT ) # Maximum time for XML thread to finish
493                        debug_msg( 7, self.printTime() + ' - xmlthread(): Done waiting.' )
494
495                debug_msg( 7, self.printTime() + ' - xmlthread(): finished.' )
496
497                return 0
498
499        def parseThread( self ):
500                """Actual parsing thread"""
501
502                debug_msg( 7, self.printTime() + ' - parsethread(): started.' )
503                debug_msg( 7, self.printTime() + ' - parsethread(): Parsing XML..' )
504                ret = self.myParser.parse( self.myXMLGatherer.getFileObject() )
505                debug_msg( 7, self.printTime() + ' - parsethread(): Done parsing.' )
506                debug_msg( 7, self.printTime() + ' - parsethread(): finished.' )
507
508                return ret
509
510class GangliaConfigParser:
511
512        sources = [ ]
513
514        def __init__( self, config ):
515                """Parse some stuff from our gmetad's config, such as polling interval"""
516
517                self.config = config
518                self.parseValues()
519
520        def parseValues( self ):
521                """Parse certain values from gmetad.conf"""
522
523                readcfg = open( self.config, 'r' )
524
525                for line in readcfg.readlines():
526
527                        if line.count( '"' ) > 1:
528
529                                if line.find( 'data_source' ) != -1 and line[0] != '#':
530
531                                        source = { }
532                                        source['name'] = line.split( '"' )[1]
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:
540
541                                                        if letter not in string.digits:
542
543                                                                valid_interval = 0
544
545                                                if valid_interval and len(word) > 0:
546
547                                                        source['interval'] = word
548                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
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']) )
554
555                                        self.sources.append( source )
556
557        def getInterval( self, source_name ):
558                """Return interval for source_name"""
559
560                for source in self.sources:
561
562                        if source['name'] == source_name:
563
564                                return source['interval']
565
566                return None
567
568        def getLowestInterval( self ):
569                """Return the lowest interval of all clusters"""
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
585class RRDHandler:
586        """Class for handling RRD activity"""
587
588        myMetrics = { }
589        lastStored = { }
590        timeserials = { }
591        slot = None
592
593        def __init__( self, config, cluster ):
594                """Setup initial variables"""
595                self.block = 0
596                self.cluster = cluster
597                self.config = config
598                self.slot = threading.Lock()
599                self.rrdm = RRDMutator()
600                self.gatherLastUpdates()
601
602        def gatherLastUpdates( self ):
603                """Populate the lastStored list, containing timestamps of all last updates"""
604
605                cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster )
606
607                hosts = [ ]
608
609                if os.path.exists( cluster_dir ):
610
611                        dirlist = os.listdir( cluster_dir )
612
613                        for dir in dirlist:
614
615                                hosts.append( dir )
616
617                for host in hosts:
618
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
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
636                                        dirlist = os.listdir( metric_dir )
637
638                                        for file in dirlist:
639
640                                                metricname = file.split( '.rrd' )[0]
641
642                                                if not self.lastStored.has_key( host ):
643
644                                                        self.lastStored[ host ] = { }
645
646                                                self.lastStored[ host ][ metricname ] = self.rrdm.grabLastUpdate( metric_dir + '/' + file )
647
648        def getClusterName( self ):
649                """Return clustername"""
650
651                return self.cluster
652
653        def memMetric( self, host, metric ):
654                """Store metric from host in memory"""
655
656                if self.myMetrics.has_key( host ):
657
658                        if self.myMetrics[ host ].has_key( metric['name'] ):
659
660                                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
661
662                                        if mymetric['time'] == metric['time']:
663
664                                                # Allready have this metric, abort
665                                                return 1
666                        else:
667                                self.myMetrics[ host ][ metric['name'] ] = [ ]
668                else:
669                        self.myMetrics[ host ] = { }
670                        self.myMetrics[ host ][ metric['name'] ] = [ ]
671
672                # Push new metric onto stack
673                # atomic code; only 1 thread at a time may access the stack
674
675                # <ATOMIC>
676                #
677                self.slot.acquire()
678
679                self.myMetrics[ host ][ metric['name'] ].append( metric )
680
681                self.slot.release()
682                #
683                # </ATOMIC>
684
685        def makeUpdateList( self, host, metriclist ):
686                """
687                Make a list of update values for rrdupdate
688                but only those that we didn't store before
689                """
690
691                update_list = [ ]
692                metric = None
693
694                while len( metriclist ) > 0:
695
696                        metric = metriclist.pop( 0 )
697
698                        if self.checkStoreMetric( host, metric ):
699                                update_list.append( '%s:%s' %( metric['time'], metric['val'] ) )
700
701                return update_list
702
703        def checkStoreMetric( self, host, metric ):
704                """Check if supplied metric if newer than last one stored"""
705
706                if self.lastStored.has_key( host ):
707
708                        if self.lastStored[ host ].has_key( metric['name'] ):
709
710                                if metric['time'] <= self.lastStored[ host ][ metric['name'] ]:
711
712                                        # This is old
713                                        return 0
714
715                return 1
716
717        def memLastUpdate( self, host, metricname, metriclist ):
718                """
719                Memorize the time of the latest metric from metriclist
720                but only if it wasn't allready memorized
721                """
722
723                if not self.lastStored.has_key( host ):
724                        self.lastStored[ host ] = { }
725
726                last_update_time = 0
727
728                for metric in metriclist:
729
730                        if metric['name'] == metricname:
731
732                                if metric['time'] > last_update_time:
733
734                                        last_update_time = metric['time']
735
736                if self.lastStored[ host ].has_key( metricname ):
737                       
738                        if last_update_time <= self.lastStored[ host ][ metricname ]:
739                                return 1
740
741                self.lastStored[ host ][ metricname ] = last_update_time
742
743        def storeMetrics( self ):
744                """
745                Store all metrics from memory to disk
746                and do it to the RRD's in appropriate timeperiod directory
747                """
748
749                for hostname, mymetrics in self.myMetrics.items():     
750
751                        for metricname, mymetric in mymetrics.items():
752
753                                metrics_to_store = [ ]
754
755                                # Pop metrics from stack for storing until none is left
756                                # atomic code: only 1 thread at a time may access myMetrics
757
758                                # <ATOMIC>
759                                #
760                                self.slot.acquire() 
761
762                                while len( self.myMetrics[ hostname ][ metricname ] ) > 0:
763
764                                        if len( self.myMetrics[ hostname ][ metricname ] ) > 0:
765                                                metrics_to_store.append( self.myMetrics[ hostname ][ metricname ].pop( 0 ) )
766
767                                self.slot.release()
768                                #
769                                # </ATOMIC>
770
771                                # Create a mapping table, each metric to the period where it should be stored
772                                #
773                                metric_serial_table = self.determineSerials( hostname, metricname, metrics_to_store )
774
775                                update_rets = [ ]
776
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
789                                        update_rets.append( update_ret )
790
791                                if not (1) in update_rets:
792
793                                        self.memLastUpdate( hostname, metricname, metrics_to_store )
794
795        def makeTimeSerial( self ):
796                """Generate a time serial. Seconds since epoch"""
797
798                # Seconds since epoch
799                mytime = int( time.time() )
800
801                return mytime
802
803        def makeRrdPath( self, host, metricname, timeserial ):
804                """Make a RRD location/path and filename"""
805
806                rrd_dir = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
807                rrd_file = '%s/%s.rrd' %( rrd_dir, metricname )
808
809                return rrd_dir, rrd_file
810
811        def getLastRrdTimeSerial( self, host ):
812                """Find the last timeserial (directory) for this host"""
813
814                newest_timeserial = 0
815
816                for dir in self.timeserials[ host ]:
817
818                        valid_dir = 1
819
820                        for letter in dir:
821                                if letter not in string.digits:
822                                        valid_dir = 0
823
824                        if valid_dir:
825                                timeserial = dir
826                                if timeserial > newest_timeserial:
827                                        newest_timeserial = timeserial
828
829                if newest_timeserial:
830                        return newest_timeserial
831                else:
832                        return 0
833
834        def determinePeriod( self, host, check_serial ):
835                """Determine to which period (directory) this time(serial) belongs"""
836
837                period_serial = 0
838
839                if self.timeserials.has_key( host ):
840
841                        for serial in self.timeserials[ host ]:
842
843                                if check_serial >= serial and period_serial < serial:
844
845                                        period_serial = serial
846
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
865                                if (int( metric['time'] ) - int( period ) ) > archive_secs:
866
867                                        # This one should get it's own new period
868                                        period = metric['time']
869
870                                        if not self.timeserials.has_key( host ):
871                                                self.timeserials[ host ] = [ ]
872
873                                        self.timeserials[ host ].append( period )
874
875                                if not metric_serial_table.has_key( period ):
876
877                                        metric_serial_table[ period ] = [ ]
878
879                                metric_serial_table[ period ].append( metric )
880
881                return metric_serial_table
882
883        def createCheck( self, host, metricname, timeserial ):
884                """Check if an rrd allready exists for this metric, create if not"""
885
886                debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
887               
888                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
889
890                if not os.path.exists( rrd_dir ):
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
907                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
908
909                if not os.path.exists( rrd_file ):
910
911                        interval = self.config.getInterval( self.cluster )
912                        heartbeat = 8 * int( interval )
913
914                        params = [ ]
915
916                        params.append( '--step' )
917                        params.append( str( interval ) )
918
919                        params.append( '--start' )
920                        params.append( str( int( timeserial ) - 1 ) )
921
922                        params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat )
923                        params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) )
924
925                        self.rrdm.create( str(rrd_file), params )
926
927                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
928
929        def update( self, host, metricname, timeserial, metriclist ):
930                """
931                Update rrd file for host with metricname
932                in directory timeserial with metriclist
933                """
934
935                debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
936
937                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
938
939                update_list = self.makeUpdateList( host, metriclist )
940
941                if len( update_list ) > 0:
942                        ret = self.rrdm.update( str(rrd_file), update_list )
943
944                        if ret:
945                                return 1
946               
947                        debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) )
948
949                return 0
950
951def main():
952        """Program startup"""
953
954        myProcessor = GangliaXMLProcessor()
955
956        if DAEMONIZE:
957                myProcessor.daemon()
958        else:
959                myProcessor.run()
960
961def check_dir( directory ):
962        """Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"""
963
964        if directory[-1] == '/':
965                directory = directory[:-1]
966
967        return directory
968
969def debug_msg( level, msg ):
970        """Only print msg if it is not below our debug level"""
971
972        if (DEBUG_LEVEL >= level):
973                sys.stderr.write( msg + '\n' )
974
975def printTime( ):
976        """Print current time in human readable format"""
977
978        return time.strftime("%a %d %b %Y %H:%M:%S")
979
980# Ooohh, someone started me! Let's go..
981if __name__ == '__main__':
982        main()
Note: See TracBrowser for help on using the repository browser.