source: trunk/daemon/togad.py @ 191

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

daemon/togad.py:

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