source: trunk/daemon/togad.py @ 182

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

daemon/togad.py:

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