source: trunk/jobarchived/jobarchived.py @ 388

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

jobarchived/jobarchived.py:

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