source: branches/1.0/jobarchived/jobarchived.py @ 857

Last change on this file since 857 was 857, checked in by ramonb, 11 years ago

jobarchived.py:

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