source: trunk/jobarchived/jobarchived.py @ 370

Last change on this file since 370 was 370, checked in by bastiaans, 17 years ago

jobarchived/jobarchived.py:

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