source: trunk/jobarchived/jobarchived.py @ 357

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

jobarchived/jobarchived.conf-dist:

  • use port 8651 again, works better

jobarchived/jobarchived.py:

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