source: trunk/daemon/togad.py @ 70

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

daemon/togad.py:

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