source: trunk/daemon/togad.py @ 176

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

daemon/togad.py:

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