source: trunk/daemon/togad.py @ 84

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

daemon/togad.py:

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