source: trunk/daemon/togad.py @ 173

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

daemon/togad.py:

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