source: trunk/daemon/togad.py @ 90

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

daemon/togad.py:

  • Only add nodes once
  • Only add nodes if it is not empty
File size: 31.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# 6  = SQL
23# 1  = daemon threading
24#
25DEBUG_LEVEL = 7
26
27# Where is the gmetad.conf located
28#
29GMETAD_CONF = '/etc/gmetad.conf'
30
31# Where to grab XML data from
32# Normally: local gmetad (port 8651)
33#
34# Syntax: <hostname>:<port>
35#
36ARCHIVE_XMLSOURCE = "localhost:8651"
37
38# List of data_source names to archive for
39#
40# Syntax: [ "<clustername>", "<clustername>" ]
41#
42ARCHIVE_DATASOURCES = [ "LISA Cluster" ]
43
44# Where to store the archived rrd's
45#
46ARCHIVE_PATH = '/data/toga/rrds'
47
48# Amount of hours to store in one single archived .rrd
49#
50ARCHIVE_HOURS_PER_RRD = 12
51
52# Toga's SQL dbase to use
53#
54# Syntax: <hostname>/<database>
55#
56TOGA_SQL_DBASE = "localhost/toga"
57
58# Wether or not to run as a daemon in background
59#
60DAEMONIZE = 0
61
62######################
63#                    #
64# Configuration ends #
65#                    #
66######################
67
68###
69# You'll only want to change anything below here unless you
70# know what you are doing (i.e. your name is Ramon Bastiaans :D )
71###
72
73# What XML data types not to store
74#
75UNSUPPORTED_ARCHIVE_TYPES = [ 'string' ]
76
77# Maximum time (in seconds) a parsethread may run
78#
79PARSE_TIMEOUT = 60
80
81# Maximum time (in seconds) a storethread may run
82#
83STORE_TIMEOUT = 360
84
85"""
86This is TOrque-GAnglia's data Daemon
87"""
88
89class DataSQLStore:
90
91        db_vars = None
92        dbc = None
93
94        def __init__( self, hostname, database ):
95
96                self.db_vars = DBClass.InitVars(DataBaseName=database,
97                                User='root',
98                                Host=hostname,
99                                Password='',
100                                Dictionary='true')
101
102                try:
103                        self.dbc     = DBClass.DB(self.db_vars)
104                except DBClass.DBError, details:
105                        print 'Error in connection to db: %s' %details
106                        sys.exit(1)
107
108        def setDatabase(self, statement):
109                ret = self.doDatabase('set', statement)
110                return ret
111               
112        def getDatabase(self, statement):
113                ret = self.doDatabase('get', statement)
114                return ret
115
116        def doDatabase(self, type, statement):
117
118                debug_msg( 6, 'doDatabase(): %s: %s' %(type, statement) )
119                try:
120                        if type == 'set':
121                                result = self.dbc.Set( statement )
122                                self.dbc.Commit()
123                        elif type == 'get':
124                                result = self.dbc.Get( statement )
125                               
126                except DBClass.DBError, detail:
127                        operation = statement.split(' ')[0]
128                        print "%s operation on database failed while performing\n'%s'\n%s"\
129                                %(operation, statement, detail)
130                        sys.exit(1)
131
132                debug_msg( 6, 'doDatabase(): result: %s' %(result) )
133                return result
134
135        def getNodeId( self, hostname ):
136
137                id = self.getDatabase( "SELECT node_id FROM nodes WHERE node_hostname = '%s'" %hostname )
138
139                if len( id ) > 0:
140
141                        id = id[0][0]
142
143                        return id
144                else:
145                        return None
146
147        def getNodeIds( self, hostnames ):
148
149                ids = [ ]
150
151                for node in hostnames:
152
153                        id = self.getNodeId( node )
154
155                        if id:
156                                ids.append( id )
157
158                return ids
159
160        def getJobId( self, jobid ):
161
162                id = self.getDatabase( "SELECT job_id FROM jobs WHERE job_id = '%s'" %jobid )
163
164                if id:
165                        id = id[0][0]
166
167                        return id
168                else:
169                        return None
170
171        def addJob( self, job_id, jobattrs ):
172
173                if not self.getJobId( job_id ):
174
175                        self.mutateJob( 'insert', job_id, jobattrs ) 
176                else:
177                        self.mutateJob( 'update', job_id, jobattrs )
178
179        def mutateJob( self, action, job_id, jobattrs ):
180
181                job_values = [ 'name', 'queue', 'owner', 'requested_time', 'requested_memory', 'ppn', 'status', 'start_timestamp', 'stop_timestamp' ]
182
183                insert_col_str = 'job_id'
184                insert_val_str = "'%s'" %job_id
185                update_str = None
186
187                debug_msg( 6, 'mutateJob(): %s %s' %(action,job_id))
188
189                for valname, value in jobattrs.items():
190
191                        if valname in job_values and value:
192
193                                column_name = 'job_' + valname
194
195                                if action == 'insert':
196
197                                        if not insert_col_str:
198                                                insert_col_str = column_name
199                                        else:
200                                                insert_col_str = insert_col_str + ',' + column_name
201
202                                        if not insert_val_str:
203                                                insert_val_str = value
204                                        else:
205                                                insert_val_str = insert_val_str + ",'%s'" %value
206
207                                elif action == 'update':
208                                       
209                                        if not update_str:
210                                                update_str = "%s='%s'" %(column_name, value)
211                                        else:
212                                                update_str = update_str + ",%s='%s'" %(column_name, value)
213
214                        elif valname == 'nodes' and value:
215
216                                self.addNodes( value )
217                                node_list = value
218
219                if action == 'insert':
220
221                        self.setDatabase( "INSERT INTO jobs ( %s ) VALUES ( %s )" %( insert_col_str, insert_val_str ) )
222                        #ids = self.getNodeIds( node_list )
223
224                        #self.addJobNodes( job_id, ids )
225                elif action == 'update':
226
227                        self.setDatabase( "UPDATE jobs SET %s WHERE job_id=%s" %(update_str, job_id) )
228
229        def addNodes( self, hostnames ):
230
231                for node in hostnames:
232
233                        id = self.getNodeId( node )
234       
235                        if not id:
236                                self.setDatabase( "INSERT INTO nodes ( node_hostname ) VALUES ( '%s' )" %node )
237
238        def addJobNodes( self, jobid, nodes ):
239
240                for node in nodes:
241                        self.addJobNode( jobid, node )
242
243        def addJobNode( self, jobid, nodeid ):
244
245                self.setDatabase( "INSERT INTO job_nodes (job_id,node_id) VALUES ( %s,%s )" %(jobid, nodeid) )
246
247        def storeJobInfo( self, jobid, jobattrs ):
248
249                self.addJob( jobid, jobattrs )
250
251class RRDMutator:
252        """A class for performing RRD mutations"""
253
254        binary = '/usr/bin/rrdtool'
255
256        def __init__( self, binary=None ):
257                """Set alternate binary if supplied"""
258
259                if binary:
260                        self.binary = binary
261
262        def create( self, filename, args ):
263                """Create a new rrd with args"""
264
265                return self.perform( 'create', '"' + filename + '"', args )
266
267        def update( self, filename, args ):
268                """Update a rrd with args"""
269
270                return self.perform( 'update', '"' + filename + '"', args )
271
272        def grabLastUpdate( self, filename ):
273                """Determine the last update time of filename rrd"""
274
275                last_update = 0
276
277                debug_msg( 8, self.binary + ' info "' + filename + '"' )
278
279                for line in os.popen( self.binary + ' info "' + filename + '"' ).readlines():
280
281                        if line.find( 'last_update') != -1:
282
283                                last_update = line.split( ' = ' )[1]
284
285                if last_update:
286                        return last_update
287                else:
288                        return 0
289
290        def perform( self, action, filename, args ):
291                """Perform action on rrd filename with args"""
292
293                arg_string = None
294
295                if type( args ) is not ListType:
296                        debug_msg( 8, 'Arguments needs to be of type List' )
297                        return 1
298
299                for arg in args:
300
301                        if not arg_string:
302
303                                arg_string = arg
304                        else:
305                                arg_string = arg_string + ' ' + arg
306
307                debug_msg( 8, self.binary + ' ' + action + ' ' + filename + ' ' + arg_string  )
308
309                for line in os.popen( self.binary + ' ' + action + ' ' + filename + ' ' + arg_string ).readlines():
310
311                        if line.find( 'ERROR' ) != -1:
312
313                                error_msg = string.join( line.split( ' ' )[1:] )
314                                debug_msg( 8, error_msg )
315                                return 1
316
317                return 0
318
319class XMLProcessor:
320        """Skeleton class for XML processor's"""
321
322        def daemon( self ):
323                """Run as daemon forever"""
324
325                # Fork the first child
326                #
327                pid = os.fork()
328
329                if pid > 0:
330
331                        sys.exit(0)  # end parent
332
333                # creates a session and sets the process group ID
334                #
335                os.setsid()
336
337                # Fork the second child
338                #
339                pid = os.fork()
340
341                if pid > 0:
342
343                        sys.exit(0)  # end parent
344
345                # Go to the root directory and set the umask
346                #
347                os.chdir('/')
348                os.umask(0)
349
350                sys.stdin.close()
351                sys.stdout.close()
352                sys.stderr.close()
353
354                os.open('/dev/null', 0)
355                os.dup(0)
356                os.dup(0)
357
358                self.run()
359
360        def run( self ):
361                """Do main processing of XML here"""
362
363                pass
364
365class TorqueXMLProcessor( XMLProcessor ):
366        """Main class for processing XML and acting with it"""
367
368        def __init__( self ):
369                """Setup initial XML connection and handlers"""
370
371                self.myXMLGatherer = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] ) 
372                self.myXMLSource = self.myXMLGatherer.getFileObject()
373                self.myXMLHandler = TorqueXMLHandler()
374                self.myXMLError = XMLErrorHandler()
375                self.config = GangliaConfigParser( GMETAD_CONF )
376
377        def run( self ):
378                """Main XML processing"""
379
380                debug_msg( 5, printTime() + ' - torquexmlthread(): started.' )
381
382                while( 1 ):
383
384                        self.myXMLSource = self.myXMLGatherer.getFileObject()
385                        debug_msg( 1, printTime() + ' - torquexmlthread(): Parsing..' )
386                        xml.sax.parse( self.myXMLSource, self.myXMLHandler, self.myXMLError )
387                        debug_msg( 1, printTime() + ' - torquexmlthread(): Done parsing.' )
388                        debug_msg( 1, printTime() + ' - torquexmlthread(): Sleeping.. (%ss)' %(str( self.config.getLowestInterval() ) ) )
389                        time.sleep( self.config.getLowestInterval() )
390
391class TorqueXMLHandler( xml.sax.handler.ContentHandler ):
392        """Parse Torque's jobinfo XML from our plugin"""
393
394        jobAttrs = { }
395        jobs_to_store = [ ]
396
397        def __init__( self ):
398
399                self.ds = DataSQLStore( TOGA_SQL_DBASE.split( '/' )[0], TOGA_SQL_DBASE.split( '/' )[1] )
400
401        def startElement( self, name, attrs ):
402                """
403                This XML will be all gmetric XML
404                so there will be no specific start/end element
405                just one XML statement with all info
406                """
407               
408                heartbeat = 0
409               
410                jobinfo = { }
411
412                if name == 'METRIC':
413
414                        metricname = attrs.get( 'NAME', "" )
415
416                        if metricname == 'TOGA-HEARTBEAT':
417                                self.heartbeat = attrs.get( 'VAL', "" )
418
419                        elif metricname.find( 'TOGA-JOB' ) != -1:
420
421                                job_id = metricname.split( 'TOGA-JOB-' )[1]
422                                val = attrs.get( 'VAL', "" )
423
424                                check_change = 0
425
426                                if self.jobAttrs.has_key( job_id ):
427                                        check_change = 1
428
429                                valinfo = val.split( ' ' )
430
431                                for myval in valinfo:
432
433                                        if len( myval.split( '=' ) ) > 1:
434
435                                                valname = myval.split( '=' )[0]
436                                                value = myval.split( '=' )[1]
437
438                                                if valname == 'nodes':
439                                                        value = value.split( ';' )
440
441                                                jobinfo[ valname ] = value
442
443                                if check_change:
444                                        if self.jobinfoChanged( self.jobAttrs, job_id, jobinfo ):
445                                                self.jobAttrs[ job_id ] = self.setJobAttrs( self.jobAttrs[ job_id ], jobinfo )
446                                                if not job_id in self.jobs_to_store:
447                                                        self.jobs_to_store.append( job_id )
448
449                                                debug_msg( 0, 'jobinfo for job %s has changed' %job_id )
450                                else:
451                                        self.jobAttrs[ job_id ] = jobinfo
452
453                                        if not job_id in self.jobs_to_store:
454                                                self.jobs_to_store.append( job_id )
455
456                                        debug_msg( 0, 'jobinfo for job %s has changed' %job_id )
457                                       
458        def endDocument( self ):
459                """When all metrics have gone, check if any jobs have finished"""
460
461                for jobid, jobinfo in self.jobAttrs.items():
462
463                        # This is an old job, not in current jobinfo list anymore
464                        # it must have finished, since we _did_ get a new heartbeat
465                        #
466                        if jobinfo['reported'] < self.heartbeat and jobinfo['status'] == 'R' and jobid not in self.jobs_to_store:
467
468                                self.jobAttrs[ jobid ]['status'] = 'F'
469                                self.jobAttrs[ jobid ]['stop_timestamp'] = str( int( jobinfo['reported'] ) + int( jobinfo['poll_interval'] ) )
470                                if not jobid in self.jobs_to_store:
471                                        self.jobs_to_store.append( jobid )
472
473                debug_msg( 1, printTime() + ' - torquexmlthread(): Storing..' )
474
475                for jobid in self.jobs_to_store:
476                        self.ds.storeJobInfo( jobid, self.jobAttrs[ jobid ] )   
477
478                debug_msg( 1, printTime() + ' - torquexmlthread(): Done storing.' )
479
480                self.jobs_to_store = [ ]
481
482        def setJobAttrs( self, old, new ):
483                """
484                Set new job attributes in old, but not lose existing fields
485                if old attributes doesn't have those
486                """
487
488                for valname, value in new.items():
489                        old[ valname ] = value
490
491                return old
492               
493
494        def jobinfoChanged( self, jobattrs, jobid, jobinfo ):
495                """
496                Check if jobinfo has changed from jobattrs[jobid]
497                if it's report time is bigger than previous one
498                and it is report time is recent (equal to heartbeat)
499                """
500
501                ignore_changes = [ 'reported' ]
502
503                if jobattrs.has_key( jobid ):
504
505                        for valname, value in jobinfo.items():
506
507                                if valname not in ignore_changes:
508
509                                        if jobattrs[ jobid ].has_key( valname ):
510
511                                                if value != jobattrs[ jobid ][ valname ]:
512
513                                                        if jobinfo['reported'] > jobattrs[ jobid ][ 'reported' ] and jobinfo['reported'] == self.heartbeat:
514                                                                return 1
515
516                                        else:
517                                                return 1
518
519                return 0
520
521class GangliaXMLHandler( xml.sax.handler.ContentHandler ):
522        """Parse Ganglia's XML"""
523
524        def __init__( self, config ):
525                """Setup initial variables and gather info on existing rrd archive"""
526
527                self.config = config
528                self.clusters = { }
529                debug_msg( 0, printTime() + ' - Checking existing toga rrd archive..' )
530                self.gatherClusters()
531                debug_msg( 0, printTime() + ' - Check done.' )
532
533        def gatherClusters( self ):
534                """Find all existing clusters in archive dir"""
535
536                archive_dir = check_dir(ARCHIVE_PATH)
537
538                hosts = [ ]
539
540                if os.path.exists( archive_dir ):
541
542                        dirlist = os.listdir( archive_dir )
543
544                        for item in dirlist:
545
546                                clustername = item
547
548                                if not self.clusters.has_key( clustername ) and clustername in ARCHIVE_DATASOURCES:
549
550                                        self.clusters[ clustername ] = RRDHandler( self.config, clustername )
551
552        def startElement( self, name, attrs ):
553                """Memorize appropriate data from xml start tags"""
554
555                if name == 'GANGLIA_XML':
556
557                        self.XMLSource = attrs.get( 'SOURCE', "" )
558                        self.gangliaVersion = attrs.get( 'VERSION', "" )
559
560                        debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
561
562                elif name == 'GRID':
563
564                        self.gridName = attrs.get( 'NAME', "" )
565                        self.time = attrs.get( 'LOCALTIME', "" )
566
567                        debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
568
569                elif name == 'CLUSTER':
570
571                        self.clusterName = attrs.get( 'NAME', "" )
572                        self.time = attrs.get( 'LOCALTIME', "" )
573
574                        if not self.clusters.has_key( self.clusterName ) and self.clusterName in ARCHIVE_DATASOURCES:
575
576                                self.clusters[ self.clusterName ] = RRDHandler( self.config, self.clusterName )
577
578                                debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
579
580                elif name == 'HOST' and self.clusterName in ARCHIVE_DATASOURCES:     
581
582                        self.hostName = attrs.get( 'NAME', "" )
583                        self.hostIp = attrs.get( 'IP', "" )
584                        self.hostReported = attrs.get( 'REPORTED', "" )
585
586                        debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
587
588                elif name == 'METRIC' and self.clusterName in ARCHIVE_DATASOURCES:
589
590                        type = attrs.get( 'TYPE', "" )
591
592                        if type not in UNSUPPORTED_ARCHIVE_TYPES:
593
594                                myMetric = { }
595                                myMetric['name'] = attrs.get( 'NAME', "" )
596                                myMetric['val'] = attrs.get( 'VAL', "" )
597                                myMetric['time'] = self.hostReported
598
599                                self.clusters[ self.clusterName ].memMetric( self.hostName, myMetric )
600
601                                debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
602
603        def storeMetrics( self ):
604                """Store metrics of each cluster rrd handler"""
605
606                for clustername, rrdh in self.clusters.items():
607
608                        ret = rrdh.storeMetrics()
609
610                        if ret:
611                                debug_msg( 9, 'An error occured while storing metrics for cluster %s' %clustername )
612                                return 1
613
614                return 0
615
616class XMLErrorHandler( xml.sax.handler.ErrorHandler ):
617
618        def error( self, exception ):
619                """Recoverable error"""
620
621                debug_msg( 0, 'Recoverable error ' + str( exception ) )
622
623        def fatalError( self, exception ):
624                """Non-recoverable error"""
625
626                exception_str = str( exception )
627
628                # Ignore 'no element found' errors
629                if exception_str.find( 'no element found' ) != -1:
630                        debug_msg( 1, 'No XML data found: probably socket not (re)connected.' )
631                        return 0
632
633                debug_msg( 0, 'Non-recoverable error ' + str( exception ) )
634                sys.exit( 1 )
635
636        def warning( self, exception ):
637                """Warning"""
638
639                debug_msg( 0, 'Warning ' + str( exception ) )
640
641class XMLGatherer:
642        """Setup a connection and file object to Ganglia's XML"""
643
644        s = None
645        fd = None
646
647        def __init__( self, host, port ):
648                """Store host and port for connection"""
649
650                self.host = host
651                self.port = port
652                self.connect()
653                self.makeFileDescriptor()
654
655        def connect( self ):
656                """Setup connection to XML source"""
657
658                for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ):
659
660                        af, socktype, proto, canonname, sa = res
661
662                        try:
663
664                                self.s = socket.socket( af, socktype, proto )
665
666                        except socket.error, msg:
667
668                                self.s = None
669                                continue
670
671                        try:
672
673                                self.s.connect( sa )
674
675                        except socket.error, msg:
676
677                                self.disconnect()
678                                continue
679
680                        break
681
682                if self.s is None:
683
684                        debug_msg( 0, 'Could not open socket' )
685                        sys.exit( 1 )
686
687        def disconnect( self ):
688                """Close socket"""
689
690                if self.s:
691                        self.s.shutdown( 2 )
692                        self.s.close()
693                        self.s = None
694
695        def __del__( self ):
696                """Kill the socket before we leave"""
697
698                self.disconnect()
699
700        def reconnect( self ):
701                """Reconnect"""
702
703                if self.s:
704                        self.disconnect()
705
706                self.connect()
707
708        def makeFileDescriptor( self ):
709                """Make file descriptor that points to our socket connection"""
710
711                self.reconnect()
712
713                if self.s:
714                        self.fd = self.s.makefile( 'r' )
715
716        def getFileObject( self ):
717                """Connect, and return a file object"""
718
719                self.makeFileDescriptor()
720
721                if self.fd:
722                        return self.fd
723
724class GangliaXMLProcessor( XMLProcessor ):
725        """Main class for processing XML and acting with it"""
726
727        def __init__( self ):
728                """Setup initial XML connection and handlers"""
729
730                self.config = GangliaConfigParser( GMETAD_CONF )
731
732                self.myXMLGatherer = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] ) 
733                self.myXMLSource = self.myXMLGatherer.getFileObject()
734                self.myXMLHandler = GangliaXMLHandler( self.config )
735                self.myXMLError = XMLErrorHandler()
736
737        def run( self ):
738                """Main XML processing; start a xml and storethread"""
739
740                xmlthread = threading.Thread( None, self.processXML, 'xmlthread' )
741                storethread = threading.Thread( None, self.storeMetrics, 'storethread' )
742
743                while( 1 ):
744
745                        if not xmlthread.isAlive():
746                                # Gather XML at the same interval as gmetad
747
748                                # threaded call to: self.processXML()
749                                #
750                                xmlthread = threading.Thread( None, self.processXML, 'xmlthread' )
751                                xmlthread.start()
752
753                        if not storethread.isAlive():
754                                # Store metrics every .. sec
755
756                                # threaded call to: self.storeMetrics()
757                                #
758                                storethread = threading.Thread( None, self.storeMetrics, 'storethread' )
759                                storethread.start()
760               
761                        # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway
762                        time.sleep( 1 ) 
763
764        def storeMetrics( self ):
765                """Store metrics retained in memory to disk"""
766
767                debug_msg( 7, printTime() + ' - storethread(): started.' )
768
769                # Store metrics somewhere between every 360 and 640 seconds
770                #
771                STORE_INTERVAL = random.randint( 360, 640 )
772
773                storethread = threading.Thread( None, self.storeThread, 'storemetricthread' )
774                storethread.start()
775
776                debug_msg( 7, printTime() + ' - storethread(): Sleeping.. (%ss)' %STORE_INTERVAL )
777                time.sleep( STORE_INTERVAL )
778                debug_msg( 7, printTime() + ' - storethread(): Done sleeping.' )
779
780                if storethread.isAlive():
781
782                        debug_msg( 7, printTime() + ' - storethread(): storemetricthread() still running, waiting to finish..' )
783                        storethread.join( STORE_TIMEOUT ) # Maximum time is for storing thread to finish
784                        debug_msg( 7, printTime() + ' - storethread(): Done waiting.' )
785
786                debug_msg( 7, printTime() + ' - storethread(): finished.' )
787
788                return 0
789
790        def storeThread( self ):
791                """Actual metric storing thread"""
792
793                debug_msg( 1, printTime() + ' - storemetricthread(): started.' )
794                debug_msg( 1, printTime() + ' - storemetricthread(): Storing data..' )
795                ret = self.myXMLHandler.storeMetrics()
796                debug_msg( 1, printTime() + ' - storemetricthread(): Done storing.' )
797                debug_msg( 1, printTime() + ' - storemetricthread(): finished.' )
798               
799                return ret
800
801        def processXML( self ):
802                """Process XML"""
803
804                debug_msg( 1, printTime() + ' - xmlthread(): started.' )
805
806                parsethread = threading.Thread( None, self.parseThread, 'parsethread' )
807                parsethread.start()
808
809                debug_msg( 1, printTime() + ' - xmlthread(): Sleeping.. (%ss)' %self.config.getLowestInterval() )
810                time.sleep( float( self.config.getLowestInterval() ) ) 
811                debug_msg( 1, printTime() + ' - xmlthread(): Done sleeping.' )
812
813                if parsethread.isAlive():
814
815                        debug_msg( 1, printTime() + ' - xmlthread(): parsethread() still running, waiting to finish..' )
816                        parsethread.join( PARSE_TIMEOUT ) # Maximum time for XML thread to finish
817                        debug_msg( 7, printTime() + ' - xmlthread(): Done waiting.' )
818
819                debug_msg( 1, printTime() + ' - xmlthread(): finished.' )
820
821                return 0
822
823        def parseThread( self ):
824                """Actual parsing thread"""
825
826                debug_msg( 1, printTime() + ' - parsethread(): started.' )
827                debug_msg( 1, printTime() + ' - parsethread(): Parsing XML..' )
828                self.myXMLSource = self.myXMLGatherer.getFileObject()
829                ret = xml.sax.parse( self.myXMLSource, self.myXMLHandler, self.myXMLError )
830                debug_msg( 1, printTime() + ' - parsethread(): Done parsing.' )
831                debug_msg( 1, printTime() + ' - parsethread(): finished.' )
832
833                return ret
834
835class GangliaConfigParser:
836
837        sources = [ ]
838
839        def __init__( self, config ):
840                """Parse some stuff from our gmetad's config, such as polling interval"""
841
842                self.config = config
843                self.parseValues()
844
845        def parseValues( self ):
846                """Parse certain values from gmetad.conf"""
847
848                readcfg = open( self.config, 'r' )
849
850                for line in readcfg.readlines():
851
852                        if line.count( '"' ) > 1:
853
854                                if line.find( 'data_source' ) != -1 and line[0] != '#':
855
856                                        source = { }
857                                        source['name'] = line.split( '"' )[1]
858                                        source_words = line.split( '"' )[2].split( ' ' )
859
860                                        for word in source_words:
861
862                                                valid_interval = 1
863
864                                                for letter in word:
865
866                                                        if letter not in string.digits:
867
868                                                                valid_interval = 0
869
870                                                if valid_interval and len(word) > 0:
871
872                                                        source['interval'] = word
873                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
874       
875                                        # No interval found, use Ganglia's default     
876                                        if not source.has_key( 'interval' ):
877                                                source['interval'] = 15
878                                                debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
879
880                                        self.sources.append( source )
881
882        def getInterval( self, source_name ):
883                """Return interval for source_name"""
884
885                for source in self.sources:
886
887                        if source['name'] == source_name:
888
889                                return source['interval']
890
891                return None
892
893        def getLowestInterval( self ):
894                """Return the lowest interval of all clusters"""
895
896                lowest_interval = 0
897
898                for source in self.sources:
899
900                        if not lowest_interval or source['interval'] <= lowest_interval:
901
902                                lowest_interval = source['interval']
903
904                # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays
905                if lowest_interval:
906                        return lowest_interval
907                else:
908                        return 15
909
910class RRDHandler:
911        """Class for handling RRD activity"""
912
913        myMetrics = { }
914        lastStored = { }
915        timeserials = { }
916        slot = None
917
918        def __init__( self, config, cluster ):
919                """Setup initial variables"""
920
921                self.block = 0
922                self.cluster = cluster
923                self.config = config
924                self.slot = threading.Lock()
925                self.rrdm = RRDMutator()
926                self.gatherLastUpdates()
927
928        def gatherLastUpdates( self ):
929                """Populate the lastStored list, containing timestamps of all last updates"""
930
931                cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster )
932
933                hosts = [ ]
934
935                if os.path.exists( cluster_dir ):
936
937                        dirlist = os.listdir( cluster_dir )
938
939                        for dir in dirlist:
940
941                                hosts.append( dir )
942
943                for host in hosts:
944
945                        host_dir = cluster_dir + '/' + host
946                        dirlist = os.listdir( host_dir )
947
948                        for dir in dirlist:
949
950                                if not self.timeserials.has_key( host ):
951
952                                        self.timeserials[ host ] = [ ]
953
954                                self.timeserials[ host ].append( dir )
955
956                        last_serial = self.getLastRrdTimeSerial( host )
957                        if last_serial:
958
959                                metric_dir = cluster_dir + '/' + host + '/' + last_serial
960                                if os.path.exists( metric_dir ):
961
962                                        dirlist = os.listdir( metric_dir )
963
964                                        for file in dirlist:
965
966                                                metricname = file.split( '.rrd' )[0]
967
968                                                if not self.lastStored.has_key( host ):
969
970                                                        self.lastStored[ host ] = { }
971
972                                                self.lastStored[ host ][ metricname ] = self.rrdm.grabLastUpdate( metric_dir + '/' + file )
973
974        def getClusterName( self ):
975                """Return clustername"""
976
977                return self.cluster
978
979        def memMetric( self, host, metric ):
980                """Store metric from host in memory"""
981
982                if self.myMetrics.has_key( host ):
983
984                        if self.myMetrics[ host ].has_key( metric['name'] ):
985
986                                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
987
988                                        if mymetric['time'] == metric['time']:
989
990                                                # Allready have this metric, abort
991                                                return 1
992                        else:
993                                self.myMetrics[ host ][ metric['name'] ] = [ ]
994                else:
995                        self.myMetrics[ host ] = { }
996                        self.myMetrics[ host ][ metric['name'] ] = [ ]
997
998                # Push new metric onto stack
999                # atomic code; only 1 thread at a time may access the stack
1000
1001                # <ATOMIC>
1002                #
1003                self.slot.acquire()
1004
1005                self.myMetrics[ host ][ metric['name'] ].append( metric )
1006
1007                self.slot.release()
1008                #
1009                # </ATOMIC>
1010
1011        def makeUpdateList( self, host, metriclist ):
1012                """
1013                Make a list of update values for rrdupdate
1014                but only those that we didn't store before
1015                """
1016
1017                update_list = [ ]
1018                metric = None
1019
1020                while len( metriclist ) > 0:
1021
1022                        metric = metriclist.pop( 0 )
1023
1024                        if self.checkStoreMetric( host, metric ):
1025                                update_list.append( '%s:%s' %( metric['time'], metric['val'] ) )
1026
1027                return update_list
1028
1029        def checkStoreMetric( self, host, metric ):
1030                """Check if supplied metric if newer than last one stored"""
1031
1032                if self.lastStored.has_key( host ):
1033
1034                        if self.lastStored[ host ].has_key( metric['name'] ):
1035
1036                                if metric['time'] <= self.lastStored[ host ][ metric['name'] ]:
1037
1038                                        # This is old
1039                                        return 0
1040
1041                return 1
1042
1043        def memLastUpdate( self, host, metricname, metriclist ):
1044                """
1045                Memorize the time of the latest metric from metriclist
1046                but only if it wasn't allready memorized
1047                """
1048
1049                if not self.lastStored.has_key( host ):
1050                        self.lastStored[ host ] = { }
1051
1052                last_update_time = 0
1053
1054                for metric in metriclist:
1055
1056                        if metric['name'] == metricname:
1057
1058                                if metric['time'] > last_update_time:
1059
1060                                        last_update_time = metric['time']
1061
1062                if self.lastStored[ host ].has_key( metricname ):
1063                       
1064                        if last_update_time <= self.lastStored[ host ][ metricname ]:
1065                                return 1
1066
1067                self.lastStored[ host ][ metricname ] = last_update_time
1068
1069        def storeMetrics( self ):
1070                """
1071                Store all metrics from memory to disk
1072                and do it to the RRD's in appropriate timeperiod directory
1073                """
1074
1075                for hostname, mymetrics in self.myMetrics.items():     
1076
1077                        for metricname, mymetric in mymetrics.items():
1078
1079                                metrics_to_store = [ ]
1080
1081                                # Pop metrics from stack for storing until none is left
1082                                # atomic code: only 1 thread at a time may access myMetrics
1083
1084                                # <ATOMIC>
1085                                #
1086                                self.slot.acquire() 
1087
1088                                while len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1089
1090                                        if len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1091                                                metrics_to_store.append( self.myMetrics[ hostname ][ metricname ].pop( 0 ) )
1092
1093                                self.slot.release()
1094                                #
1095                                # </ATOMIC>
1096
1097                                # Create a mapping table, each metric to the period where it should be stored
1098                                #
1099                                metric_serial_table = self.determineSerials( hostname, metricname, metrics_to_store )
1100
1101                                update_rets = [ ]
1102
1103                                for period, pmetric in metric_serial_table.items():
1104
1105                                        self.createCheck( hostname, metricname, period )       
1106
1107                                        update_ret = self.update( hostname, metricname, period, pmetric )
1108
1109                                        if update_ret == 0:
1110
1111                                                debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
1112                                        else:
1113                                                debug_msg( 9, 'metric update failed' )
1114
1115                                        update_rets.append( update_ret )
1116
1117                                if not (1) in update_rets:
1118
1119                                        self.memLastUpdate( hostname, metricname, metrics_to_store )
1120
1121        def makeTimeSerial( self ):
1122                """Generate a time serial. Seconds since epoch"""
1123
1124                # Seconds since epoch
1125                mytime = int( time.time() )
1126
1127                return mytime
1128
1129        def makeRrdPath( self, host, metricname, timeserial ):
1130                """Make a RRD location/path and filename"""
1131
1132                rrd_dir = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
1133                rrd_file = '%s/%s.rrd' %( rrd_dir, metricname )
1134
1135                return rrd_dir, rrd_file
1136
1137        def getLastRrdTimeSerial( self, host ):
1138                """Find the last timeserial (directory) for this host"""
1139
1140                newest_timeserial = 0
1141
1142                for dir in self.timeserials[ host ]:
1143
1144                        valid_dir = 1
1145
1146                        for letter in dir:
1147                                if letter not in string.digits:
1148                                        valid_dir = 0
1149
1150                        if valid_dir:
1151                                timeserial = dir
1152                                if timeserial > newest_timeserial:
1153                                        newest_timeserial = timeserial
1154
1155                if newest_timeserial:
1156                        return newest_timeserial
1157                else:
1158                        return 0
1159
1160        def determinePeriod( self, host, check_serial ):
1161                """Determine to which period (directory) this time(serial) belongs"""
1162
1163                period_serial = 0
1164
1165                if self.timeserials.has_key( host ):
1166
1167                        for serial in self.timeserials[ host ]:
1168
1169                                if check_serial >= serial and period_serial < serial:
1170
1171                                        period_serial = serial
1172
1173                return period_serial
1174
1175        def determineSerials( self, host, metricname, metriclist ):
1176                """
1177                Determine the correct serial and corresponding rrd to store
1178                for a list of metrics
1179                """
1180
1181                metric_serial_table = { }
1182
1183                for metric in metriclist:
1184
1185                        if metric['name'] == metricname:
1186
1187                                period = self.determinePeriod( host, metric['time'] )   
1188
1189                                archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60)
1190
1191                                if (int( metric['time'] ) - int( period ) ) > archive_secs:
1192
1193                                        # This one should get it's own new period
1194                                        period = metric['time']
1195
1196                                        if not self.timeserials.has_key( host ):
1197                                                self.timeserials[ host ] = [ ]
1198
1199                                        self.timeserials[ host ].append( period )
1200
1201                                if not metric_serial_table.has_key( period ):
1202
1203                                        metric_serial_table[ period ] = [ ]
1204
1205                                metric_serial_table[ period ].append( metric )
1206
1207                return metric_serial_table
1208
1209        def createCheck( self, host, metricname, timeserial ):
1210                """Check if an rrd allready exists for this metric, create if not"""
1211
1212                debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1213               
1214                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
1215
1216                if not os.path.exists( rrd_dir ):
1217
1218                        try:
1219                                os.makedirs( rrd_dir )
1220
1221                        except OSError, msg:
1222
1223                                if msg.find( 'File exists' ) != -1:
1224
1225                                        # Ignore exists errors
1226                                        pass
1227
1228                                else:
1229
1230                                        print msg
1231                                        return
1232
1233                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
1234
1235                if not os.path.exists( rrd_file ):
1236
1237                        interval = self.config.getInterval( self.cluster )
1238                        heartbeat = 8 * int( interval )
1239
1240                        params = [ ]
1241
1242                        params.append( '--step' )
1243                        params.append( str( interval ) )
1244
1245                        params.append( '--start' )
1246                        params.append( str( int( timeserial ) - 1 ) )
1247
1248                        params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat )
1249                        params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) )
1250
1251                        self.rrdm.create( str(rrd_file), params )
1252
1253                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
1254
1255        def update( self, host, metricname, timeserial, metriclist ):
1256                """
1257                Update rrd file for host with metricname
1258                in directory timeserial with metriclist
1259                """
1260
1261                debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1262
1263                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
1264
1265                update_list = self.makeUpdateList( host, metriclist )
1266
1267                if len( update_list ) > 0:
1268                        ret = self.rrdm.update( str(rrd_file), update_list )
1269
1270                        if ret:
1271                                return 1
1272               
1273                        debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) )
1274
1275                return 0
1276
1277def main():
1278        """Program startup"""
1279
1280        myTProcessor = TorqueXMLProcessor()
1281        myGProcessor = GangliaXMLProcessor()
1282
1283        if DAEMONIZE:
1284                torquexmlthread = threading.Thread( None, myTProcessor.daemon, 'tprocxmlthread' )
1285                gangliaxmlthread = threading.Thread( None, myGProcessor.daemon, 'gprocxmlthread' )
1286        else:
1287                torquexmlthread = threading.Thread( None, myTProcessor.run, 'tprocxmlthread' )
1288                gangliaxmlthread = threading.Thread( None, myGProcessor.run, 'gprocxmlthread' )
1289
1290        torquexmlthread.start()
1291        gangliaxmlthread.start()
1292
1293# Global functions
1294
1295def check_dir( directory ):
1296        """Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"""
1297
1298        if directory[-1] == '/':
1299                directory = directory[:-1]
1300
1301        return directory
1302
1303def debug_msg( level, msg ):
1304        """Only print msg if it is not below our debug level"""
1305
1306        if (DEBUG_LEVEL >= level):
1307                sys.stderr.write( msg + '\n' )
1308
1309def printTime( ):
1310        """Print current time in human readable format"""
1311
1312        return time.strftime("%a %d %b %Y %H:%M:%S")
1313
1314# Ooohh, someone started me! Let's go..
1315if __name__ == '__main__':
1316        main()
Note: See TracBrowser for help on using the repository browser.