source: trunk/daemon/togad.py @ 179

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

daemon/togad.py:

  • Rearranged thread locking, I suspect a conflict
  • Disabled error checking on rrd update:
    • more important to have correct last update time!
    • with correct update time there will be no errors anyway
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               
412                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:
[100]451                                        if self.jobinfoChanged( self.jobAttrs, job_id, jobinfo ) and self.jobAttrs[ job_id ]['status'] != 'E':
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
[74]469                for jobid, jobinfo in self.jobAttrs.items():
470
471                        # This is an old job, not in current jobinfo list anymore
472                        # it must have finished, since we _did_ get a new heartbeat
473                        #
[96]474                        mytime = int( jobinfo['reported'] ) + int( jobinfo['poll_interval'] )
[102]475
[96]476                        if mytime < self.heartbeat and jobid not in self.jobs_processed and jobinfo['status'] == 'R':
[74]477
[97]478                                if not jobid in self.jobs_processed:
[96]479                                        self.jobs_processed.append( jobid )
480
[74]481                                self.jobAttrs[ jobid ]['status'] = 'F'
[151]482                                self.jobAttrs[ jobid ]['stop_timestamp'] = str( mytime )
[96]483
[84]484                                if not jobid in self.jobs_to_store:
485                                        self.jobs_to_store.append( jobid )
[74]486
[169]487                debug_msg( 1, 'torque_xml_thread(): Storing..' )
[87]488
[84]489                for jobid in self.jobs_to_store:
[155]490                        if self.jobAttrs[ jobid ]['status'] in [ 'R', 'Q', 'F' ]:
[151]491                                self.ds.storeJobInfo( jobid, self.jobAttrs[ jobid ] )   
[84]492
[169]493                debug_msg( 1, 'torque_xml_thread(): Done storing.' )
[87]494
[96]495                self.jobs_processed = [ ]
[84]496                self.jobs_to_store = [ ]
497
[82]498        def setJobAttrs( self, old, new ):
499                """
500                Set new job attributes in old, but not lose existing fields
501                if old attributes doesn't have those
502                """
503
504                for valname, value in new.items():
505                        old[ valname ] = value
506
507                return old
508               
509
[73]510        def jobinfoChanged( self, jobattrs, jobid, jobinfo ):
[74]511                """
512                Check if jobinfo has changed from jobattrs[jobid]
513                if it's report time is bigger than previous one
514                and it is report time is recent (equal to heartbeat)
515                """
[72]516
[87]517                ignore_changes = [ 'reported' ]
518
[73]519                if jobattrs.has_key( jobid ):
520
521                        for valname, value in jobinfo.items():
522
[87]523                                if valname not in ignore_changes:
[73]524
[87]525                                        if jobattrs[ jobid ].has_key( valname ):
[73]526
[87]527                                                if value != jobattrs[ jobid ][ valname ]:
[73]528
[87]529                                                        if jobinfo['reported'] > jobattrs[ jobid ][ 'reported' ] and jobinfo['reported'] == self.heartbeat:
530                                                                return 1
[73]531
[87]532                                        else:
533                                                return 1
534
[73]535                return 0
536
[71]537class GangliaXMLHandler( xml.sax.handler.ContentHandler ):
[63]538        """Parse Ganglia's XML"""
[3]539
[33]540        def __init__( self, config ):
[63]541                """Setup initial variables and gather info on existing rrd archive"""
542
[33]543                self.config = config
[35]544                self.clusters = { }
[169]545                debug_msg( 1, 'Checking existing toga rrd archive..' )
[44]546                self.gatherClusters()
[169]547                debug_msg( 1, 'Check done.' )
[33]548
[44]549        def gatherClusters( self ):
[63]550                """Find all existing clusters in archive dir"""
[44]551
[45]552                archive_dir = check_dir(ARCHIVE_PATH)
[44]553
554                hosts = [ ]
555
556                if os.path.exists( archive_dir ):
557
558                        dirlist = os.listdir( archive_dir )
559
560                        for item in dirlist:
561
562                                clustername = item
563
[60]564                                if not self.clusters.has_key( clustername ) and clustername in ARCHIVE_DATASOURCES:
[44]565
566                                        self.clusters[ clustername ] = RRDHandler( self.config, clustername )
567
[6]568        def startElement( self, name, attrs ):
[63]569                """Memorize appropriate data from xml start tags"""
[3]570
[7]571                if name == 'GANGLIA_XML':
[32]572
573                        self.XMLSource = attrs.get( 'SOURCE', "" )
574                        self.gangliaVersion = attrs.get( 'VERSION', "" )
575
[12]576                        debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
[6]577
[7]578                elif name == 'GRID':
[32]579
580                        self.gridName = attrs.get( 'NAME', "" )
581                        self.time = attrs.get( 'LOCALTIME', "" )
582
[12]583                        debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
[6]584
[7]585                elif name == 'CLUSTER':
[32]586
587                        self.clusterName = attrs.get( 'NAME', "" )
588                        self.time = attrs.get( 'LOCALTIME', "" )
589
[60]590                        if not self.clusters.has_key( self.clusterName ) and self.clusterName in ARCHIVE_DATASOURCES:
[32]591
[34]592                                self.clusters[ self.clusterName ] = RRDHandler( self.config, self.clusterName )
[33]593
[35]594                                debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
[6]595
[60]596                elif name == 'HOST' and self.clusterName in ARCHIVE_DATASOURCES:     
[32]597
598                        self.hostName = attrs.get( 'NAME', "" )
599                        self.hostIp = attrs.get( 'IP', "" )
600                        self.hostReported = attrs.get( 'REPORTED', "" )
601
[12]602                        debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
[6]603
[60]604                elif name == 'METRIC' and self.clusterName in ARCHIVE_DATASOURCES:
[6]605
[32]606                        type = attrs.get( 'TYPE', "" )
[6]607
[32]608                        if type not in UNSUPPORTED_ARCHIVE_TYPES:
[3]609
[32]610                                myMetric = { }
611                                myMetric['name'] = attrs.get( 'NAME', "" )
612                                myMetric['val'] = attrs.get( 'VAL', "" )
613                                myMetric['time'] = self.hostReported
[3]614
[34]615                                self.clusters[ self.clusterName ].memMetric( self.hostName, myMetric )
[3]616
[34]617                                debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
[6]618
[34]619        def storeMetrics( self ):
[63]620                """Store metrics of each cluster rrd handler"""
[9]621
[34]622                for clustername, rrdh in self.clusters.items():
[16]623
[38]624                        ret = rrdh.storeMetrics()
[9]625
[38]626                        if ret:
627                                debug_msg( 9, 'An error occured while storing metrics for cluster %s' %clustername )
628                                return 1
629
630                return 0
631
[71]632class XMLErrorHandler( xml.sax.handler.ErrorHandler ):
633
634        def error( self, exception ):
635                """Recoverable error"""
636
[169]637                debug_msg( 0, 'Recoverable XML error ' + str( exception ) + ' ignored.' )
[71]638
639        def fatalError( self, exception ):
640                """Non-recoverable error"""
641
642                exception_str = str( exception )
643
644                # Ignore 'no element found' errors
645                if exception_str.find( 'no element found' ) != -1:
[169]646                        debug_msg( 0, 'No XML data found: Socket not (re)connected or datasource not available.' )
[71]647                        return 0
648
[170]649                debug_msg( 0, 'FATAL ERROR: Non-recoverable XML error ' + str( exception ) )
[71]650                sys.exit( 1 )
651
652        def warning( self, exception ):
653                """Warning"""
654
655                debug_msg( 0, 'Warning ' + str( exception ) )
656
[78]657class XMLGatherer:
[63]658        """Setup a connection and file object to Ganglia's XML"""
[3]659
[8]660        s = None
[70]661        fd = None
[8]662
663        def __init__( self, host, port ):
[63]664                """Store host and port for connection"""
[8]665
[5]666                self.host = host
667                self.port = port
[33]668                self.connect()
[70]669                self.makeFileDescriptor()
[3]670
[33]671        def connect( self ):
[63]672                """Setup connection to XML source"""
[8]673
674                for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ):
[32]675
[5]676                        af, socktype, proto, canonname, sa = res
[32]677
[5]678                        try:
[32]679
[8]680                                self.s = socket.socket( af, socktype, proto )
[32]681
[5]682                        except socket.error, msg:
[32]683
[8]684                                self.s = None
[5]685                                continue
[32]686
[5]687                        try:
[32]688
[8]689                                self.s.connect( sa )
[32]690
[5]691                        except socket.error, msg:
[32]692
[70]693                                self.disconnect()
[5]694                                continue
[32]695
[5]696                        break
[3]697
[8]698                if self.s is None:
[32]699
[170]700                        debug_msg( 0, 'FATAL ERROR: Could not open socket or unable to connect to datasource!' )
[33]701                        sys.exit( 1 )
[5]702
[33]703        def disconnect( self ):
[63]704                """Close socket"""
[33]705
706                if self.s:
[71]707                        self.s.shutdown( 2 )
[33]708                        self.s.close()
709                        self.s = None
710
711        def __del__( self ):
[63]712                """Kill the socket before we leave"""
[33]713
714                self.disconnect()
715
[70]716        def reconnect( self ):
717                """Reconnect"""
[33]718
[38]719                if self.s:
720                        self.disconnect()
[33]721
[70]722                self.connect()
[5]723
[70]724        def makeFileDescriptor( self ):
725                """Make file descriptor that points to our socket connection"""
726
727                self.reconnect()
728
729                if self.s:
730                        self.fd = self.s.makefile( 'r' )
731
732        def getFileObject( self ):
733                """Connect, and return a file object"""
734
[78]735                self.makeFileDescriptor()
736
[70]737                if self.fd:
738                        return self.fd
739
[78]740class GangliaXMLProcessor( XMLProcessor ):
[63]741        """Main class for processing XML and acting with it"""
[5]742
[33]743        def __init__( self ):
[63]744                """Setup initial XML connection and handlers"""
[33]745
746                self.config = GangliaConfigParser( GMETAD_CONF )
747
[78]748                self.myXMLGatherer = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] ) 
[70]749                self.myXMLSource = self.myXMLGatherer.getFileObject()
[78]750                self.myXMLHandler = GangliaXMLHandler( self.config )
751                self.myXMLError = XMLErrorHandler()
[73]752
[9]753        def run( self ):
[63]754                """Main XML processing; start a xml and storethread"""
[8]755
[102]756                xml_thread = threading.Thread( None, self.processXML, 'xmlthread' )
757                store_thread = threading.Thread( None, self.storeMetrics, 'storethread' )
[22]758
[36]759                while( 1 ):
760
[102]761                        if not xml_thread.isAlive():
[36]762                                # Gather XML at the same interval as gmetad
763
764                                # threaded call to: self.processXML()
765                                #
[169]766                                try:
767                                        xml_thread = threading.Thread( None, self.processXML, 'xml_thread' )
768                                        xml_thread.start()
[176]769                                except thread.error, msg:
[169]770                                        debug_msg( 0, 'ERROR: Unable to start xml_thread!: '+str(msg))
771                                        #return 1
[36]772
[102]773                        if not store_thread.isAlive():
[55]774                                # Store metrics every .. sec
[36]775
[55]776                                # threaded call to: self.storeMetrics()
777                                #
[169]778                                try:
779                                        store_thread = threading.Thread( None, self.storeMetrics, 'store_thread' )
780                                        store_thread.start()
[176]781                                except thread.error, msg:
[169]782                                        debug_msg( 0, 'ERROR: Unable to start store_thread!: '+str(msg))
783                                        #return 1
[36]784               
785                        # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway
786                        time.sleep( 1 ) 
787
[33]788        def storeMetrics( self ):
[63]789                """Store metrics retained in memory to disk"""
[22]790
[63]791                # Store metrics somewhere between every 360 and 640 seconds
[38]792                #
[55]793                STORE_INTERVAL = random.randint( 360, 640 )
[22]794
[169]795                try:
796                        store_metric_thread = threading.Thread( None, self.storeThread, 'store_metric_thread' )
797                        store_metric_thread.start()
[176]798                except thread.error, msg:
[169]799                        debug_msg( 0, 'ERROR: Unable to start ganglia_store_thread()!: '+str(msg) )
800                        return 1
[36]801
[169]802                debug_msg( 1, 'ganglia_store_thread(): started.' )
803
804                debug_msg( 1, 'ganglia_store_thread(): Sleeping.. (%ss)' %STORE_INTERVAL )
[36]805                time.sleep( STORE_INTERVAL )
[169]806                debug_msg( 1, 'ganglia_store_thread(): Done sleeping.' )
[36]807
[102]808                if store_metric_thread.isAlive():
[36]809
[169]810                        debug_msg( 1, 'ganglia_store_thread(): storemetricthread() still running, waiting to finish..' )
[136]811                        store_metric_thread.join( STORE_TIMEOUT ) # Maximum time is for storing thread to finish
[169]812                        debug_msg( 1, 'ganglia_store_thread(): Done waiting.' )
[36]813
[169]814                debug_msg( 1, 'ganglia_store_thread(): finished.' )
[36]815
816                return 0
817
[39]818        def storeThread( self ):
[63]819                """Actual metric storing thread"""
[39]820
[169]821                debug_msg( 1, 'ganglia_store_metric_thread(): started.' )
822                debug_msg( 1, 'ganglia_store_metric_thread(): Storing data..' )
[78]823                ret = self.myXMLHandler.storeMetrics()
[176]824                if ret > 0:
825                        debug_msg( 0, 'ganglia_store_metric_thread(): UNKNOWN ERROR %s while storing Metrics!' %str(ret) )
[169]826                debug_msg( 1, 'ganglia_store_metric_thread(): Done storing.' )
827                debug_msg( 1, 'ganglia_store_metric_thread(): finished.' )
[39]828               
[176]829                return 0
[39]830
[8]831        def processXML( self ):
[63]832                """Process XML"""
[8]833
[169]834                try:
835                        parsethread = threading.Thread( None, self.parseThread, 'parsethread' )
836                        parsethread.start()
[176]837                except thread.error, msg:
[169]838                        debug_msg( 0, 'ERROR: Unable to start ganglia_xml_thread()!: ' + str(msg) )
839                        return 1
[8]840
[169]841                debug_msg( 1, 'ganglia_xml_thread(): started.' )
[36]842
[169]843                debug_msg( 1, 'ganglia_xml_thread(): Sleeping.. (%ss)' %self.config.getLowestInterval() )
[36]844                time.sleep( float( self.config.getLowestInterval() ) ) 
[169]845                debug_msg( 1, 'ganglia_xml_thread(): Done sleeping.' )
[36]846
847                if parsethread.isAlive():
848
[169]849                        debug_msg( 1, 'ganglia_xml_thread(): parsethread() still running, waiting (%ss) to finish..' %PARSE_TIMEOUT )
[47]850                        parsethread.join( PARSE_TIMEOUT ) # Maximum time for XML thread to finish
[169]851                        debug_msg( 1, 'ganglia_xml_thread(): Done waiting.' )
[36]852
[169]853                debug_msg( 1, 'ganglia_xml_thread(): finished.' )
[36]854
855                return 0
856
[39]857        def parseThread( self ):
[63]858                """Actual parsing thread"""
[39]859
[169]860                debug_msg( 1, 'ganglia_parse_thread(): started.' )
861                debug_msg( 1, 'ganglia_parse_thread(): Parsing XML..' )
[78]862                self.myXMLSource = self.myXMLGatherer.getFileObject()
[176]863
864                try:
865                        xml.sax.parse( self.myXMLSource, self.myXMLHandler, self.myXMLError )
866                except socket.error, msg:
867                        debug_msg( 0, 'ERROR: Socket error in connect to datasource!: %s' %msg )
868
[169]869                debug_msg( 1, 'ganglia_parse_thread(): Done parsing.' )
870                debug_msg( 1, 'ganglia_parse_thread(): finished.' )
[39]871
[176]872                return 0
[39]873
[9]874class GangliaConfigParser:
875
[34]876        sources = [ ]
[9]877
878        def __init__( self, config ):
[63]879                """Parse some stuff from our gmetad's config, such as polling interval"""
[32]880
[9]881                self.config = config
882                self.parseValues()
883
[32]884        def parseValues( self ):
[63]885                """Parse certain values from gmetad.conf"""
[9]886
887                readcfg = open( self.config, 'r' )
888
889                for line in readcfg.readlines():
890
891                        if line.count( '"' ) > 1:
892
[10]893                                if line.find( 'data_source' ) != -1 and line[0] != '#':
[9]894
[11]895                                        source = { }
896                                        source['name'] = line.split( '"' )[1]
[9]897                                        source_words = line.split( '"' )[2].split( ' ' )
898
899                                        for word in source_words:
900
901                                                valid_interval = 1
902
903                                                for letter in word:
[32]904
[9]905                                                        if letter not in string.digits:
[32]906
[9]907                                                                valid_interval = 0
908
[10]909                                                if valid_interval and len(word) > 0:
[32]910
[9]911                                                        source['interval'] = word
[12]912                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
[33]913       
914                                        # No interval found, use Ganglia's default     
915                                        if not source.has_key( 'interval' ):
916                                                source['interval'] = 15
917                                                debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
[32]918
[33]919                                        self.sources.append( source )
[9]920
921        def getInterval( self, source_name ):
[63]922                """Return interval for source_name"""
[32]923
[9]924                for source in self.sources:
[32]925
[12]926                        if source['name'] == source_name:
[32]927
[9]928                                return source['interval']
[32]929
[9]930                return None
931
[34]932        def getLowestInterval( self ):
[63]933                """Return the lowest interval of all clusters"""
[34]934
935                lowest_interval = 0
936
937                for source in self.sources:
938
939                        if not lowest_interval or source['interval'] <= lowest_interval:
940
941                                lowest_interval = source['interval']
942
943                # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays
944                if lowest_interval:
945                        return lowest_interval
946                else:
947                        return 15
948
[9]949class RRDHandler:
[63]950        """Class for handling RRD activity"""
[9]951
[32]952        myMetrics = { }
[40]953        lastStored = { }
[47]954        timeserials = { }
[36]955        slot = None
[32]956
[33]957        def __init__( self, config, cluster ):
[63]958                """Setup initial variables"""
[78]959
[44]960                self.block = 0
[9]961                self.cluster = cluster
[33]962                self.config = config
[40]963                self.slot = threading.Lock()
[37]964                self.rrdm = RRDMutator()
[42]965                self.gatherLastUpdates()
[9]966
[42]967        def gatherLastUpdates( self ):
[63]968                """Populate the lastStored list, containing timestamps of all last updates"""
[42]969
970                cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster )
971
972                hosts = [ ]
973
974                if os.path.exists( cluster_dir ):
975
[44]976                        dirlist = os.listdir( cluster_dir )
[42]977
[44]978                        for dir in dirlist:
[42]979
[44]980                                hosts.append( dir )
[42]981
982                for host in hosts:
983
[47]984                        host_dir = cluster_dir + '/' + host
985                        dirlist = os.listdir( host_dir )
986
987                        for dir in dirlist:
988
989                                if not self.timeserials.has_key( host ):
990
991                                        self.timeserials[ host ] = [ ]
992
993                                self.timeserials[ host ].append( dir )
994
[42]995                        last_serial = self.getLastRrdTimeSerial( host )
996                        if last_serial:
997
998                                metric_dir = cluster_dir + '/' + host + '/' + last_serial
999                                if os.path.exists( metric_dir ):
1000
[44]1001                                        dirlist = os.listdir( metric_dir )
[42]1002
[44]1003                                        for file in dirlist:
[42]1004
[44]1005                                                metricname = file.split( '.rrd' )[0]
[42]1006
[44]1007                                                if not self.lastStored.has_key( host ):
[42]1008
[44]1009                                                        self.lastStored[ host ] = { }
[42]1010
[44]1011                                                self.lastStored[ host ][ metricname ] = self.rrdm.grabLastUpdate( metric_dir + '/' + file )
[42]1012
[32]1013        def getClusterName( self ):
[63]1014                """Return clustername"""
1015
[32]1016                return self.cluster
1017
1018        def memMetric( self, host, metric ):
[63]1019                """Store metric from host in memory"""
[32]1020
[179]1021                # <ATOMIC>
1022                #
1023                self.slot.acquire()
1024               
[34]1025                if self.myMetrics.has_key( host ):
[32]1026
[34]1027                        if self.myMetrics[ host ].has_key( metric['name'] ):
[32]1028
[34]1029                                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
[32]1030
[34]1031                                        if mymetric['time'] == metric['time']:
[32]1032
[34]1033                                                # Allready have this metric, abort
[179]1034                                                self.slot.release()
[34]1035                                                return 1
1036                        else:
1037                                self.myMetrics[ host ][ metric['name'] ] = [ ]
1038                else:
[32]1039                        self.myMetrics[ host ] = { }
[34]1040                        self.myMetrics[ host ][ metric['name'] ] = [ ]
[32]1041
[63]1042                # Push new metric onto stack
1043                # atomic code; only 1 thread at a time may access the stack
1044
[32]1045                self.myMetrics[ host ][ metric['name'] ].append( metric )
1046
[40]1047                self.slot.release()
[53]1048                #
1049                # </ATOMIC>
[40]1050
[47]1051        def makeUpdateList( self, host, metriclist ):
[63]1052                """
1053                Make a list of update values for rrdupdate
1054                but only those that we didn't store before
1055                """
[37]1056
1057                update_list = [ ]
[41]1058                metric = None
[37]1059
[47]1060                while len( metriclist ) > 0:
[37]1061
[53]1062                        metric = metriclist.pop( 0 )
[37]1063
[53]1064                        if self.checkStoreMetric( host, metric ):
1065                                update_list.append( '%s:%s' %( metric['time'], metric['val'] ) )
[40]1066
[37]1067                return update_list
1068
[49]1069        def checkStoreMetric( self, host, metric ):
[63]1070                """Check if supplied metric if newer than last one stored"""
[40]1071
1072                if self.lastStored.has_key( host ):
1073
[47]1074                        if self.lastStored[ host ].has_key( metric['name'] ):
[40]1075
[47]1076                                if metric['time'] <= self.lastStored[ host ][ metric['name'] ]:
[40]1077
[50]1078                                        # This is old
[40]1079                                        return 0
1080
[50]1081                return 1
1082
[54]1083        def memLastUpdate( self, host, metricname, metriclist ):
[63]1084                """
1085                Memorize the time of the latest metric from metriclist
1086                but only if it wasn't allready memorized
1087                """
[50]1088
[54]1089                if not self.lastStored.has_key( host ):
1090                        self.lastStored[ host ] = { }
1091
[50]1092                last_update_time = 0
1093
1094                for metric in metriclist:
1095
[54]1096                        if metric['name'] == metricname:
[50]1097
[54]1098                                if metric['time'] > last_update_time:
[50]1099
[54]1100                                        last_update_time = metric['time']
[40]1101
[54]1102                if self.lastStored[ host ].has_key( metricname ):
[52]1103                       
[54]1104                        if last_update_time <= self.lastStored[ host ][ metricname ]:
[52]1105                                return 1
[40]1106
[54]1107                self.lastStored[ host ][ metricname ] = last_update_time
[52]1108
[33]1109        def storeMetrics( self ):
[63]1110                """
1111                Store all metrics from memory to disk
1112                and do it to the RRD's in appropriate timeperiod directory
1113                """
[33]1114
1115                for hostname, mymetrics in self.myMetrics.items():     
1116
1117                        for metricname, mymetric in mymetrics.items():
1118
[53]1119                                metrics_to_store = [ ]
1120
[63]1121                                # Pop metrics from stack for storing until none is left
1122                                # atomic code: only 1 thread at a time may access myMetrics
1123
[53]1124                                # <ATOMIC>
[50]1125                                #
[47]1126                                self.slot.acquire() 
[33]1127
[54]1128                                while len( self.myMetrics[ hostname ][ metricname ] ) > 0:
[53]1129
[54]1130                                        if len( self.myMetrics[ hostname ][ metricname ] ) > 0:
[53]1131
[176]1132                                                try:
1133                                                        metrics_to_store.append( self.myMetrics[ hostname ][ metricname ].pop( 0 ) )
1134                                                except IndexError, msg:
1135
[179]1136                                                        # Somehow sometimes myMetrics[ hostname ][ metricname ]
1137                                                        # is still len 0 when the statement is executed.
1138                                                        # Just ignore indexerror's..
[176]1139                                                        pass
1140
[53]1141                                self.slot.release()
1142                                #
1143                                # </ATOMIC>
1144
[47]1145                                # Create a mapping table, each metric to the period where it should be stored
1146                                #
[53]1147                                metric_serial_table = self.determineSerials( hostname, metricname, metrics_to_store )
[33]1148
[50]1149                                update_rets = [ ]
1150
[47]1151                                for period, pmetric in metric_serial_table.items():
1152
[146]1153                                        create_ret = self.createCheck( hostname, metricname, period )   
[47]1154
1155                                        update_ret = self.update( hostname, metricname, period, pmetric )
1156
1157                                        if update_ret == 0:
1158
1159                                                debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
1160                                        else:
1161                                                debug_msg( 9, 'metric update failed' )
1162
[146]1163                                        update_rets.append( create_ret )
[50]1164                                        update_rets.append( update_ret )
[47]1165
[179]1166                                # Lets ignore errors here for now, we need to make sure last update time
1167                                # is correct!
1168                                #
1169                                #if not (1) in update_rets:
[50]1170
[179]1171                                self.memLastUpdate( hostname, metricname, metrics_to_store )
[50]1172
[17]1173        def makeTimeSerial( self ):
[63]1174                """Generate a time serial. Seconds since epoch"""
[17]1175
1176                # Seconds since epoch
1177                mytime = int( time.time() )
1178
1179                return mytime
1180
[50]1181        def makeRrdPath( self, host, metricname, timeserial ):
[63]1182                """Make a RRD location/path and filename"""
[17]1183
[50]1184                rrd_dir = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
1185                rrd_file = '%s/%s.rrd' %( rrd_dir, metricname )
[17]1186
1187                return rrd_dir, rrd_file
1188
[20]1189        def getLastRrdTimeSerial( self, host ):
[63]1190                """Find the last timeserial (directory) for this host"""
[17]1191
[19]1192                newest_timeserial = 0
1193
[47]1194                for dir in self.timeserials[ host ]:
[32]1195
[47]1196                        valid_dir = 1
[17]1197
[47]1198                        for letter in dir:
1199                                if letter not in string.digits:
1200                                        valid_dir = 0
[17]1201
[47]1202                        if valid_dir:
1203                                timeserial = dir
1204                                if timeserial > newest_timeserial:
1205                                        newest_timeserial = timeserial
[17]1206
1207                if newest_timeserial:
[18]1208                        return newest_timeserial
[17]1209                else:
1210                        return 0
1211
[47]1212        def determinePeriod( self, host, check_serial ):
[63]1213                """Determine to which period (directory) this time(serial) belongs"""
[47]1214
1215                period_serial = 0
1216
[56]1217                if self.timeserials.has_key( host ):
[47]1218
[56]1219                        for serial in self.timeserials[ host ]:
[47]1220
[56]1221                                if check_serial >= serial and period_serial < serial:
[47]1222
[56]1223                                        period_serial = serial
1224
[47]1225                return period_serial
1226
1227        def determineSerials( self, host, metricname, metriclist ):
1228                """
1229                Determine the correct serial and corresponding rrd to store
1230                for a list of metrics
1231                """
1232
1233                metric_serial_table = { }
1234
1235                for metric in metriclist:
1236
1237                        if metric['name'] == metricname:
1238
1239                                period = self.determinePeriod( host, metric['time'] )   
1240
1241                                archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60)
1242
[49]1243                                if (int( metric['time'] ) - int( period ) ) > archive_secs:
[47]1244
1245                                        # This one should get it's own new period
1246                                        period = metric['time']
[57]1247
1248                                        if not self.timeserials.has_key( host ):
1249                                                self.timeserials[ host ] = [ ]
1250
[50]1251                                        self.timeserials[ host ].append( period )
[47]1252
1253                                if not metric_serial_table.has_key( period ):
1254
[49]1255                                        metric_serial_table[ period ] = [ ]
[47]1256
1257                                metric_serial_table[ period ].append( metric )
1258
1259                return metric_serial_table
1260
[33]1261        def createCheck( self, host, metricname, timeserial ):
[63]1262                """Check if an rrd allready exists for this metric, create if not"""
[9]1263
[35]1264                debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
[47]1265               
[33]1266                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
[17]1267
[9]1268                if not os.path.exists( rrd_dir ):
[58]1269
1270                        try:
1271                                os.makedirs( rrd_dir )
1272
[169]1273                        except os.OSError, msg:
[58]1274
1275                                if msg.find( 'File exists' ) != -1:
1276
1277                                        # Ignore exists errors
1278                                        pass
1279
1280                                else:
1281
1282                                        print msg
1283                                        return
1284
[14]1285                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
[9]1286
[14]1287                if not os.path.exists( rrd_file ):
[9]1288
[33]1289                        interval = self.config.getInterval( self.cluster )
[47]1290                        heartbeat = 8 * int( interval )
[9]1291
[37]1292                        params = [ ]
[12]1293
[37]1294                        params.append( '--step' )
1295                        params.append( str( interval ) )
[12]1296
[37]1297                        params.append( '--start' )
[47]1298                        params.append( str( int( timeserial ) - 1 ) )
[12]1299
[37]1300                        params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat )
1301                        params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) )
[13]1302
[37]1303                        self.rrdm.create( str(rrd_file), params )
1304
[14]1305                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
1306
[47]1307        def update( self, host, metricname, timeserial, metriclist ):
[63]1308                """
1309                Update rrd file for host with metricname
1310                in directory timeserial with metriclist
1311                """
[9]1312
[35]1313                debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
[9]1314
[33]1315                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
[18]1316
[47]1317                update_list = self.makeUpdateList( host, metriclist )
[15]1318
[41]1319                if len( update_list ) > 0:
1320                        ret = self.rrdm.update( str(rrd_file), update_list )
[32]1321
[41]1322                        if ret:
1323                                return 1
[27]1324               
[41]1325                        debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) )
[15]1326
[36]1327                return 0
1328
[169]1329def daemon():
1330        """daemonized threading"""
[8]1331
[169]1332        # Fork the first child
1333        #
1334        pid = os.fork()
1335
1336        if pid > 0:
1337
1338                sys.exit(0)  # end parent
1339
1340        # creates a session and sets the process group ID
1341        #
1342        os.setsid()
1343
1344        # Fork the second child
1345        #
1346        pid = os.fork()
1347
1348        if pid > 0:
1349
1350                sys.exit(0)  # end parent
1351
1352        # Go to the root directory and set the umask
1353        #
1354        os.chdir('/')
1355        os.umask(0)
1356
1357        sys.stdin.close()
1358        sys.stdout.close()
1359        sys.stderr.close()
1360
1361        os.open('/dev/null', 0)
1362        os.dup(0)
1363        os.dup(0)
1364
1365        run()
1366
1367def run():
1368        """Threading start"""
1369
[102]1370        myTorqueProcessor = TorqueXMLProcessor()
1371        myGangliaProcessor = GangliaXMLProcessor()
[8]1372
[169]1373        try:
[102]1374                torque_xml_thread = threading.Thread( None, myTorqueProcessor.run, 'torque_proc_thread' )
1375                ganglia_xml_thread = threading.Thread( None, myGangliaProcessor.run, 'ganglia_proc_thread' )
[22]1376
[169]1377                torque_xml_thread.start()
1378                ganglia_xml_thread.start()
1379               
[176]1380        except thread.error, msg:
[169]1381                debug_msg( 0, 'FATAL ERROR: Unable to start main threads!: '+ str(msg) )
1382                syslog.closelog()
1383                sys.exit(1)
1384               
1385        debug_msg( 0, 'main threading started.' )
[78]1386
[169]1387def main():
1388        """Program startup"""
1389
1390        if( DAEMONIZE and USE_SYSLOG ):
1391                syslog.openlog( 'jobarchived', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
1392
1393        if DAEMONIZE:
1394                daemon()
1395        else:
1396                run()
1397
1398#
[81]1399# Global functions
[169]1400#
[81]1401
[9]1402def check_dir( directory ):
[63]1403        """Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"""
[9]1404
1405        if directory[-1] == '/':
1406                directory = directory[:-1]
1407
1408        return directory
1409
[12]1410def debug_msg( level, msg ):
[169]1411        """Only print msg if correct levels"""
[12]1412
[169]1413        if (not DAEMONIZE and DEBUG_LEVEL >= level):
1414                sys.stderr.write( printTime() + ' - ' + msg + '\n' )
1415       
1416        if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
1417                syslog.syslog( msg )
[12]1418
[46]1419def printTime( ):
[63]1420        """Print current time in human readable format"""
[46]1421
1422        return time.strftime("%a %d %b %Y %H:%M:%S")
1423
[63]1424# Ooohh, someone started me! Let's go..
[9]1425if __name__ == '__main__':
1426        main()
Note: See TracBrowser for help on using the repository browser.