source: trunk/daemon/togad.py @ 182

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

daemon/togad.py:

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