source: trunk/jobarchived/jobarchived.py @ 292

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

jobarchived/jobarchived.py:

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