source: trunk/jobarchived/jobarchived.py @ 289

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

jobarchived/jobarchived.py:

  • removed more debug statements
  • Property svn:keywords set to Id
File size: 37.7 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 289 2006-12-21 09:37:02Z 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                for line in os.popen( self.binary + ' info "' + filename + '"' ).readlines():
398
399                        if line.find( 'last_update') != -1:
400
401                                last_update = line.split( ' = ' )[1]
402
403                if last_update:
404                        return last_update
405                else:
406                        return 0
407
408        def perform( self, action, filename, args ):
409                """Perform action on rrd filename with args"""
410
411                arg_string = None
412
413                if type( args ) is not ListType:
414                        debug_msg( 8, 'Arguments needs to be of type List' )
415                        return 1
416
417                for arg in args:
418
419                        if not arg_string:
420
421                                arg_string = arg
422                        else:
423                                arg_string = arg_string + ' ' + arg
424
425                debug_msg( 8, self.binary + ' ' + action + ' ' + filename + ' ' + arg_string  )
426
427                cmd = os.popen( self.binary + ' ' + action + ' ' + filename + ' ' + arg_string )
428                lines = cmd.readlines()
429                cmd.close()
430
431                for line in lines:
432
433                        if line.find( 'ERROR' ) != -1:
434
435                                error_msg = string.join( line.split( ' ' )[1:] )
436                                debug_msg( 8, error_msg )
437                                return 1
438
439                return 0
440
441class XMLProcessor:
442        """Skeleton class for XML processor's"""
443
444        def run( self ):
445                """Do main processing of XML here"""
446
447                pass
448
449class TorqueXMLProcessor( XMLProcessor ):
450        """Main class for processing XML and acting with it"""
451
452        def __init__( self, XMLSource ):
453                """Setup initial XML connection and handlers"""
454
455                self.myXMLGatherer      = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] ) 
456                #self.myXMLSource       = self.myXMLGatherer.getFileObject()
457                self.myXMLSource        = XMLSource
458                self.myXMLHandler       = TorqueXMLHandler()
459                self.myXMLError         = XMLErrorHandler()
460
461                self.config             = GangliaConfigParser( GMETAD_CONF )
462
463        def run( self ):
464                """Main XML processing"""
465
466                debug_msg( 1, 'torque_xml_thread(): started.' )
467
468                while( 1 ):
469
470                        #self.myXMLSource = self.mXMLGatherer.getFileObject()
471                        debug_msg( 1, 'torque_xml_thread(): Parsing..' )
472
473                        my_data = self.myXMLSource.getData()
474
475                        try:
476                                xml.sax.parseString( my_data, self.myXMLHandler, self.myXMLError )
477                        except socket.error, msg:
478                                debug_msg( 0, 'ERROR: Socket error in connect to datasource!: %s' %msg )
479                               
480                        debug_msg( 1, 'torque_xml_thread(): Done parsing.' )
481                        debug_msg( 1, 'torque_xml_thread(): Sleeping.. (%ss)' %(str( self.config.getLowestInterval() ) ) )
482                        time.sleep( self.config.getLowestInterval() )
483
484class TorqueXMLHandler( xml.sax.handler.ContentHandler ):
485        """Parse Torque's jobinfo XML from our plugin"""
486
487        jobAttrs = { }
488
489        def __init__( self ):
490
491                self.ds = DataSQLStore( JOB_SQL_DBASE.split( '/' )[0], JOB_SQL_DBASE.split( '/' )[1] )
492                self.jobs_processed = [ ]
493                self.jobs_to_store = [ ]
494
495        def startDocument( self ):
496
497                self.heartbeat = 0
498
499        def startElement( self, name, attrs ):
500                """
501                This XML will be all gmetric XML
502                so there will be no specific start/end element
503                just one XML statement with all info
504                """
505               
506                jobinfo = { }
507
508                if name == 'CLUSTER':
509
510                        self.clustername = attrs.get( 'NAME', "" )
511
512                elif name == 'METRIC' and self.clustername in ARCHIVE_DATASOURCES:
513
514                        metricname = attrs.get( 'NAME', "" )
515
516                        if metricname == 'MONARCH-HEARTBEAT':
517                                self.heartbeat = attrs.get( 'VAL', "" )
518
519                        elif metricname.find( 'MONARCH-JOB' ) != -1:
520
521                                job_id = metricname.split( 'MONARCH-JOB-' )[1].split( '-' )[0]
522                                val = attrs.get( 'VAL', "" )
523
524                                if not job_id in self.jobs_processed:
525                                        self.jobs_processed.append( job_id )
526
527                                check_change = 0
528
529                                if self.jobAttrs.has_key( job_id ):
530                                        check_change = 1
531
532                                valinfo = val.split( ' ' )
533
534                                for myval in valinfo:
535
536                                        if len( myval.split( '=' ) ) > 1:
537
538                                                valname = myval.split( '=' )[0]
539                                                value = myval.split( '=' )[1]
540
541                                                if valname == 'nodes':
542                                                        value = value.split( ';' )
543
544                                                jobinfo[ valname ] = value
545
546                                if check_change:
547                                        if self.jobinfoChanged( self.jobAttrs, job_id, jobinfo ) and self.jobAttrs[ job_id ]['status'] in [ 'R', 'Q' ]:
548                                                self.jobAttrs[ job_id ]['stop_timestamp'] = ''
549                                                self.jobAttrs[ job_id ] = self.setJobAttrs( self.jobAttrs[ job_id ], jobinfo )
550                                                if not job_id in self.jobs_to_store:
551                                                        self.jobs_to_store.append( job_id )
552
553                                                debug_msg( 6, 'jobinfo for job %s has changed' %job_id )
554                                else:
555                                        self.jobAttrs[ job_id ] = jobinfo
556
557                                        if not job_id in self.jobs_to_store:
558                                                self.jobs_to_store.append( job_id )
559
560                                        debug_msg( 6, 'jobinfo for job %s has changed' %job_id )
561                                       
562        def endDocument( self ):
563                """When all metrics have gone, check if any jobs have finished"""
564
565                if self.heartbeat:
566                        for jobid, jobinfo in self.jobAttrs.items():
567
568                                # This is an old job, not in current jobinfo list anymore
569                                # it must have finished, since we _did_ get a new heartbeat
570                                #
571                                mytime = int( jobinfo['reported'] ) + int( jobinfo['poll_interval'] )
572
573                                if (mytime < self.heartbeat) and (jobid not in self.jobs_processed) and (jobinfo['status'] == 'R'):
574
575                                        if not jobid in self.jobs_processed:
576                                                self.jobs_processed.append( jobid )
577
578                                        self.jobAttrs[ jobid ]['status'] = 'F'
579                                        self.jobAttrs[ jobid ]['stop_timestamp'] = str( mytime )
580
581                                        if not jobid in self.jobs_to_store:
582                                                self.jobs_to_store.append( jobid )
583
584                        debug_msg( 1, 'torque_xml_thread(): Storing..' )
585
586                        for jobid in self.jobs_to_store:
587                                if self.jobAttrs[ jobid ]['status'] in [ 'R', 'Q', 'F' ]:
588
589                                        self.ds.storeJobInfo( jobid, self.jobAttrs[ jobid ] )
590
591                                        if self.jobAttrs[ jobid ]['status'] == 'F':
592                                                del self.jobAttrs[ jobid ]
593
594                        debug_msg( 1, 'torque_xml_thread(): Done storing.' )
595
596                        self.jobs_processed = [ ]
597                        self.jobs_to_store = [ ]
598
599        def setJobAttrs( self, old, new ):
600                """
601                Set new job attributes in old, but not lose existing fields
602                if old attributes doesn't have those
603                """
604
605                for valname, value in new.items():
606                        old[ valname ] = value
607
608                return old
609               
610
611        def jobinfoChanged( self, jobattrs, jobid, jobinfo ):
612                """
613                Check if jobinfo has changed from jobattrs[jobid]
614                if it's report time is bigger than previous one
615                and it is report time is recent (equal to heartbeat)
616                """
617
618                ignore_changes = [ 'reported' ]
619
620                if jobattrs.has_key( jobid ):
621
622                        for valname, value in jobinfo.items():
623
624                                if valname not in ignore_changes:
625
626                                        if jobattrs[ jobid ].has_key( valname ):
627
628                                                if value != jobattrs[ jobid ][ valname ]:
629
630                                                        if jobinfo['reported'] > jobattrs[ jobid ][ 'reported' ] and jobinfo['reported'] == self.heartbeat:
631                                                                return 1
632
633                                        else:
634                                                return 1
635
636                return 0
637
638class GangliaXMLHandler( xml.sax.handler.ContentHandler ):
639        """Parse Ganglia's XML"""
640
641        def __init__( self, config ):
642                """Setup initial variables and gather info on existing rrd archive"""
643
644                self.config = config
645                self.clusters = { }
646                debug_msg( 1, 'Checking existing toga rrd archive..' )
647                self.gatherClusters()
648                debug_msg( 1, 'Check done.' )
649
650        def gatherClusters( self ):
651                """Find all existing clusters in archive dir"""
652
653                archive_dir = check_dir(ARCHIVE_PATH)
654
655                hosts = [ ]
656
657                if os.path.exists( archive_dir ):
658
659                        dirlist = os.listdir( archive_dir )
660
661                        for item in dirlist:
662
663                                clustername = item
664
665                                if not self.clusters.has_key( clustername ) and clustername in ARCHIVE_DATASOURCES:
666
667                                        self.clusters[ clustername ] = RRDHandler( self.config, clustername )
668
669        def startElement( self, name, attrs ):
670                """Memorize appropriate data from xml start tags"""
671
672                if name == 'GANGLIA_XML':
673
674                        self.XMLSource = attrs.get( 'SOURCE', "" )
675                        self.gangliaVersion = attrs.get( 'VERSION', "" )
676
677                        debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
678
679                elif name == 'GRID':
680
681                        self.gridName = attrs.get( 'NAME', "" )
682                        self.time = attrs.get( 'LOCALTIME', "" )
683
684                        debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
685
686                elif name == 'CLUSTER':
687
688                        self.clusterName = attrs.get( 'NAME', "" )
689                        self.time = attrs.get( 'LOCALTIME', "" )
690
691                        if not self.clusters.has_key( self.clusterName ) and self.clusterName in ARCHIVE_DATASOURCES:
692
693                                self.clusters[ self.clusterName ] = RRDHandler( self.config, self.clusterName )
694
695                                debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
696
697                elif name == 'HOST' and self.clusterName in ARCHIVE_DATASOURCES:     
698
699                        self.hostName = attrs.get( 'NAME', "" )
700                        self.hostIp = attrs.get( 'IP', "" )
701                        self.hostReported = attrs.get( 'REPORTED', "" )
702
703                        debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
704
705                elif name == 'METRIC' and self.clusterName in ARCHIVE_DATASOURCES:
706
707                        type = attrs.get( 'TYPE', "" )
708                       
709                        exclude_metric = False
710                       
711                        for ex_metricstr in ARCHIVE_EXCLUDE_METRICS:
712
713                                orig_name = attrs.get( 'NAME', "" )     
714
715                                if string.lower( orig_name ) == string.lower( ex_metricstr ):
716                               
717                                        exclude_metric = True
718
719                                elif re.match( ex_metricstr, orig_name ):
720
721                                        exclude_metric = True
722
723                        if type not in UNSUPPORTED_ARCHIVE_TYPES and not exclude_metric:
724
725                                myMetric = { }
726                                myMetric['name'] = attrs.get( 'NAME', "" )
727                                myMetric['val'] = attrs.get( 'VAL', "" )
728                                myMetric['time'] = self.hostReported
729
730                                self.clusters[ self.clusterName ].memMetric( self.hostName, myMetric )
731
732                                debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
733
734        def storeMetrics( self ):
735                """Store metrics of each cluster rrd handler"""
736
737                for clustername, rrdh in self.clusters.items():
738
739                        ret = rrdh.storeMetrics()
740
741                        if ret:
742                                debug_msg( 9, 'An error occured while storing metrics for cluster %s' %clustername )
743                                return 1
744
745                return 0
746
747class XMLErrorHandler( xml.sax.handler.ErrorHandler ):
748
749        def error( self, exception ):
750                """Recoverable error"""
751
752                debug_msg( 0, 'Recoverable XML error ' + str( exception ) + ' ignored.' )
753
754        def fatalError( self, exception ):
755                """Non-recoverable error"""
756
757                exception_str = str( exception )
758
759                # Ignore 'no element found' errors
760                if exception_str.find( 'no element found' ) != -1:
761                        debug_msg( 0, 'No XML data found: Socket not (re)connected or datasource not available.' )
762                        return 0
763
764                debug_msg( 0, 'FATAL ERROR: Non-recoverable XML error ' + str( exception ) )
765                sys.exit( 1 )
766
767        def warning( self, exception ):
768                """Warning"""
769
770                debug_msg( 0, 'Warning ' + str( exception ) )
771
772class XMLGatherer:
773        """Setup a connection and file object to Ganglia's XML"""
774
775        s               = None
776        fd              = None
777        data            = None
778
779        # Time since the last update
780        #
781        LAST_UPDATE     = 0
782
783        # Minimum interval between updates
784        #
785        MIN_UPDATE_INT  = 10
786
787        # Is a update occuring now
788        #
789        update_now      = False
790
791        def __init__( self, host, port ):
792                """Store host and port for connection"""
793
794                self.host = host
795                self.port = port
796
797                self.retrieveData()
798
799        def retrieveData( self ):
800                """Setup connection to XML source"""
801
802                self.update_now = True
803
804                for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ):
805
806                        af, socktype, proto, canonname, sa = res
807
808                        try:
809
810                                self.s = socket.socket( af, socktype, proto )
811
812                        except socket.error, msg:
813
814                                self.s = None
815                                continue
816
817                        try:
818
819                                self.s.connect( sa )
820
821                        except socket.error, msg:
822
823                                self.disconnect()
824                                continue
825
826                        break
827
828                if self.s is None:
829
830                        debug_msg( 0, 'FATAL ERROR: Could not open socket or unable to connect to datasource!' )
831                        self.update_now = False
832                        sys.exit( 1 )
833
834                else:
835                        self.s.send( '\n' )
836
837                        my_fp                   = self.s.makefile( 'r' )
838                        my_data                 = my_fp.readlines()
839                        my_data                 = string.join( my_data, '' )
840
841                        self.data               = my_data
842
843                        self.LAST_UPDATE        = time.time()
844
845                self.update_now = False
846
847        def disconnect( self ):
848                """Close socket"""
849
850                if self.s:
851                        #self.s.shutdown( 2 )
852                        self.s.close()
853                        self.s = None
854
855        def __del__( self ):
856                """Kill the socket before we leave"""
857
858                self.disconnect()
859
860        def reGetData( self ):
861                """Reconnect"""
862
863                while self.update_now:
864
865                        # Must be another update in progress:
866                        # Wait until the update is complete
867                        #
868                        time.sleep( 1 )
869
870                if self.s:
871                        self.disconnect()
872
873                self.retrieveData()
874
875        def getData( self ):
876
877                """Return the XML data"""
878
879                # If more than MIN_UPDATE_INT seconds passed since last data update
880                # update the XML first before returning it
881                #
882
883                cur_time        = time.time()
884
885                if ( cur_time - self.LAST_UPDATE ) > self.MIN_UPDATE_INT:
886
887                        self.reGetData()
888
889                while self.update_now:
890
891                        # Must be another update in progress:
892                        # Wait until the update is complete
893                        #
894                        time.sleep( 1 )
895                       
896                return self.data
897
898        def makeFileDescriptor( self ):
899                """Make file descriptor that points to our socket connection"""
900
901                self.reconnect()
902
903                if self.s:
904                        self.fd = self.s.makefile( 'r' )
905
906        def getFileObject( self ):
907                """Connect, and return a file object"""
908
909                self.makeFileDescriptor()
910
911                if self.fd:
912                        return self.fd
913
914class GangliaXMLProcessor( XMLProcessor ):
915        """Main class for processing XML and acting with it"""
916
917        def __init__( self, XMLSource ):
918                """Setup initial XML connection and handlers"""
919
920                self.config             = GangliaConfigParser( GMETAD_CONF )
921
922                self.myXMLGatherer      = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] ) 
923                #self.myXMLSource       = self.myXMLGatherer.getFileObject()
924                self.myXMLSource        = XMLSource
925                self.myXMLHandler       = GangliaXMLHandler( self.config )
926                self.myXMLError         = XMLErrorHandler()
927
928        def run( self ):
929                """Main XML processing; start a xml and storethread"""
930
931                xml_thread = threading.Thread( None, self.processXML, 'xmlthread' )
932                store_thread = threading.Thread( None, self.storeMetrics, 'storethread' )
933
934                while( 1 ):
935
936                        if not xml_thread.isAlive():
937                                # Gather XML at the same interval as gmetad
938
939                                # threaded call to: self.processXML()
940                                #
941                                try:
942                                        xml_thread = threading.Thread( None, self.processXML, 'xml_thread' )
943                                        xml_thread.start()
944                                except thread.error, msg:
945                                        debug_msg( 0, 'ERROR: Unable to start xml_thread!: '+str(msg))
946                                        #return 1
947
948                        if not store_thread.isAlive():
949                                # Store metrics every .. sec
950
951                                # threaded call to: self.storeMetrics()
952                                #
953                                try:
954                                        store_thread = threading.Thread( None, self.storeMetrics, 'store_thread' )
955                                        store_thread.start()
956                                except thread.error, msg:
957                                        debug_msg( 0, 'ERROR: Unable to start store_thread!: '+str(msg))
958                                        #return 1
959               
960                        # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway
961                        time.sleep( 1 ) 
962
963        def storeMetrics( self ):
964                """Store metrics retained in memory to disk"""
965
966                # Store metrics somewhere between every 360 and 640 seconds
967                #
968                STORE_INTERVAL = random.randint( 360, 640 )
969
970                try:
971                        store_metric_thread = threading.Thread( None, self.storeThread, 'store_metric_thread' )
972                        store_metric_thread.start()
973                except thread.error, msg:
974                        debug_msg( 0, 'ERROR: Unable to start ganglia_store_thread()!: '+str(msg) )
975                        return 1
976
977                debug_msg( 1, 'ganglia_store_thread(): started.' )
978
979                debug_msg( 1, 'ganglia_store_thread(): Sleeping.. (%ss)' %STORE_INTERVAL )
980                time.sleep( STORE_INTERVAL )
981                debug_msg( 1, 'ganglia_store_thread(): Done sleeping.' )
982
983                if store_metric_thread.isAlive():
984
985                        debug_msg( 1, 'ganglia_store_thread(): storemetricthread() still running, waiting to finish..' )
986                        store_metric_thread.join( STORE_TIMEOUT ) # Maximum time is for storing thread to finish
987                        debug_msg( 1, 'ganglia_store_thread(): Done waiting.' )
988
989                debug_msg( 1, 'ganglia_store_thread(): finished.' )
990
991                return 0
992
993        def storeThread( self ):
994                """Actual metric storing thread"""
995
996                debug_msg( 1, 'ganglia_store_metric_thread(): started.' )
997                debug_msg( 1, 'ganglia_store_metric_thread(): Storing data..' )
998                ret = self.myXMLHandler.storeMetrics()
999                if ret > 0:
1000                        debug_msg( 0, 'ganglia_store_metric_thread(): UNKNOWN ERROR %s while storing Metrics!' %str(ret) )
1001                debug_msg( 1, 'ganglia_store_metric_thread(): Done storing.' )
1002                debug_msg( 1, 'ganglia_store_metric_thread(): finished.' )
1003               
1004                return 0
1005
1006        def processXML( self ):
1007                """Process XML"""
1008
1009                try:
1010                        parsethread = threading.Thread( None, self.parseThread, 'parsethread' )
1011                        parsethread.start()
1012                except thread.error, msg:
1013                        debug_msg( 0, 'ERROR: Unable to start ganglia_xml_thread()!: ' + str(msg) )
1014                        return 1
1015
1016                debug_msg( 1, 'ganglia_xml_thread(): started.' )
1017
1018                debug_msg( 1, 'ganglia_xml_thread(): Sleeping.. (%ss)' %self.config.getLowestInterval() )
1019                time.sleep( float( self.config.getLowestInterval() ) ) 
1020                debug_msg( 1, 'ganglia_xml_thread(): Done sleeping.' )
1021
1022                if parsethread.isAlive():
1023
1024                        debug_msg( 1, 'ganglia_xml_thread(): parsethread() still running, waiting (%ss) to finish..' %PARSE_TIMEOUT )
1025                        parsethread.join( PARSE_TIMEOUT ) # Maximum time for XML thread to finish
1026                        debug_msg( 1, 'ganglia_xml_thread(): Done waiting.' )
1027
1028                debug_msg( 1, 'ganglia_xml_thread(): finished.' )
1029
1030                return 0
1031
1032        def parseThread( self ):
1033                """Actual parsing thread"""
1034
1035                debug_msg( 1, 'ganglia_parse_thread(): started.' )
1036                debug_msg( 1, 'ganglia_parse_thread(): Parsing XML..' )
1037                #self.myXMLSource = self.myXMLGatherer.getFileObject()
1038               
1039                my_data = self.myXMLSource.getData()
1040
1041                try:
1042                        xml.sax.parseString( my_data, self.myXMLHandler, self.myXMLError )
1043                except socket.error, msg:
1044                        debug_msg( 0, 'ERROR: Socket error in connect to datasource!: %s' %msg )
1045
1046                debug_msg( 1, 'ganglia_parse_thread(): Done parsing.' )
1047                debug_msg( 1, 'ganglia_parse_thread(): finished.' )
1048
1049                return 0
1050
1051class GangliaConfigParser:
1052
1053        sources = [ ]
1054
1055        def __init__( self, config ):
1056                """Parse some stuff from our gmetad's config, such as polling interval"""
1057
1058                self.config = config
1059                self.parseValues()
1060
1061        def parseValues( self ):
1062                """Parse certain values from gmetad.conf"""
1063
1064                readcfg = open( self.config, 'r' )
1065
1066                for line in readcfg.readlines():
1067
1068                        if line.count( '"' ) > 1:
1069
1070                                if line.find( 'data_source' ) != -1 and line[0] != '#':
1071
1072                                        source = { }
1073                                        source['name'] = line.split( '"' )[1]
1074                                        source_words = line.split( '"' )[2].split( ' ' )
1075
1076                                        for word in source_words:
1077
1078                                                valid_interval = 1
1079
1080                                                for letter in word:
1081
1082                                                        if letter not in string.digits:
1083
1084                                                                valid_interval = 0
1085
1086                                                if valid_interval and len(word) > 0:
1087
1088                                                        source['interval'] = word
1089                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
1090       
1091                                        # No interval found, use Ganglia's default     
1092                                        if not source.has_key( 'interval' ):
1093                                                source['interval'] = 15
1094                                                debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
1095
1096                                        self.sources.append( source )
1097
1098        def getInterval( self, source_name ):
1099                """Return interval for source_name"""
1100
1101                for source in self.sources:
1102
1103                        if source['name'] == source_name:
1104
1105                                return source['interval']
1106
1107                return None
1108
1109        def getLowestInterval( self ):
1110                """Return the lowest interval of all clusters"""
1111
1112                lowest_interval = 0
1113
1114                for source in self.sources:
1115
1116                        if not lowest_interval or source['interval'] <= lowest_interval:
1117
1118                                lowest_interval = source['interval']
1119
1120                # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays
1121                if lowest_interval:
1122                        return lowest_interval
1123                else:
1124                        return 15
1125
1126class RRDHandler:
1127        """Class for handling RRD activity"""
1128
1129        myMetrics = { }
1130        lastStored = { }
1131        timeserials = { }
1132        slot = None
1133
1134        def __init__( self, config, cluster ):
1135                """Setup initial variables"""
1136
1137                self.block = 0
1138                self.cluster = cluster
1139                self.config = config
1140                self.slot = threading.Lock()
1141                self.rrdm = RRDMutator( RRDTOOL )
1142                self.gatherLastUpdates()
1143
1144        def gatherLastUpdates( self ):
1145                """Populate the lastStored list, containing timestamps of all last updates"""
1146
1147                cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster )
1148
1149                hosts = [ ]
1150
1151                if os.path.exists( cluster_dir ):
1152
1153                        dirlist = os.listdir( cluster_dir )
1154
1155                        for dir in dirlist:
1156
1157                                hosts.append( dir )
1158
1159                for host in hosts:
1160
1161                        host_dir = cluster_dir + '/' + host
1162                        dirlist = os.listdir( host_dir )
1163
1164                        for dir in dirlist:
1165
1166                                if not self.timeserials.has_key( host ):
1167
1168                                        self.timeserials[ host ] = [ ]
1169
1170                                self.timeserials[ host ].append( dir )
1171
1172                        last_serial = self.getLastRrdTimeSerial( host )
1173                        if last_serial:
1174
1175                                metric_dir = cluster_dir + '/' + host + '/' + last_serial
1176                                if os.path.exists( metric_dir ):
1177
1178                                        dirlist = os.listdir( metric_dir )
1179
1180                                        for file in dirlist:
1181
1182                                                metricname = file.split( '.rrd' )[0]
1183
1184                                                if not self.lastStored.has_key( host ):
1185
1186                                                        self.lastStored[ host ] = { }
1187
1188                                                self.lastStored[ host ][ metricname ] = self.rrdm.grabLastUpdate( metric_dir + '/' + file )
1189
1190        def getClusterName( self ):
1191                """Return clustername"""
1192
1193                return self.cluster
1194
1195        def memMetric( self, host, metric ):
1196                """Store metric from host in memory"""
1197
1198                # <ATOMIC>
1199                #
1200                self.slot.acquire()
1201               
1202                if self.myMetrics.has_key( host ):
1203
1204                        if self.myMetrics[ host ].has_key( metric['name'] ):
1205
1206                                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
1207
1208                                        if mymetric['time'] == metric['time']:
1209
1210                                                # Allready have this metric, abort
1211                                                self.slot.release()
1212                                                return 1
1213                        else:
1214                                self.myMetrics[ host ][ metric['name'] ] = [ ]
1215                else:
1216                        self.myMetrics[ host ] = { }
1217                        self.myMetrics[ host ][ metric['name'] ] = [ ]
1218
1219                # Push new metric onto stack
1220                # atomic code; only 1 thread at a time may access the stack
1221
1222                self.myMetrics[ host ][ metric['name'] ].append( metric )
1223
1224                self.slot.release()
1225                #
1226                # </ATOMIC>
1227
1228        def makeUpdateList( self, host, metriclist ):
1229                """
1230                Make a list of update values for rrdupdate
1231                but only those that we didn't store before
1232                """
1233
1234                update_list = [ ]
1235                metric = None
1236
1237                while len( metriclist ) > 0:
1238
1239                        metric = metriclist.pop( 0 )
1240
1241                        if self.checkStoreMetric( host, metric ):
1242                                update_list.append( '%s:%s' %( metric['time'], metric['val'] ) )
1243
1244                return update_list
1245
1246        def checkStoreMetric( self, host, metric ):
1247                """Check if supplied metric if newer than last one stored"""
1248
1249                if self.lastStored.has_key( host ):
1250
1251                        if self.lastStored[ host ].has_key( metric['name'] ):
1252
1253                                if metric['time'] <= self.lastStored[ host ][ metric['name'] ]:
1254
1255                                        # This is old
1256                                        return 0
1257
1258                return 1
1259
1260        def memLastUpdate( self, host, metricname, metriclist ):
1261                """
1262                Memorize the time of the latest metric from metriclist
1263                but only if it wasn't allready memorized
1264                """
1265
1266                if not self.lastStored.has_key( host ):
1267                        self.lastStored[ host ] = { }
1268
1269                last_update_time = 0
1270
1271                for metric in metriclist:
1272
1273                        if metric['name'] == metricname:
1274
1275                                if metric['time'] > last_update_time:
1276
1277                                        last_update_time = metric['time']
1278
1279                if self.lastStored[ host ].has_key( metricname ):
1280                       
1281                        if last_update_time <= self.lastStored[ host ][ metricname ]:
1282                                return 1
1283
1284                self.lastStored[ host ][ metricname ] = last_update_time
1285
1286        def storeMetrics( self ):
1287                """
1288                Store all metrics from memory to disk
1289                and do it to the RRD's in appropriate timeperiod directory
1290                """
1291
1292                for hostname, mymetrics in self.myMetrics.items():     
1293
1294                        for metricname, mymetric in mymetrics.items():
1295
1296                                metrics_to_store = [ ]
1297
1298                                # Pop metrics from stack for storing until none is left
1299                                # atomic code: only 1 thread at a time may access myMetrics
1300
1301                                # <ATOMIC>
1302                                #
1303                                self.slot.acquire() 
1304
1305                                while len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1306
1307                                        if len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1308
1309                                                try:
1310                                                        metrics_to_store.append( self.myMetrics[ hostname ][ metricname ].pop( 0 ) )
1311                                                except IndexError, msg:
1312
1313                                                        # Somehow sometimes myMetrics[ hostname ][ metricname ]
1314                                                        # is still len 0 when the statement is executed.
1315                                                        # Just ignore indexerror's..
1316                                                        pass
1317
1318                                self.slot.release()
1319                                #
1320                                # </ATOMIC>
1321
1322                                # Create a mapping table, each metric to the period where it should be stored
1323                                #
1324                                metric_serial_table = self.determineSerials( hostname, metricname, metrics_to_store )
1325
1326                                update_rets = [ ]
1327
1328                                for period, pmetric in metric_serial_table.items():
1329
1330                                        create_ret = self.createCheck( hostname, metricname, period )   
1331
1332                                        update_ret = self.update( hostname, metricname, period, pmetric )
1333
1334                                        if update_ret == 0:
1335
1336                                                debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
1337                                        else:
1338                                                debug_msg( 9, 'metric update failed' )
1339
1340                                        update_rets.append( create_ret )
1341                                        update_rets.append( update_ret )
1342
1343                                # Lets ignore errors here for now, we need to make sure last update time
1344                                # is correct!
1345                                #
1346                                #if not (1) in update_rets:
1347
1348                                self.memLastUpdate( hostname, metricname, metrics_to_store )
1349
1350        def makeTimeSerial( self ):
1351                """Generate a time serial. Seconds since epoch"""
1352
1353                # Seconds since epoch
1354                mytime = int( time.time() )
1355
1356                return mytime
1357
1358        def makeRrdPath( self, host, metricname, timeserial ):
1359                """Make a RRD location/path and filename"""
1360
1361                rrd_dir = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
1362                rrd_file = '%s/%s.rrd' %( rrd_dir, metricname )
1363
1364                return rrd_dir, rrd_file
1365
1366        def getLastRrdTimeSerial( self, host ):
1367                """Find the last timeserial (directory) for this host"""
1368
1369                newest_timeserial = 0
1370
1371                for dir in self.timeserials[ host ]:
1372
1373                        valid_dir = 1
1374
1375                        for letter in dir:
1376                                if letter not in string.digits:
1377                                        valid_dir = 0
1378
1379                        if valid_dir:
1380                                timeserial = dir
1381                                if timeserial > newest_timeserial:
1382                                        newest_timeserial = timeserial
1383
1384                if newest_timeserial:
1385                        return newest_timeserial
1386                else:
1387                        return 0
1388
1389        def determinePeriod( self, host, check_serial ):
1390                """Determine to which period (directory) this time(serial) belongs"""
1391
1392                period_serial = 0
1393
1394                if self.timeserials.has_key( host ):
1395
1396                        for serial in self.timeserials[ host ]:
1397
1398                                if check_serial >= serial and period_serial < serial:
1399
1400                                        period_serial = serial
1401
1402                return period_serial
1403
1404        def determineSerials( self, host, metricname, metriclist ):
1405                """
1406                Determine the correct serial and corresponding rrd to store
1407                for a list of metrics
1408                """
1409
1410                metric_serial_table = { }
1411
1412                for metric in metriclist:
1413
1414                        if metric['name'] == metricname:
1415
1416                                period = self.determinePeriod( host, metric['time'] )   
1417
1418                                archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60)
1419
1420                                if (int( metric['time'] ) - int( period ) ) > archive_secs:
1421
1422                                        # This one should get it's own new period
1423                                        period = metric['time']
1424
1425                                        if not self.timeserials.has_key( host ):
1426                                                self.timeserials[ host ] = [ ]
1427
1428                                        self.timeserials[ host ].append( period )
1429
1430                                if not metric_serial_table.has_key( period ):
1431
1432                                        metric_serial_table[ period ] = [ ]
1433
1434                                metric_serial_table[ period ].append( metric )
1435
1436                return metric_serial_table
1437
1438        def createCheck( self, host, metricname, timeserial ):
1439                """Check if an rrd allready exists for this metric, create if not"""
1440
1441                debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1442               
1443                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
1444
1445                if not os.path.exists( rrd_dir ):
1446
1447                        try:
1448                                os.makedirs( rrd_dir )
1449
1450                        except os.OSError, msg:
1451
1452                                if msg.find( 'File exists' ) != -1:
1453
1454                                        # Ignore exists errors
1455                                        pass
1456
1457                                else:
1458
1459                                        print msg
1460                                        return
1461
1462                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
1463
1464                if not os.path.exists( rrd_file ):
1465
1466                        interval = self.config.getInterval( self.cluster )
1467                        heartbeat = 8 * int( interval )
1468
1469                        params = [ ]
1470
1471                        params.append( '--step' )
1472                        params.append( str( interval ) )
1473
1474                        params.append( '--start' )
1475                        params.append( str( int( timeserial ) - 1 ) )
1476
1477                        params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat )
1478                        params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) )
1479
1480                        self.rrdm.create( str(rrd_file), params )
1481
1482                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
1483
1484        def update( self, host, metricname, timeserial, metriclist ):
1485                """
1486                Update rrd file for host with metricname
1487                in directory timeserial with metriclist
1488                """
1489
1490                debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1491
1492                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
1493
1494                update_list = self.makeUpdateList( host, metriclist )
1495
1496                if len( update_list ) > 0:
1497                        ret = self.rrdm.update( str(rrd_file), update_list )
1498
1499                        if ret:
1500                                return 1
1501               
1502                        debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) )
1503
1504                return 0
1505
1506def daemon():
1507        """daemonized threading"""
1508
1509        # Fork the first child
1510        #
1511        pid = os.fork()
1512
1513        if pid > 0:
1514
1515                sys.exit(0)  # end parent
1516
1517        # creates a session and sets the process group ID
1518        #
1519        os.setsid()
1520
1521        # Fork the second child
1522        #
1523        pid = os.fork()
1524
1525        if pid > 0:
1526
1527                sys.exit(0)  # end parent
1528
1529        # Go to the root directory and set the umask
1530        #
1531        os.chdir('/')
1532        os.umask(0)
1533
1534        sys.stdin.close()
1535        sys.stdout.close()
1536        sys.stderr.close()
1537
1538        os.open('/dev/null', os.O_RDWR)
1539        os.dup2(0, 1)
1540        os.dup2(0, 2)
1541
1542        run()
1543
1544def run():
1545        """Threading start"""
1546
1547        myXMLSource             = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] )
1548
1549        myTorqueProcessor       = TorqueXMLProcessor( myXMLSource )
1550        myGangliaProcessor      = GangliaXMLProcessor( myXMLSource )
1551
1552        try:
1553                torque_xml_thread = threading.Thread( None, myTorqueProcessor.run, 'torque_proc_thread' )
1554                ganglia_xml_thread = threading.Thread( None, myGangliaProcessor.run, 'ganglia_proc_thread' )
1555
1556                torque_xml_thread.start()
1557                ganglia_xml_thread.start()
1558               
1559        except thread.error, msg:
1560                debug_msg( 0, 'FATAL ERROR: Unable to start main threads!: '+ str(msg) )
1561                syslog.closelog()
1562                sys.exit(1)
1563               
1564        debug_msg( 0, 'main threading started.' )
1565
1566def main():
1567        """Program startup"""
1568
1569        if not processArgs( sys.argv[1:] ):
1570                sys.exit( 1 )
1571
1572        if( DAEMONIZE and USE_SYSLOG ):
1573                syslog.openlog( 'jobarchived', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
1574
1575        if DAEMONIZE:
1576                daemon()
1577        else:
1578                run()
1579
1580#
1581# Global functions
1582#
1583
1584def check_dir( directory ):
1585        """Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"""
1586
1587        if directory[-1] == '/':
1588                directory = directory[:-1]
1589
1590        return directory
1591
1592def debug_msg( level, msg ):
1593        """Only print msg if correct levels"""
1594
1595        if (not DAEMONIZE and DEBUG_LEVEL >= level):
1596                sys.stderr.write( printTime() + ' - ' + msg + '\n' )
1597       
1598        if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
1599                syslog.syslog( msg )
1600
1601def printTime( ):
1602        """Print current time in human readable format"""
1603
1604        return time.strftime("%a %d %b %Y %H:%M:%S")
1605
1606# Ooohh, someone started me! Let's go..
1607if __name__ == '__main__':
1608        main()
Note: See TracBrowser for help on using the repository browser.