source: branches/1.1/jobarchived/jobarchived.py @ 929

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