source: trunk/daemon/togad.py @ 151

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

daemon/togad.py:

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