source: trunk/daemon/togad.py @ 186

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

daemon/togad.py:

  • Delete jobs from memory after written to dbase

plugin/togap.py:

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