source: trunk/daemon/togad.py @ 78

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

daemon/togad.py:

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