source: trunk/daemon/togad.py @ 98

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

daemon/togad.py:

  • Misc bugfix.
  • Now entrys to 'job_nodes' table are created again
File size: 31.4 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                for valname, value in jobattrs.items():
190
191                        if valname in job_values and value != '':
192
193                                column_name = 'job_' + valname
194
195                                if action == 'insert':
196
197                                        if not insert_col_str:
198                                                insert_col_str = column_name
199                                        else:
200                                                insert_col_str = insert_col_str + ',' + column_name
201
202                                        if not insert_val_str:
203                                                insert_val_str = value
204                                        else:
205                                                insert_val_str = insert_val_str + ",'%s'" %value
206
207                                elif action == 'update':
208                                       
209                                        if not update_str:
210                                                update_str = "%s='%s'" %(column_name, value)
211                                        else:
212                                                update_str = update_str + ",%s='%s'" %(column_name, value)
213
214                        elif valname == 'nodes' and value:
215
216                                ids = self.addNodes( value )
217                                node_list = value
218
219                if action == 'insert':
220
221                        self.setDatabase( "INSERT INTO jobs ( %s ) VALUES ( %s )" %( insert_col_str, insert_val_str ) )
222                        self.addJobNodes( job_id, ids )
223
224                elif action == 'update':
225
226                        self.setDatabase( "UPDATE jobs SET %s WHERE job_id=%s" %(update_str, job_id) )
227
228        def addNodes( self, hostnames ):
229
230                ids = [ ]
231
232                for node in hostnames:
233
234                        id = self.getNodeId( node )
235       
236                        if not id:
237                                self.setDatabase( "INSERT INTO nodes ( node_hostname ) VALUES ( '%s' )" %node )
238                                id = self.getNodeId( node )
239
240                        ids.append( id )
241
242                return ids
243
244        def addJobNodes( self, jobid, nodes ):
245
246                for node in nodes:
247                        self.addJobNode( jobid, node )
248
249        def addJobNode( self, jobid, nodeid ):
250
251                self.setDatabase( "INSERT INTO job_nodes (job_id,node_id) VALUES ( %s,%s )" %(jobid, nodeid) )
252
253        def storeJobInfo( self, jobid, jobattrs ):
254
255                self.addJob( jobid, jobattrs )
256
257class RRDMutator:
258        """A class for performing RRD mutations"""
259
260        binary = '/usr/bin/rrdtool'
261
262        def __init__( self, binary=None ):
263                """Set alternate binary if supplied"""
264
265                if binary:
266                        self.binary = binary
267
268        def create( self, filename, args ):
269                """Create a new rrd with args"""
270
271                return self.perform( 'create', '"' + filename + '"', args )
272
273        def update( self, filename, args ):
274                """Update a rrd with args"""
275
276                return self.perform( 'update', '"' + filename + '"', args )
277
278        def grabLastUpdate( self, filename ):
279                """Determine the last update time of filename rrd"""
280
281                last_update = 0
282
283                debug_msg( 8, self.binary + ' info "' + filename + '"' )
284
285                for line in os.popen( self.binary + ' info "' + filename + '"' ).readlines():
286
287                        if line.find( 'last_update') != -1:
288
289                                last_update = line.split( ' = ' )[1]
290
291                if last_update:
292                        return last_update
293                else:
294                        return 0
295
296        def perform( self, action, filename, args ):
297                """Perform action on rrd filename with args"""
298
299                arg_string = None
300
301                if type( args ) is not ListType:
302                        debug_msg( 8, 'Arguments needs to be of type List' )
303                        return 1
304
305                for arg in args:
306
307                        if not arg_string:
308
309                                arg_string = arg
310                        else:
311                                arg_string = arg_string + ' ' + arg
312
313                debug_msg( 8, self.binary + ' ' + action + ' ' + filename + ' ' + arg_string  )
314
315                for line in os.popen( self.binary + ' ' + action + ' ' + filename + ' ' + arg_string ).readlines():
316
317                        if line.find( 'ERROR' ) != -1:
318
319                                error_msg = string.join( line.split( ' ' )[1:] )
320                                debug_msg( 8, error_msg )
321                                return 1
322
323                return 0
324
325class XMLProcessor:
326        """Skeleton class for XML processor's"""
327
328        def daemon( self ):
329                """Run as daemon forever"""
330
331                # Fork the first child
332                #
333                pid = os.fork()
334
335                if pid > 0:
336
337                        sys.exit(0)  # end parent
338
339                # creates a session and sets the process group ID
340                #
341                os.setsid()
342
343                # Fork the second child
344                #
345                pid = os.fork()
346
347                if pid > 0:
348
349                        sys.exit(0)  # end parent
350
351                # Go to the root directory and set the umask
352                #
353                os.chdir('/')
354                os.umask(0)
355
356                sys.stdin.close()
357                sys.stdout.close()
358                sys.stderr.close()
359
360                os.open('/dev/null', 0)
361                os.dup(0)
362                os.dup(0)
363
364                self.run()
365
366        def run( self ):
367                """Do main processing of XML here"""
368
369                pass
370
371class TorqueXMLProcessor( XMLProcessor ):
372        """Main class for processing XML and acting with it"""
373
374        def __init__( self ):
375                """Setup initial XML connection and handlers"""
376
377                self.myXMLGatherer = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] ) 
378                self.myXMLSource = self.myXMLGatherer.getFileObject()
379                self.myXMLHandler = TorqueXMLHandler()
380                self.myXMLError = XMLErrorHandler()
381                self.config = GangliaConfigParser( GMETAD_CONF )
382
383        def run( self ):
384                """Main XML processing"""
385
386                debug_msg( 5, printTime() + ' - torquexmlthread(): started.' )
387
388                while( 1 ):
389
390                        self.myXMLSource = self.myXMLGatherer.getFileObject()
391                        debug_msg( 1, printTime() + ' - torquexmlthread(): Parsing..' )
392                        xml.sax.parse( self.myXMLSource, self.myXMLHandler, self.myXMLError )
393                        debug_msg( 1, printTime() + ' - torquexmlthread(): Done parsing.' )
394                        debug_msg( 1, printTime() + ' - torquexmlthread(): Sleeping.. (%ss)' %(str( self.config.getLowestInterval() ) ) )
395                        time.sleep( self.config.getLowestInterval() )
396
397class TorqueXMLHandler( xml.sax.handler.ContentHandler ):
398        """Parse Torque's jobinfo XML from our plugin"""
399
400        jobAttrs = { }
401
402        def __init__( self ):
403
404                self.ds = DataSQLStore( TOGA_SQL_DBASE.split( '/' )[0], TOGA_SQL_DBASE.split( '/' )[1] )
405                self.jobs_processed = [ ]
406                self.jobs_to_store = [ ]
407
408        def startElement( self, name, attrs ):
409                """
410                This XML will be all gmetric XML
411                so there will be no specific start/end element
412                just one XML statement with all info
413                """
414               
415                heartbeat = 0
416               
417                jobinfo = { }
418
419                if name == 'METRIC':
420
421                        metricname = attrs.get( 'NAME', "" )
422
423                        if metricname == 'TOGA-HEARTBEAT':
424                                self.heartbeat = attrs.get( 'VAL', "" )
425
426                        elif metricname.find( 'TOGA-JOB' ) != -1:
427
428                                job_id = metricname.split( 'TOGA-JOB-' )[1]
429                                val = attrs.get( 'VAL', "" )
430
431                                if not job_id in self.jobs_processed:
432                                        self.jobs_processed.append( job_id )
433
434                                check_change = 0
435
436                                if self.jobAttrs.has_key( job_id ):
437                                        check_change = 1
438
439                                valinfo = val.split( ' ' )
440
441                                for myval in valinfo:
442
443                                        if len( myval.split( '=' ) ) > 1:
444
445                                                valname = myval.split( '=' )[0]
446                                                value = myval.split( '=' )[1]
447
448                                                if valname == 'nodes':
449                                                        value = value.split( ';' )
450
451                                                jobinfo[ valname ] = value
452
453                                if check_change:
454                                        if self.jobinfoChanged( self.jobAttrs, job_id, jobinfo ):
455                                                self.jobAttrs[ job_id ] = self.setJobAttrs( self.jobAttrs[ job_id ], jobinfo )
456                                                if not job_id in self.jobs_to_store:
457                                                        self.jobs_to_store.append( job_id )
458
459                                                debug_msg( 0, 'jobinfo for job %s has changed' %job_id )
460                                else:
461                                        self.jobAttrs[ job_id ] = jobinfo
462
463                                        if not job_id in self.jobs_to_store:
464                                                self.jobs_to_store.append( job_id )
465
466                                        debug_msg( 0, 'jobinfo for job %s has changed' %job_id )
467                                       
468        def endDocument( self ):
469                """When all metrics have gone, check if any jobs have finished"""
470
471                for jobid, jobinfo in self.jobAttrs.items():
472
473                        # This is an old job, not in current jobinfo list anymore
474                        # it must have finished, since we _did_ get a new heartbeat
475                        #
476                        mytime = int( jobinfo['reported'] ) + int( jobinfo['poll_interval'] )
477                        if mytime < self.heartbeat and jobid not in self.jobs_processed and jobinfo['status'] == 'R':
478
479                                if not jobid in self.jobs_processed:
480                                        self.jobs_processed.append( jobid )
481
482                                self.jobAttrs[ jobid ]['status'] = 'F'
483                                self.jobAttrs[ jobid ]['stop_timestamp'] = str( int( jobinfo['reported'] ) + int( jobinfo['poll_interval'] ) )
484
485                                if not jobid in self.jobs_to_store:
486                                        self.jobs_to_store.append( jobid )
487
488                debug_msg( 1, printTime() + ' - torquexmlthread(): Storing..' )
489
490                for jobid in self.jobs_to_store:
491                        self.ds.storeJobInfo( jobid, self.jobAttrs[ jobid ] )   
492
493                debug_msg( 1, printTime() + ' - torquexmlthread(): 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( 0, printTime() + ' - Checking existing toga rrd archive..' )
546                self.gatherClusters()
547                debug_msg( 0, printTime() + ' - 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 error ' + str( exception ) )
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( 1, 'No XML data found: probably socket not (re)connected.' )
647                        return 0
648
649                debug_msg( 0, 'Non-recoverable 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, 'Could not open socket' )
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                xmlthread = threading.Thread( None, self.processXML, 'xmlthread' )
757                storethread = threading.Thread( None, self.storeMetrics, 'storethread' )
758
759                while( 1 ):
760
761                        if not xmlthread.isAlive():
762                                # Gather XML at the same interval as gmetad
763
764                                # threaded call to: self.processXML()
765                                #
766                                xmlthread = threading.Thread( None, self.processXML, 'xmlthread' )
767                                xmlthread.start()
768
769                        if not storethread.isAlive():
770                                # Store metrics every .. sec
771
772                                # threaded call to: self.storeMetrics()
773                                #
774                                storethread = threading.Thread( None, self.storeMetrics, 'storethread' )
775                                storethread.start()
776               
777                        # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway
778                        time.sleep( 1 ) 
779
780        def storeMetrics( self ):
781                """Store metrics retained in memory to disk"""
782
783                debug_msg( 7, printTime() + ' - storethread(): started.' )
784
785                # Store metrics somewhere between every 360 and 640 seconds
786                #
787                STORE_INTERVAL = random.randint( 360, 640 )
788
789                storethread = threading.Thread( None, self.storeThread, 'storemetricthread' )
790                storethread.start()
791
792                debug_msg( 7, printTime() + ' - storethread(): Sleeping.. (%ss)' %STORE_INTERVAL )
793                time.sleep( STORE_INTERVAL )
794                debug_msg( 7, printTime() + ' - storethread(): Done sleeping.' )
795
796                if storethread.isAlive():
797
798                        debug_msg( 7, printTime() + ' - storethread(): storemetricthread() still running, waiting to finish..' )
799                        storethread.join( STORE_TIMEOUT ) # Maximum time is for storing thread to finish
800                        debug_msg( 7, printTime() + ' - storethread(): Done waiting.' )
801
802                debug_msg( 7, printTime() + ' - storethread(): finished.' )
803
804                return 0
805
806        def storeThread( self ):
807                """Actual metric storing thread"""
808
809                debug_msg( 1, printTime() + ' - storemetricthread(): started.' )
810                debug_msg( 1, printTime() + ' - storemetricthread(): Storing data..' )
811                ret = self.myXMLHandler.storeMetrics()
812                debug_msg( 1, printTime() + ' - storemetricthread(): Done storing.' )
813                debug_msg( 1, printTime() + ' - storemetricthread(): finished.' )
814               
815                return ret
816
817        def processXML( self ):
818                """Process XML"""
819
820                debug_msg( 1, printTime() + ' - xmlthread(): started.' )
821
822                parsethread = threading.Thread( None, self.parseThread, 'parsethread' )
823                parsethread.start()
824
825                debug_msg( 1, printTime() + ' - xmlthread(): Sleeping.. (%ss)' %self.config.getLowestInterval() )
826                time.sleep( float( self.config.getLowestInterval() ) ) 
827                debug_msg( 1, printTime() + ' - xmlthread(): Done sleeping.' )
828
829                if parsethread.isAlive():
830
831                        debug_msg( 1, printTime() + ' - xmlthread(): parsethread() still running, waiting to finish..' )
832                        parsethread.join( PARSE_TIMEOUT ) # Maximum time for XML thread to finish
833                        debug_msg( 7, printTime() + ' - xmlthread(): Done waiting.' )
834
835                debug_msg( 1, printTime() + ' - xmlthread(): finished.' )
836
837                return 0
838
839        def parseThread( self ):
840                """Actual parsing thread"""
841
842                debug_msg( 1, printTime() + ' - parsethread(): started.' )
843                debug_msg( 1, printTime() + ' - parsethread(): Parsing XML..' )
844                self.myXMLSource = self.myXMLGatherer.getFileObject()
845                ret = xml.sax.parse( self.myXMLSource, self.myXMLHandler, self.myXMLError )
846                debug_msg( 1, printTime() + ' - parsethread(): Done parsing.' )
847                debug_msg( 1, printTime() + ' - parsethread(): finished.' )
848
849                return ret
850
851class GangliaConfigParser:
852
853        sources = [ ]
854
855        def __init__( self, config ):
856                """Parse some stuff from our gmetad's config, such as polling interval"""
857
858                self.config = config
859                self.parseValues()
860
861        def parseValues( self ):
862                """Parse certain values from gmetad.conf"""
863
864                readcfg = open( self.config, 'r' )
865
866                for line in readcfg.readlines():
867
868                        if line.count( '"' ) > 1:
869
870                                if line.find( 'data_source' ) != -1 and line[0] != '#':
871
872                                        source = { }
873                                        source['name'] = line.split( '"' )[1]
874                                        source_words = line.split( '"' )[2].split( ' ' )
875
876                                        for word in source_words:
877
878                                                valid_interval = 1
879
880                                                for letter in word:
881
882                                                        if letter not in string.digits:
883
884                                                                valid_interval = 0
885
886                                                if valid_interval and len(word) > 0:
887
888                                                        source['interval'] = word
889                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
890       
891                                        # No interval found, use Ganglia's default     
892                                        if not source.has_key( 'interval' ):
893                                                source['interval'] = 15
894                                                debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
895
896                                        self.sources.append( source )
897
898        def getInterval( self, source_name ):
899                """Return interval for source_name"""
900
901                for source in self.sources:
902
903                        if source['name'] == source_name:
904
905                                return source['interval']
906
907                return None
908
909        def getLowestInterval( self ):
910                """Return the lowest interval of all clusters"""
911
912                lowest_interval = 0
913
914                for source in self.sources:
915
916                        if not lowest_interval or source['interval'] <= lowest_interval:
917
918                                lowest_interval = source['interval']
919
920                # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays
921                if lowest_interval:
922                        return lowest_interval
923                else:
924                        return 15
925
926class RRDHandler:
927        """Class for handling RRD activity"""
928
929        myMetrics = { }
930        lastStored = { }
931        timeserials = { }
932        slot = None
933
934        def __init__( self, config, cluster ):
935                """Setup initial variables"""
936
937                self.block = 0
938                self.cluster = cluster
939                self.config = config
940                self.slot = threading.Lock()
941                self.rrdm = RRDMutator()
942                self.gatherLastUpdates()
943
944        def gatherLastUpdates( self ):
945                """Populate the lastStored list, containing timestamps of all last updates"""
946
947                cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster )
948
949                hosts = [ ]
950
951                if os.path.exists( cluster_dir ):
952
953                        dirlist = os.listdir( cluster_dir )
954
955                        for dir in dirlist:
956
957                                hosts.append( dir )
958
959                for host in hosts:
960
961                        host_dir = cluster_dir + '/' + host
962                        dirlist = os.listdir( host_dir )
963
964                        for dir in dirlist:
965
966                                if not self.timeserials.has_key( host ):
967
968                                        self.timeserials[ host ] = [ ]
969
970                                self.timeserials[ host ].append( dir )
971
972                        last_serial = self.getLastRrdTimeSerial( host )
973                        if last_serial:
974
975                                metric_dir = cluster_dir + '/' + host + '/' + last_serial
976                                if os.path.exists( metric_dir ):
977
978                                        dirlist = os.listdir( metric_dir )
979
980                                        for file in dirlist:
981
982                                                metricname = file.split( '.rrd' )[0]
983
984                                                if not self.lastStored.has_key( host ):
985
986                                                        self.lastStored[ host ] = { }
987
988                                                self.lastStored[ host ][ metricname ] = self.rrdm.grabLastUpdate( metric_dir + '/' + file )
989
990        def getClusterName( self ):
991                """Return clustername"""
992
993                return self.cluster
994
995        def memMetric( self, host, metric ):
996                """Store metric from host in memory"""
997
998                if self.myMetrics.has_key( host ):
999
1000                        if self.myMetrics[ host ].has_key( metric['name'] ):
1001
1002                                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
1003
1004                                        if mymetric['time'] == metric['time']:
1005
1006                                                # Allready have this metric, abort
1007                                                return 1
1008                        else:
1009                                self.myMetrics[ host ][ metric['name'] ] = [ ]
1010                else:
1011                        self.myMetrics[ host ] = { }
1012                        self.myMetrics[ host ][ metric['name'] ] = [ ]
1013
1014                # Push new metric onto stack
1015                # atomic code; only 1 thread at a time may access the stack
1016
1017                # <ATOMIC>
1018                #
1019                self.slot.acquire()
1020
1021                self.myMetrics[ host ][ metric['name'] ].append( metric )
1022
1023                self.slot.release()
1024                #
1025                # </ATOMIC>
1026
1027        def makeUpdateList( self, host, metriclist ):
1028                """
1029                Make a list of update values for rrdupdate
1030                but only those that we didn't store before
1031                """
1032
1033                update_list = [ ]
1034                metric = None
1035
1036                while len( metriclist ) > 0:
1037
1038                        metric = metriclist.pop( 0 )
1039
1040                        if self.checkStoreMetric( host, metric ):
1041                                update_list.append( '%s:%s' %( metric['time'], metric['val'] ) )
1042
1043                return update_list
1044
1045        def checkStoreMetric( self, host, metric ):
1046                """Check if supplied metric if newer than last one stored"""
1047
1048                if self.lastStored.has_key( host ):
1049
1050                        if self.lastStored[ host ].has_key( metric['name'] ):
1051
1052                                if metric['time'] <= self.lastStored[ host ][ metric['name'] ]:
1053
1054                                        # This is old
1055                                        return 0
1056
1057                return 1
1058
1059        def memLastUpdate( self, host, metricname, metriclist ):
1060                """
1061                Memorize the time of the latest metric from metriclist
1062                but only if it wasn't allready memorized
1063                """
1064
1065                if not self.lastStored.has_key( host ):
1066                        self.lastStored[ host ] = { }
1067
1068                last_update_time = 0
1069
1070                for metric in metriclist:
1071
1072                        if metric['name'] == metricname:
1073
1074                                if metric['time'] > last_update_time:
1075
1076                                        last_update_time = metric['time']
1077
1078                if self.lastStored[ host ].has_key( metricname ):
1079                       
1080                        if last_update_time <= self.lastStored[ host ][ metricname ]:
1081                                return 1
1082
1083                self.lastStored[ host ][ metricname ] = last_update_time
1084
1085        def storeMetrics( self ):
1086                """
1087                Store all metrics from memory to disk
1088                and do it to the RRD's in appropriate timeperiod directory
1089                """
1090
1091                for hostname, mymetrics in self.myMetrics.items():     
1092
1093                        for metricname, mymetric in mymetrics.items():
1094
1095                                metrics_to_store = [ ]
1096
1097                                # Pop metrics from stack for storing until none is left
1098                                # atomic code: only 1 thread at a time may access myMetrics
1099
1100                                # <ATOMIC>
1101                                #
1102                                self.slot.acquire() 
1103
1104                                while len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1105
1106                                        if len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1107                                                metrics_to_store.append( self.myMetrics[ hostname ][ metricname ].pop( 0 ) )
1108
1109                                self.slot.release()
1110                                #
1111                                # </ATOMIC>
1112
1113                                # Create a mapping table, each metric to the period where it should be stored
1114                                #
1115                                metric_serial_table = self.determineSerials( hostname, metricname, metrics_to_store )
1116
1117                                update_rets = [ ]
1118
1119                                for period, pmetric in metric_serial_table.items():
1120
1121                                        self.createCheck( hostname, metricname, period )       
1122
1123                                        update_ret = self.update( hostname, metricname, period, pmetric )
1124
1125                                        if update_ret == 0:
1126
1127                                                debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
1128                                        else:
1129                                                debug_msg( 9, 'metric update failed' )
1130
1131                                        update_rets.append( update_ret )
1132
1133                                if not (1) in update_rets:
1134
1135                                        self.memLastUpdate( hostname, metricname, metrics_to_store )
1136
1137        def makeTimeSerial( self ):
1138                """Generate a time serial. Seconds since epoch"""
1139
1140                # Seconds since epoch
1141                mytime = int( time.time() )
1142
1143                return mytime
1144
1145        def makeRrdPath( self, host, metricname, timeserial ):
1146                """Make a RRD location/path and filename"""
1147
1148                rrd_dir = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
1149                rrd_file = '%s/%s.rrd' %( rrd_dir, metricname )
1150
1151                return rrd_dir, rrd_file
1152
1153        def getLastRrdTimeSerial( self, host ):
1154                """Find the last timeserial (directory) for this host"""
1155
1156                newest_timeserial = 0
1157
1158                for dir in self.timeserials[ host ]:
1159
1160                        valid_dir = 1
1161
1162                        for letter in dir:
1163                                if letter not in string.digits:
1164                                        valid_dir = 0
1165
1166                        if valid_dir:
1167                                timeserial = dir
1168                                if timeserial > newest_timeserial:
1169                                        newest_timeserial = timeserial
1170
1171                if newest_timeserial:
1172                        return newest_timeserial
1173                else:
1174                        return 0
1175
1176        def determinePeriod( self, host, check_serial ):
1177                """Determine to which period (directory) this time(serial) belongs"""
1178
1179                period_serial = 0
1180
1181                if self.timeserials.has_key( host ):
1182
1183                        for serial in self.timeserials[ host ]:
1184
1185                                if check_serial >= serial and period_serial < serial:
1186
1187                                        period_serial = serial
1188
1189                return period_serial
1190
1191        def determineSerials( self, host, metricname, metriclist ):
1192                """
1193                Determine the correct serial and corresponding rrd to store
1194                for a list of metrics
1195                """
1196
1197                metric_serial_table = { }
1198
1199                for metric in metriclist:
1200
1201                        if metric['name'] == metricname:
1202
1203                                period = self.determinePeriod( host, metric['time'] )   
1204
1205                                archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60)
1206
1207                                if (int( metric['time'] ) - int( period ) ) > archive_secs:
1208
1209                                        # This one should get it's own new period
1210                                        period = metric['time']
1211
1212                                        if not self.timeserials.has_key( host ):
1213                                                self.timeserials[ host ] = [ ]
1214
1215                                        self.timeserials[ host ].append( period )
1216
1217                                if not metric_serial_table.has_key( period ):
1218
1219                                        metric_serial_table[ period ] = [ ]
1220
1221                                metric_serial_table[ period ].append( metric )
1222
1223                return metric_serial_table
1224
1225        def createCheck( self, host, metricname, timeserial ):
1226                """Check if an rrd allready exists for this metric, create if not"""
1227
1228                debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1229               
1230                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
1231
1232                if not os.path.exists( rrd_dir ):
1233
1234                        try:
1235                                os.makedirs( rrd_dir )
1236
1237                        except OSError, msg:
1238
1239                                if msg.find( 'File exists' ) != -1:
1240
1241                                        # Ignore exists errors
1242                                        pass
1243
1244                                else:
1245
1246                                        print msg
1247                                        return
1248
1249                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
1250
1251                if not os.path.exists( rrd_file ):
1252
1253                        interval = self.config.getInterval( self.cluster )
1254                        heartbeat = 8 * int( interval )
1255
1256                        params = [ ]
1257
1258                        params.append( '--step' )
1259                        params.append( str( interval ) )
1260
1261                        params.append( '--start' )
1262                        params.append( str( int( timeserial ) - 1 ) )
1263
1264                        params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat )
1265                        params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) )
1266
1267                        self.rrdm.create( str(rrd_file), params )
1268
1269                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
1270
1271        def update( self, host, metricname, timeserial, metriclist ):
1272                """
1273                Update rrd file for host with metricname
1274                in directory timeserial with metriclist
1275                """
1276
1277                debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1278
1279                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
1280
1281                update_list = self.makeUpdateList( host, metriclist )
1282
1283                if len( update_list ) > 0:
1284                        ret = self.rrdm.update( str(rrd_file), update_list )
1285
1286                        if ret:
1287                                return 1
1288               
1289                        debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) )
1290
1291                return 0
1292
1293def main():
1294        """Program startup"""
1295
1296        myTProcessor = TorqueXMLProcessor()
1297        myGProcessor = GangliaXMLProcessor()
1298
1299        if DAEMONIZE:
1300                torquexmlthread = threading.Thread( None, myTProcessor.daemon, 'tprocxmlthread' )
1301                gangliaxmlthread = threading.Thread( None, myGProcessor.daemon, 'gprocxmlthread' )
1302        else:
1303                torquexmlthread = threading.Thread( None, myTProcessor.run, 'tprocxmlthread' )
1304                gangliaxmlthread = threading.Thread( None, myGProcessor.run, 'gprocxmlthread' )
1305
1306        torquexmlthread.start()
1307        gangliaxmlthread.start()
1308
1309# Global functions
1310
1311def check_dir( directory ):
1312        """Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"""
1313
1314        if directory[-1] == '/':
1315                directory = directory[:-1]
1316
1317        return directory
1318
1319def debug_msg( level, msg ):
1320        """Only print msg if it is not below our debug level"""
1321
1322        if (DEBUG_LEVEL >= level):
1323                sys.stderr.write( msg + '\n' )
1324
1325def printTime( ):
1326        """Print current time in human readable format"""
1327
1328        return time.strftime("%a %d %b %Y %H:%M:%S")
1329
1330# Ooohh, someone started me! Let's go..
1331if __name__ == '__main__':
1332        main()
Note: See TracBrowser for help on using the repository browser.