source: trunk/daemon/togad.py @ 82

Last change on this file since 82 was 82, checked in by bastiaans, 18 years ago

daemon/togad.py:

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