source: trunk/daemon/togad.py @ 163

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

daemon/togad.py:

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