source: trunk/daemon/togad.py @ 99

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

daemon/togad.py:

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