source: trunk/jobarchived/jobarchived.py @ 369

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

jobarchived/jobarchived.py:

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