source: branches/0.4/jobarchived/jobarchived.py @ 792

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