source: trunk/jobarchived/jobarchived.py @ 293

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

jobarchived/jobarchived.py:

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