source: trunk/daemon/togad.py @ 183

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

daemon/togad.py:

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