source: trunk/jobarchived/jobarchived.py @ 466

Last change on this file since 466 was 466, checked in by bastiaans, 16 years ago

jobarchived/jobarchived.py:

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