source: trunk/daemon/togad.py @ 100

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

daemon/togad.py:

  • Ignore 'E' status updates/changes for a job

From pbs's docs:
"E - Job is exiting after having run"

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