source: trunk/jobarchived/jobarchived.py @ 229

Last change on this file since 229 was 225, checked in by bastiaans, 18 years ago

ALL:

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