source: trunk/jobarchived/jobarchived.py @ 288

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

jobarchived/jobarchived.py:

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