source: trunk/daemon/togad.py @ 72

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

daemon/togad.py:

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