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

Last change on this file since 841 was 829, checked in by ramonb, 11 years ago
  • updated version number to 1.0
  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 60.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 829 2013-04-12 13:49:35Z 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 checkStaleJobs( self ):
571
572        # Locate all jobs in the database that are not set to finished
573        #
574        q = "SELECT * from jobs WHERE job_status != 'F'"
575
576        r = self.getDatabase( q )
577
578        if len( r ) == 0:
579
580            return None
581
582        cleanjobs    = [ ]
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 == 'Q' or not job_start_timestamp:
599
600                cleanjobs.append( job_id )
601
602            else:
603
604                start_timestamp = int( job_start_timestamp )
605
606                # If it was set to running longer than JOB_TIMEOUT
607                # close the job: it probably finished while we were not running
608                #
609                if ( cur_time - start_timestamp ) > jobtimeout_sec:
610
611                    if job_requested_time:
612
613                        rtime_epoch    = reqtime2epoch( job_requested_time )
614                    else:
615                        rtime_epoch    = None
616                   
617                    timeoutjobs.append( (job_id, job_start_timestamp, rtime_epoch) )
618
619        debug_msg( 1, 'Found ' + str( len( cleanjobs ) ) + ' stale jobs in database: deleting entries' )
620
621        # Purge these from database
622        #
623        for j in cleanjobs:
624
625            q = "DELETE FROM jobs WHERE job_id = '" + str( j ) + "'"
626            self.setDatabase( q )
627
628        debug_msg( 1, 'Found ' + str( len( timeoutjobs ) ) + ' timed out jobs in database: closing entries' )
629
630        # Close these jobs in the database
631        # update the stop_timestamp to: start_timestamp + requested wallclock
632        # and set state: finished
633        #
634        for j in timeoutjobs:
635
636            ( i, s, r )        = j
637
638            if r:
639                new_end_timestamp    = int( s ) + r
640
641            q = "UPDATE jobs SET job_status='F',job_stop_timestamp = '" + str( new_end_timestamp ) + "' WHERE job_id = '" + str(i) + "'"
642            self.setDatabase( q )
643
644class RRDMutator:
645    """A class for performing RRD mutations"""
646
647    binary = None
648
649    def __init__( self, binary=None ):
650        """Set alternate binary if supplied"""
651
652        if binary:
653            self.binary = binary
654
655    def create( self, filename, args ):
656        """Create a new rrd with args"""
657
658        global MODRRDTOOL
659
660        if MODRRDTOOL:
661            return self.perform( 'create', filename, args )
662        else:
663            return self.perform( 'create', '"' + filename + '"', args )
664
665    def update( self, filename, args ):
666        """Update a rrd with args"""
667
668        global MODRRDTOOL
669
670        if MODRRDTOOL:
671            return self.perform( 'update', filename, args )
672        else:
673            return self.perform( 'update', '"' + filename + '"', args )
674
675    def grabLastUpdate( self, filename ):
676        """Determine the last update time of filename rrd"""
677
678        global MODRRDTOOL
679
680        last_update = 0
681
682        # Use the py-rrdtool module if it's available on this system
683        #
684        if MODRRDTOOL:
685
686            debug_msg( 8, 'rrdtool.info( ' + filename + ' )' )
687
688            rrd_header     = { }
689
690            try:
691                rrd_header    = rrdtool.info( filename )
692            except rrdtool.error, msg:
693                debug_msg( 8, str( msg ) )
694
695            if rrd_header.has_key( 'last_update' ):
696                return last_update
697            else:
698                return 0
699
700        # For backwards compatiblity: use the rrdtool binary if py-rrdtool is unavailable
701        # DEPRECATED (slow!)
702        #
703        else:
704            debug_msg( 8, self.binary + ' info ' + filename )
705
706            my_pipe        = os.popen( self.binary + ' info "' + filename + '"' )
707
708            for line in my_pipe.readlines():
709
710                if line.find( 'last_update') != -1:
711
712                    last_update = line.split( ' = ' )[1]
713
714            if my_pipe:
715
716                my_pipe.close()
717
718            if last_update:
719                return last_update
720            else:
721                return 0
722
723
724    def perform( self, action, filename, args ):
725        """Perform action on rrd filename with args"""
726
727        global MODRRDTOOL
728
729        arg_string = None
730
731        if type( args ) is not ListType:
732            debug_msg( 8, 'Arguments needs to be of type List' )
733            return 1
734
735        for arg in args:
736
737            if not arg_string:
738
739                arg_string = arg
740            else:
741                arg_string = arg_string + ' ' + arg
742
743        if MODRRDTOOL:
744
745            debug_msg( 8, 'rrdtool.' + action + "( " + filename + ' ' + arg_string + ")" )
746
747            try:
748                debug_msg( 8, "filename '" + str(filename) + "' type "+ str(type(filename)) + " args " + str( args ) )
749
750                if action == 'create':
751
752                    rrdtool.create( str( filename ), *args )
753
754                elif action == 'update':
755
756                    rrdtool.update( str( filename ), *args )
757
758            except rrdtool.error, msg:
759
760                error_msg = str( msg )
761                debug_msg( 8, error_msg )
762                return 1
763
764        else:
765
766            debug_msg( 8, self.binary + ' ' + action + ' ' + filename + ' ' + arg_string  )
767
768            cmd     = os.popen( self.binary + ' ' + action + ' ' + filename + ' ' + arg_string )
769            lines   = cmd.readlines()
770
771            cmd.close()
772
773            for line in lines:
774
775                if line.find( 'ERROR' ) != -1:
776
777                    error_msg = string.join( line.split( ' ' )[1:] )
778                    debug_msg( 8, error_msg )
779                    return 1
780
781        return 0
782
783class XMLProcessor:
784    """Skeleton class for XML processor's"""
785
786    def run( self ):
787        """Do main processing of XML here"""
788
789        pass
790
791class JobXMLProcessor( XMLProcessor ):
792    """Main class for processing XML and acting with it"""
793
794    def __init__( self, XMLSource, DataStore ):
795        """Setup initial XML connection and handlers"""
796
797        self.myXMLSource  = XMLSource
798        self.myXMLHandler = JobXMLHandler( DataStore )
799        self.myXMLError   = XMLErrorHandler()
800
801        self.config       = GangliaConfigParser( GMETAD_CONF )
802
803        self.kill_thread  = False
804
805    def killThread( self ):
806
807        self.kill_thread  = True
808
809    def run( self ):
810        """Main XML processing"""
811
812        debug_msg( 1, 'job_xml_thread(): started.' )
813
814        while( 1 ):
815
816            debug_msg( 1, 'job_xml_thread(): Retrieving XML data..' )
817
818            my_data    = self.myXMLSource.getData()
819
820            debug_msg( 1, 'job_xml_thread(): Done retrieving: data size %d' %len(my_data) )
821
822            if my_data:
823                debug_msg( 1, 'job_xml_thread(): Parsing XML..' )
824
825                xml.sax.parseString( my_data, self.myXMLHandler, self.myXMLError )
826
827                debug_msg( 1, 'job_xml_thread(): Done parsing.' )
828            else:
829                debug_msg( 1, 'job_xml_thread(): Got no data.' )
830
831            if self.kill_thread:
832
833                debug_msg( 1, 'job_xml_thread(): killed.' )
834                return None
835               
836            debug_msg( 1, 'job_xml_thread(): Sleeping.. (%ss)' %(str( self.config.getLowestInterval() ) ) )
837            time.sleep( self.config.getLowestInterval() )
838
839class JobXMLHandler( xml.sax.handler.ContentHandler ):
840    """Parse Job's jobinfo XML from our plugin"""
841
842    def __init__( self, datastore ):
843
844        self.ds              = datastore
845        self.jobs_processed  = [ ]
846        self.jobs_to_store   = [ ]
847        self.jobAttrs        = { }
848        self.jobAttrsSaved   = { }
849
850        debug_msg( 1, "XML: Handler created" )
851
852    def startDocument( self ):
853
854        self.jobs_processed = [ ]
855        self.heartbeat      = 0
856        self.elementct      = 0
857
858        debug_msg( 1, "XML: Start document" )
859
860    def startElement( self, name, attrs ):
861        """
862        This XML will be all gmetric XML
863        so there will be no specific start/end element
864        just one XML statement with all info
865        """
866
867        jobinfo = { }
868
869        self.elementct    += 1
870
871        if name == 'CLUSTER':
872
873            self.clustername = str( attrs.get( 'NAME', "" ) )
874
875        elif name == 'METRIC' and self.clustername in ARCHIVE_DATASOURCES:
876
877            metricname = str( attrs.get( 'NAME', "" ) )
878
879            if metricname == 'zplugin_monarch_heartbeat':
880
881                self.heartbeat = str( attrs.get( 'VAL', "" ) )
882
883            elif metricname.find( 'zplugin_monarch_job' ) != -1:
884
885                job_id  = metricname.split( 'zplugin_monarch_job_' )[1].split( '_' )[1]
886                val     = str( attrs.get( 'VAL', "" ) )
887
888                valinfo = val.split( ' ' )
889
890                for myval in valinfo:
891
892                    if len( myval.split( '=' ) ) > 1:
893
894                        valname = myval.split( '=' )[0]
895                        value   = myval.split( '=' )[1]
896
897                        if valname == 'nodes':
898
899                            value = value.split( ';' )
900
901                        jobinfo[ valname ] = value
902
903                self.jobAttrs[ job_id ] = jobinfo
904
905                self.jobs_processed.append( job_id )
906                   
907    def endDocument( self ):
908        """When all metrics have gone, check if any jobs have finished"""
909
910        jobs_finished = [ ]
911
912        debug_msg( 1, "XML: Processed "+str(self.elementct)+ " elements - found "+str(len(self.jobs_processed))+" jobs" )
913
914        if self.heartbeat == 0:
915            return None
916
917        for jobid, jobinfo in self.jobAttrs.items():
918
919            if jobinfo['reported'] != self.heartbeat:
920
921                if (jobinfo['status'] != 'R'):
922                    debug_msg( 1, 'job %s report time %s does not match current heartbeat %s : ignoring job' %(jobid, jobinfo['reported'], self.heartbeat ) )
923                    del self.jobAttrs[ jobid ]
924
925                    if jobid in self.jobs_to_store:
926                        del self.jobs_to_store[ jobid ]
927
928                    continue
929
930                elif jobid not in self.jobs_processed:
931
932                    # Was running previous heartbeat but not anymore: must be finished
933                    self.jobAttrs[ jobid ]['status'] = 'F'
934                    self.jobAttrs[ jobid ]['stop_timestamp'] = str( self.heartbeat )
935                    debug_msg( 1, 'job %s appears to have finished' %jobid )
936
937                    jobs_finished.append( jobid )
938
939                    if not jobid in self.jobs_to_store:
940                        self.jobs_to_store.append( jobid )
941
942                    continue
943
944            elif self.jobAttrsSaved.has_key( jobid ):
945
946                # This should pretty much never happen, but hey let's be careful
947                # Perhaps if someone altered their job while in queue with qalter
948
949                if self.jobinfoChanged( jobid, jobinfo ):
950
951                    self.jobAttrs[ jobid ]['stop_timestamp'] = ''
952                    self.jobAttrs[ jobid ]                   = self.setJobAttrs( self.jobAttrs[ jobid ], jobinfo )
953
954                    if not jobid in self.jobs_to_store:
955
956                        self.jobs_to_store.append( jobid )
957
958                    debug_msg( 10, 'jobinfo for job %s has changed' %jobid )
959            else:
960                debug_msg( 1, 'new job %s' %jobid )
961
962                if not jobid in self.jobs_to_store:
963
964                    self.jobs_to_store.append( jobid )
965
966        debug_msg( 1, 'job_xml_thread(): Found %s updated jobs.' %len(self.jobs_to_store) )
967
968        failed_store = [ ]
969        succes_store = [ ]
970
971        if len( self.jobs_to_store ) > 0:
972
973            debug_msg( 1, 'job_xml_thread(): Storing jobs to database..' )
974
975            for n in range( 0, len(self.jobs_to_store ) ):
976
977                if len( self.jobs_to_store ) == 0:
978                    break
979
980                jobid = self.jobs_to_store.pop( 0 )
981
982                db_ok = self.ds.storeJobInfo( jobid, self.jobAttrs[ jobid ] )
983
984                if not db_ok:
985
986                    self.ds.doRollback()
987                    failed_store.append( jobid )
988                    continue
989
990                self.ds.doCommit()
991                succes_store.append( jobid )
992
993                if not jobid in jobs_finished:
994
995                    self.jobAttrsSaved[ jobid ] = self.jobAttrs[ jobid ]
996
997                elif self.jobAttrsSaved.has_key( jobid ):
998
999                    del self.jobAttrsSaved[ jobid ]
1000
1001                if self.jobAttrs[ jobid ]['status'] == 'F':
1002
1003                    del self.jobAttrs[ jobid ]
1004
1005            result_str = 'succesfully stored: %s jobs' %str(len(succes_store))
1006
1007            if len( failed_store ) > 0:
1008                result_str = result_str + ' - failed to store: %s jobs - deferred to next interval' %str(len(failed_store))
1009
1010            debug_msg( 1, 'job_xml_thread(): Done storing. %s' %result_str )
1011
1012        else:
1013            debug_msg( 1, 'job_xml_thread(): No jobs to store.' )
1014
1015        self.jobs_processed = [ ]
1016
1017        # TODO: once in while check database AND self.jobAttrsSaved for stale jobs
1018
1019    def setJobAttrs( self, old, new ):
1020        """
1021        Set new job attributes in old, but not lose existing fields
1022        if old attributes doesn't have those
1023        """
1024
1025        for valname, value in new.items():
1026            old[ valname ] = value
1027
1028        return old
1029       
1030
1031    def jobinfoChanged( self, jobid, jobinfo ):
1032        """
1033        Check if jobinfo has changed from jobattrs[jobid]
1034        if it's report time is bigger than previous one
1035        and it is report time is recent (equal to heartbeat)
1036        """
1037
1038        ignore_changes = [ 'reported' ]
1039
1040        if self.jobAttrsSaved.has_key( jobid ):
1041
1042            for valname, value in jobinfo.items():
1043
1044                if valname not in ignore_changes:
1045
1046                    if self.jobAttrsSaved[ jobid ].has_key( valname ):
1047
1048                        if value != self.jobAttrsSaved[ jobid ][ valname ]:
1049
1050                            if jobinfo['reported'] > self.jobAttrsSaved[ jobid ][ 'reported' ]:
1051
1052                                debug_msg( 1, "job %s field '%s' changed since saved from: %s to: %s" %( jobid, valname, value, self.jobAttrsSaved[ jobid ][ valname ] ) )
1053
1054                                return True
1055
1056                    else:
1057                        debug_msg( 1, "job %s did not have field '%s'" %( jobid, valname )  )
1058                        return True
1059
1060        return False
1061
1062class GangliaXMLHandler( xml.sax.handler.ContentHandler ):
1063    """Parse Ganglia's XML"""
1064
1065    def __init__( self, config, datastore ):
1066        """Setup initial variables and gather info on existing rrd archive"""
1067
1068        self.config    = config
1069        self.clusters    = { }
1070        self.ds        = datastore
1071
1072        debug_msg( 1, 'Checking database..' )
1073
1074        global DEBUG_LEVEL
1075
1076        if DEBUG_LEVEL <= 2:
1077            self.ds.checkStaleJobs()
1078
1079        debug_msg( 1, 'Check done.' )
1080        debug_msg( 1, 'Checking rrd archive..' )
1081        self.gatherClusters()
1082        debug_msg( 1, 'Check done.' )
1083
1084    def gatherClusters( self ):
1085        """Find all existing clusters in archive dir"""
1086
1087        archive_dir    = check_dir(ARCHIVE_PATH)
1088
1089        hosts        = [ ]
1090
1091        if os.path.exists( archive_dir ):
1092
1093            dirlist    = os.listdir( archive_dir )
1094
1095            for cfgcluster in ARCHIVE_DATASOURCES:
1096
1097                if cfgcluster not in dirlist:
1098
1099                    # Autocreate a directory for this cluster
1100                    # assume it is new
1101                    #
1102                    cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), cfgcluster )
1103
1104                    os.mkdir( cluster_dir )
1105
1106                    dirlist.append( cfgcluster )
1107
1108            for item in dirlist:
1109
1110                clustername = item
1111
1112                if not self.clusters.has_key( clustername ) and clustername in ARCHIVE_DATASOURCES:
1113
1114                    self.clusters[ clustername ] = RRDHandler( self.config, clustername )
1115
1116        debug_msg( 9, "Found "+str(len(self.clusters.keys()))+" clusters" )
1117
1118    def startElement( self, name, attrs ):
1119        """Memorize appropriate data from xml start tags"""
1120
1121        if name == 'GANGLIA_XML':
1122
1123            self.XMLSource      = str( attrs.get( 'SOURCE',  "" ) )
1124            self.gangliaVersion = str( attrs.get( 'VERSION', "" ) )
1125
1126            debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
1127
1128        elif name == 'GRID':
1129
1130            self.gridName    = str( attrs.get( 'NAME', "" ) )
1131            self.time    = str( attrs.get( 'LOCALTIME', "" ) )
1132
1133            debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
1134
1135        elif name == 'CLUSTER':
1136
1137            self.clusterName = str( attrs.get( 'NAME',      "" ) )
1138            self.time        = str( attrs.get( 'LOCALTIME', "" ) )
1139
1140            if not self.clusters.has_key( self.clusterName ) and self.clusterName in ARCHIVE_DATASOURCES:
1141
1142                self.clusters[ self.clusterName ] = RRDHandler( self.config, self.clusterName )
1143
1144                debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
1145
1146        elif name == 'HOST' and self.clusterName in ARCHIVE_DATASOURCES:     
1147
1148            self.hostName     = str( attrs.get( 'NAME',     "" ) )
1149            self.hostIp       = str( attrs.get( 'IP',       "" ) )
1150            self.hostReported = str( attrs.get( 'REPORTED', "" ) )
1151
1152            debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
1153
1154        elif name == 'METRIC' and self.clusterName in ARCHIVE_DATASOURCES:
1155
1156            type = str( attrs.get( 'TYPE', "" ) )
1157           
1158            exclude_metric = False
1159           
1160            for ex_metricstr in ARCHIVE_EXCLUDE_METRICS:
1161
1162                orig_name = str( attrs.get( 'NAME', "" ) )
1163
1164                if string.lower( orig_name ) == string.lower( ex_metricstr ):
1165               
1166                    exclude_metric = True
1167
1168                elif re.match( ex_metricstr, orig_name ):
1169
1170                    exclude_metric = True
1171
1172            if type not in UNSUPPORTED_ARCHIVE_TYPES and not exclude_metric:
1173
1174                myMetric         = { }
1175                myMetric['name'] = str( attrs.get( 'NAME', "" ) )
1176                myMetric['val']  = str( attrs.get( 'VAL',  "" ) )
1177                myMetric['time'] = self.hostReported
1178
1179                self.clusters[ self.clusterName ].memMetric( self.hostName, myMetric )
1180
1181                debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
1182
1183    def storeMetrics( self ):
1184        """Store metrics of each cluster rrd handler"""
1185
1186        for clustername, rrdh in self.clusters.items():
1187
1188            ret = rrdh.storeMetrics()
1189
1190            if ret:
1191                debug_msg( 9, 'An error occured while storing metrics for cluster %s' %clustername )
1192                return 1
1193
1194        return 0
1195
1196class XMLErrorHandler( xml.sax.handler.ErrorHandler ):
1197
1198    def error( self, exception ):
1199        """Recoverable error"""
1200
1201        debug_msg( 0, 'Recoverable XML error ' + str( exception ) + ' ignored.' )
1202
1203    def fatalError( self, exception ):
1204        """Non-recoverable error"""
1205
1206        exception_str = str( exception )
1207
1208        # Ignore 'no element found' errors
1209        if exception_str.find( 'no element found' ) != -1:
1210            debug_msg( 0, 'No XML data found: Socket not (re)connected or datasource not available.' )
1211            return 0
1212
1213        debug_msg( 0, 'FATAL ERROR: Non-recoverable XML error ' + str( exception ) )
1214        sys.exit( 1 )
1215
1216    def warning( self, exception ):
1217        """Warning"""
1218
1219        debug_msg( 0, 'Warning ' + str( exception ) )
1220
1221class XMLGatherer:
1222    """Setup a connection and file object to Ganglia's XML"""
1223
1224    s        = None
1225    fd        = None
1226    data        = None
1227    slot        = None
1228
1229    # Time since the last update
1230    #
1231    LAST_UPDATE    = 0
1232
1233    # Minimum interval between updates
1234    #
1235    MIN_UPDATE_INT    = 10
1236
1237    # Is a update occuring now
1238    #
1239    update_now    = False
1240
1241    def __init__( self, host, port ):
1242        """Store host and port for connection"""
1243
1244        self.host    = host
1245        self.port    = port
1246        self.slot    = threading.Lock()
1247
1248        self.retrieveData()
1249
1250    def retrieveData( self ):
1251        """Setup connection to XML source"""
1252
1253        self.update_now    = True
1254
1255        self.slot.acquire()
1256
1257        self.data    = None
1258
1259        for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ):
1260
1261            af, socktype, proto, canonname, sa = res
1262
1263            try:
1264
1265                self.s = socket.socket( af, socktype, proto )
1266
1267            except ( socket.error, socket.gaierror, socket.herror, socket.timeout ), msg:
1268
1269                self.s = None
1270                continue
1271
1272            try:
1273
1274                self.s.connect( sa )
1275
1276            except ( socket.error, socket.gaierror, socket.herror, socket.timeout ), msg:
1277
1278                self.disconnect()
1279                continue
1280
1281            break
1282
1283        if self.s is None:
1284
1285            debug_msg( 0, 'FATAL ERROR: Could not open socket or unable to connect to datasource!' )
1286            self.update_now    = False
1287            #sys.exit( 1 )
1288
1289        else:
1290            #self.s.send( '\n' )
1291
1292            my_fp            = self.s.makefile( 'r' )
1293            my_data          = my_fp.readlines()
1294            my_data          = string.join( my_data, '' )
1295
1296            self.data        = my_data
1297
1298            self.LAST_UPDATE = time.time()
1299
1300        self.slot.release()
1301
1302        self.update_now    = False
1303
1304    def disconnect( self ):
1305        """Close socket"""
1306
1307        if self.s:
1308            #self.s.shutdown( 2 )
1309            self.s.close()
1310            self.s = None
1311
1312    def __del__( self ):
1313        """Kill the socket before we leave"""
1314
1315        self.disconnect()
1316
1317    def reGetData( self ):
1318        """Reconnect"""
1319
1320        while self.update_now:
1321
1322            # Must be another update in progress:
1323            # Wait until the update is complete
1324            #
1325            time.sleep( 1 )
1326
1327        if self.s:
1328            self.disconnect()
1329
1330        self.retrieveData()
1331
1332    def getData( self ):
1333
1334        """Return the XML data"""
1335
1336        # If more than MIN_UPDATE_INT seconds passed since last data update
1337        # update the XML first before returning it
1338        #
1339
1340        cur_time    = time.time()
1341
1342        if ( cur_time - self.LAST_UPDATE ) > self.MIN_UPDATE_INT:
1343
1344            self.reGetData()
1345
1346        while self.update_now:
1347
1348            # Must be another update in progress:
1349            # Wait until the update is complete
1350            #
1351            time.sleep( 1 )
1352           
1353        return self.data
1354
1355    def makeFileDescriptor( self ):
1356        """Make file descriptor that points to our socket connection"""
1357
1358        self.reconnect()
1359
1360        if self.s:
1361            self.fd = self.s.makefile( 'r' )
1362
1363    def getFileObject( self ):
1364        """Connect, and return a file object"""
1365
1366        self.makeFileDescriptor()
1367
1368        if self.fd:
1369            return self.fd
1370
1371class GangliaXMLProcessor( XMLProcessor ):
1372    """Main class for processing XML and acting with it"""
1373
1374    def __init__( self, XMLSource, DataStore ):
1375        """Setup initial XML connection and handlers"""
1376
1377        self.config       = GangliaConfigParser( GMETAD_CONF )
1378        self.myXMLSource  = XMLSource
1379        self.ds           = DataStore
1380        self.myXMLHandler = GangliaXMLHandler( self.config, self.ds )
1381        self.myXMLError   = XMLErrorHandler()
1382
1383    def run( self ):
1384        """Main XML processing; start a xml and storethread"""
1385
1386        xml_thread   = threading.Thread( None, self.processXML,   'xmlthread' )
1387        store_thread = threading.Thread( None, self.storeMetrics, 'storethread' )
1388
1389        while( 1 ):
1390
1391            if not xml_thread.isAlive():
1392                # Gather XML at the same interval as gmetad
1393
1394                # threaded call to: self.processXML()
1395                #
1396                try:
1397                    xml_thread = threading.Thread( None, self.processXML, 'xml_thread' )
1398                    xml_thread.start()
1399                except thread.error, msg:
1400                    debug_msg( 0, 'ERROR: Unable to start xml_thread!: '+str(msg))
1401                    #return 1
1402
1403            if not store_thread.isAlive():
1404                # Store metrics every .. sec
1405
1406                # threaded call to: self.storeMetrics()
1407                #
1408                try:
1409                    store_thread = threading.Thread( None, self.storeMetrics, 'store_thread' )
1410                    store_thread.start()
1411                except thread.error, msg:
1412                    debug_msg( 0, 'ERROR: Unable to start store_thread!: '+str(msg))
1413                    #return 1
1414       
1415            # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway
1416            time.sleep( 1 )   
1417
1418    def storeMetrics( self ):
1419        """Store metrics retained in memory to disk"""
1420
1421        global DEBUG_LEVEL
1422
1423        # Store metrics somewhere between every 360 and 640 seconds
1424        #
1425        if DEBUG_LEVEL >= 1:
1426            STORE_INTERVAL = 60
1427        else:
1428            STORE_INTERVAL = random.randint( 360, 640 )
1429
1430        try:
1431            store_metric_thread = threading.Thread( None, self.storeThread, 'store_metric_thread' )
1432            store_metric_thread.start()
1433        except thread.error, msg:
1434            debug_msg( 0, 'ERROR: Unable to start ganglia_store_thread()!: '+str(msg) )
1435            return 1
1436
1437        debug_msg( 1, 'ganglia_store_thread(): started.' )
1438
1439        debug_msg( 1, 'ganglia_store_thread(): Sleeping.. (%ss)' %STORE_INTERVAL )
1440        time.sleep( STORE_INTERVAL )
1441        debug_msg( 1, 'ganglia_store_thread(): Done sleeping.' )
1442
1443        if store_metric_thread.isAlive():
1444
1445            debug_msg( 1, 'ganglia_store_thread(): storemetricthread() still running, waiting to finish..' )
1446            store_metric_thread.join( STORE_TIMEOUT ) # Maximum time is for storing thread to finish
1447
1448            if store_metric_thread.isAlive():
1449
1450                debug_msg( 1, 'ganglia_store_thread(): Done waiting: storemetricthread() still running :( now what?' )
1451            else:
1452                debug_msg( 1, 'ganglia_store_thread(): Done waiting: storemetricthread() has finished' )
1453
1454        debug_msg( 1, 'ganglia_store_thread(): finished.' )
1455
1456        return 0
1457
1458    def storeThread( self ):
1459        """Actual metric storing thread"""
1460
1461        debug_msg( 1, 'ganglia_store_metric_thread(): started.' )
1462        debug_msg( 1, 'ganglia_store_metric_thread(): Storing data..' )
1463
1464        ret = self.myXMLHandler.storeMetrics()
1465        if ret > 0:
1466            debug_msg( 0, 'ganglia_store_metric_thread(): UNKNOWN ERROR %s while storing Metrics!' %str(ret) )
1467
1468        debug_msg( 1, 'ganglia_store_metric_thread(): Done storing.' )
1469        debug_msg( 1, 'ganglia_store_metric_thread(): finished.' )
1470       
1471        return 0
1472
1473    def processXML( self ):
1474        """Process XML"""
1475
1476        try:
1477            parsethread = threading.Thread( None, self.parseThread, 'parsethread' )
1478            parsethread.start()
1479        except thread.error, msg:
1480            debug_msg( 0, 'ERROR: Unable to start ganglia_xml_thread()!: ' + str(msg) )
1481            return 1
1482
1483        debug_msg( 1, 'ganglia_xml_thread(): started.' )
1484
1485        debug_msg( 1, 'ganglia_xml_thread(): Sleeping.. (%ss)' %self.config.getLowestInterval() )
1486        time.sleep( float( self.config.getLowestInterval() ) )   
1487        debug_msg( 1, 'ganglia_xml_thread(): Done sleeping.' )
1488
1489        if parsethread.isAlive():
1490
1491            debug_msg( 1, 'ganglia_xml_thread(): parsethread() still running, waiting (%ss) to finish..' %PARSE_TIMEOUT )
1492            parsethread.join( PARSE_TIMEOUT ) # Maximum time for XML thread to finish
1493
1494            if parsethread.isAlive():
1495                debug_msg( 1, 'ganglia_xml_thread(): Done waiting: parsethread() still running :( now what?' )
1496            else:
1497                debug_msg( 1, 'ganglia_xml_thread(): Done waiting: parsethread() finished' )
1498
1499        debug_msg( 1, 'ganglia_xml_thread(): finished.' )
1500
1501        return 0
1502
1503    def parseThread( self ):
1504        """Actual parsing thread"""
1505
1506        debug_msg( 1, 'ganglia_parse_thread(): started.' )
1507        debug_msg( 1, 'ganglia_parse_thread(): Retrieving XML data..' )
1508       
1509        my_data    = self.myXMLSource.getData()
1510
1511        debug_msg( 1, 'ganglia_parse_thread(): Done retrieving: data size %d' %len(my_data) )
1512
1513        if my_data:
1514            debug_msg( 1, 'ganglia_parse_thread(): Parsing XML..' )
1515            xml.sax.parseString( my_data, self.myXMLHandler, self.myXMLError )
1516            debug_msg( 1, 'ganglia_parse_thread(): Done parsing.' )
1517
1518        debug_msg( 1, 'ganglia_parse_thread(): finished.' )
1519
1520        return 0
1521
1522class GangliaConfigParser:
1523
1524    sources = [ ]
1525
1526    def __init__( self, config ):
1527        """Parse some stuff from our gmetad's config, such as polling interval"""
1528
1529        self.config = config
1530        self.parseValues()
1531
1532    def parseValues( self ):
1533        """Parse certain values from gmetad.conf"""
1534
1535        readcfg = open( self.config, 'r' )
1536
1537        for line in readcfg.readlines():
1538
1539            if line.count( '"' ) > 1:
1540
1541                if line.find( 'data_source' ) != -1 and line[0] != '#':
1542
1543                    source        = { }
1544                    source['name']    = line.split( '"' )[1]
1545                    source_words    = line.split( '"' )[2].split( ' ' )
1546
1547                    for word in source_words:
1548
1549                        valid_interval = 1
1550
1551                        for letter in word:
1552
1553                            if letter not in string.digits:
1554
1555                                valid_interval = 0
1556
1557                        if valid_interval and len(word) > 0:
1558
1559                            source['interval'] = word
1560                            debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
1561   
1562                    # No interval found, use Ganglia's default   
1563                    if not source.has_key( 'interval' ):
1564                        source['interval'] = 15
1565                        debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
1566
1567                    self.sources.append( source )
1568
1569    def getInterval( self, source_name ):
1570        """Return interval for source_name"""
1571
1572        for source in self.sources:
1573
1574            if source['name'] == source_name:
1575
1576                return source['interval']
1577
1578        return None
1579
1580    def getLowestInterval( self ):
1581        """Return the lowest interval of all clusters"""
1582
1583        lowest_interval = 0
1584
1585        for source in self.sources:
1586
1587            if not lowest_interval or source['interval'] <= lowest_interval:
1588
1589                lowest_interval = source['interval']
1590
1591        # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays
1592        if lowest_interval:
1593            return lowest_interval
1594        else:
1595            return 15
1596
1597class RRDHandler:
1598    """Class for handling RRD activity"""
1599
1600    myMetrics = { }
1601    lastStored = { }
1602    timeserials = { }
1603    slot = None
1604
1605    def __init__( self, config, cluster ):
1606        """Setup initial variables"""
1607
1608        global MODRRDTOOL
1609
1610        self.block    = 0
1611        self.cluster    = cluster
1612        self.config    = config
1613        self.slot    = threading.Lock()
1614
1615        if MODRRDTOOL:
1616
1617            self.rrdm    = RRDMutator()
1618        else:
1619            self.rrdm    = RRDMutator( RRDTOOL )
1620
1621        global DEBUG_LEVEL
1622
1623        if DEBUG_LEVEL <= 2:
1624            self.gatherLastUpdates()
1625
1626    def gatherLastUpdates( self ):
1627        """Populate the lastStored list, containing timestamps of all last updates"""
1628
1629        cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster )
1630
1631        hosts = [ ]
1632
1633        if os.path.exists( cluster_dir ):
1634
1635            dirlist = os.listdir( cluster_dir )
1636
1637            for dir in dirlist:
1638
1639                hosts.append( dir )
1640
1641        for host in hosts:
1642
1643            host_dir    = cluster_dir + '/' + host
1644            dirlist        = os.listdir( host_dir )
1645
1646            for dir in dirlist:
1647
1648                if not self.timeserials.has_key( host ):
1649
1650                    self.timeserials[ host ] = [ ]
1651
1652                self.timeserials[ host ].append( dir )
1653
1654            last_serial = self.getLastRrdTimeSerial( host )
1655
1656            if last_serial:
1657
1658                metric_dir = cluster_dir + '/' + host + '/' + last_serial
1659
1660                if os.path.exists( metric_dir ):
1661
1662                    dirlist = os.listdir( metric_dir )
1663
1664                    for file in dirlist:
1665
1666                        metricname = file.split( '.rrd' )[0]
1667
1668                        if not self.lastStored.has_key( host ):
1669
1670                            self.lastStored[ host ] = { }
1671
1672                        self.lastStored[ host ][ metricname ] = self.rrdm.grabLastUpdate( metric_dir + '/' + file )
1673
1674    def getClusterName( self ):
1675        """Return clustername"""
1676
1677        return self.cluster
1678
1679    def memMetric( self, host, metric ):
1680        """Store metric from host in memory"""
1681
1682        # <ATOMIC>
1683        #
1684        self.slot.acquire()
1685       
1686        if self.myMetrics.has_key( host ):
1687
1688            if self.myMetrics[ host ].has_key( metric['name'] ):
1689
1690                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
1691
1692                    if mymetric['time'] == metric['time']:
1693
1694                        # Allready have this metric, abort
1695                        self.slot.release()
1696                        return 1
1697            else:
1698                self.myMetrics[ host ][ metric['name'] ] = [ ]
1699        else:
1700            self.myMetrics[ host ]                = { }
1701            self.myMetrics[ host ][ metric['name'] ]    = [ ]
1702
1703        # Push new metric onto stack
1704        # atomic code; only 1 thread at a time may access the stack
1705
1706        self.myMetrics[ host ][ metric['name'] ].append( metric )
1707
1708        self.slot.release()
1709        #
1710        # </ATOMIC>
1711
1712    def makeUpdateList( self, host, metriclist ):
1713        """
1714        Make a list of update values for rrdupdate
1715        but only those that we didn't store before
1716        """
1717
1718        update_list    = [ ]
1719        metric        = None
1720
1721        while len( metriclist ) > 0:
1722
1723            metric = metriclist.pop( 0 )
1724
1725            if self.checkStoreMetric( host, metric ):
1726
1727                u_val    = str( metric['time'] ) + ':' + str( metric['val'] )
1728                #update_list.append( str('%s:%s') %( metric['time'], metric['val'] ) )
1729                update_list.append( u_val )
1730
1731        return update_list
1732
1733    def checkStoreMetric( self, host, metric ):
1734        """Check if supplied metric if newer than last one stored"""
1735
1736        if self.lastStored.has_key( host ):
1737
1738            if self.lastStored[ host ].has_key( metric['name'] ):
1739
1740                if metric['time'] <= self.lastStored[ host ][ metric['name'] ]:
1741
1742                    # This is old
1743                    return 0
1744
1745        return 1
1746
1747    def memLastUpdate( self, host, metricname, metriclist ):
1748        """
1749        Memorize the time of the latest metric from metriclist
1750        but only if it wasn't allready memorized
1751        """
1752
1753        if not self.lastStored.has_key( host ):
1754            self.lastStored[ host ] = { }
1755
1756        last_update_time = 0
1757
1758        for metric in metriclist:
1759
1760            if metric['name'] == metricname:
1761
1762                if metric['time'] > last_update_time:
1763
1764                    last_update_time = metric['time']
1765
1766        if self.lastStored[ host ].has_key( metricname ):
1767           
1768            if last_update_time <= self.lastStored[ host ][ metricname ]:
1769                return 1
1770
1771        self.lastStored[ host ][ metricname ] = last_update_time
1772
1773    def storeMetrics( self ):
1774        """
1775        Store all metrics from memory to disk
1776        and do it to the RRD's in appropriate timeperiod directory
1777        """
1778
1779        debug_msg( 5, "Entering storeMetrics()")
1780
1781        count_values  = 0
1782        count_metrics = 0
1783        count_bits    = 0
1784
1785        for hostname, mymetrics in self.myMetrics.items():   
1786
1787            for metricname, mymetric in mymetrics.items():
1788
1789                count_metrics += 1
1790
1791                for dmetric in mymetric:
1792
1793                    count_values += 1
1794
1795                    count_bits   += len( dmetric['time'] )
1796                    count_bits   += len( dmetric['val'] )
1797
1798        count_bytes    = count_bits / 8
1799
1800        debug_msg( 5, "size of cluster '" + self.cluster + "': " + 
1801            str( len( self.myMetrics.keys() ) ) + " hosts " + 
1802            str( count_metrics ) + " metrics " + str( count_values ) + " values " +
1803            str( count_bits ) + " bits " + str( count_bytes ) + " bytes " )
1804
1805        for hostname, mymetrics in self.myMetrics.items():   
1806
1807            for metricname, mymetric in mymetrics.items():
1808
1809                metrics_to_store = [ ]
1810
1811                # Pop metrics from stack for storing until none is left
1812                # atomic code: only 1 thread at a time may access myMetrics
1813
1814                # <ATOMIC>
1815                #
1816                self.slot.acquire() 
1817
1818                while len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1819
1820                    if len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1821
1822                        try:
1823                            metrics_to_store.append( self.myMetrics[ hostname ][ metricname ].pop( 0 ) )
1824                        except IndexError, msg:
1825
1826                            # Somehow sometimes myMetrics[ hostname ][ metricname ]
1827                            # is still len 0 when the statement is executed.
1828                            # Just ignore indexerror's..
1829                            pass
1830
1831                self.slot.release()
1832                #
1833                # </ATOMIC>
1834
1835                # Create a mapping table, each metric to the period where it should be stored
1836                #
1837                metric_serial_table = self.determineSerials( hostname, metricname, metrics_to_store )
1838
1839                update_rets = [ ]
1840
1841                for period, pmetric in metric_serial_table.items():
1842
1843                    create_ret = self.createCheck( hostname, metricname, period )   
1844
1845                    update_ret = self.update( hostname, metricname, period, pmetric )
1846
1847                    if update_ret == 0:
1848
1849                        debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
1850                    else:
1851                        debug_msg( 9, 'metric update failed' )
1852
1853                    update_rets.append( create_ret )
1854                    update_rets.append( update_ret )
1855
1856                # Lets ignore errors here for now, we need to make sure last update time
1857                # is correct!
1858                #
1859                #if not (1) in update_rets:
1860
1861                self.memLastUpdate( hostname, metricname, metrics_to_store )
1862
1863        debug_msg( 5, "Leaving storeMetrics()")
1864
1865    def makeTimeSerial( self ):
1866        """Generate a time serial. Seconds since epoch"""
1867
1868        # Seconds since epoch
1869        mytime = int( time.time() )
1870
1871        return mytime
1872
1873    def makeRrdPath( self, host, metricname, timeserial ):
1874        """Make a RRD location/path and filename"""
1875
1876        rrd_dir        = '%s/%s/%s/%s'    %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
1877        rrd_file    = '%s/%s.rrd'    %( rrd_dir, metricname )
1878
1879        return rrd_dir, rrd_file
1880
1881    def getLastRrdTimeSerial( self, host ):
1882        """Find the last timeserial (directory) for this host"""
1883
1884        newest_timeserial = 0
1885
1886        for dir in self.timeserials[ host ]:
1887
1888            valid_dir = 1
1889
1890            for letter in dir:
1891                if letter not in string.digits:
1892                    valid_dir = 0
1893
1894            if valid_dir:
1895                timeserial = dir
1896                if timeserial > newest_timeserial:
1897                    newest_timeserial = timeserial
1898
1899        if newest_timeserial:
1900            return newest_timeserial
1901        else:
1902            return 0
1903
1904    def determinePeriod( self, host, check_serial ):
1905        """Determine to which period (directory) this time(serial) belongs"""
1906
1907        period_serial = 0
1908
1909        if self.timeserials.has_key( host ):
1910
1911            for serial in self.timeserials[ host ]:
1912
1913                if check_serial >= serial and period_serial < serial:
1914
1915                    period_serial = serial
1916
1917        return period_serial
1918
1919    def determineSerials( self, host, metricname, metriclist ):
1920        """
1921        Determine the correct serial and corresponding rrd to store
1922        for a list of metrics
1923        """
1924
1925        metric_serial_table = { }
1926
1927        for metric in metriclist:
1928
1929            if metric['name'] == metricname:
1930
1931                period        = self.determinePeriod( host, metric['time'] )   
1932
1933                archive_secs    = ARCHIVE_HOURS_PER_RRD * (60 * 60)
1934
1935                if (int( metric['time'] ) - int( period ) ) > archive_secs:
1936
1937                    # This one should get it's own new period
1938                    period = metric['time']
1939
1940                    if not self.timeserials.has_key( host ):
1941                        self.timeserials[ host ] = [ ]
1942
1943                    self.timeserials[ host ].append( period )
1944
1945                if not metric_serial_table.has_key( period ):
1946
1947                    metric_serial_table[ period ] = [ ]
1948
1949                metric_serial_table[ period ].append( metric )
1950
1951        return metric_serial_table
1952
1953    def createCheck( self, host, metricname, timeserial ):
1954        """Check if an rrd allready exists for this metric, create if not"""
1955
1956        debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1957       
1958        rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
1959
1960        if not os.path.exists( rrd_dir ):
1961
1962            try:
1963                os.makedirs( rrd_dir )
1964
1965            except os.OSError, msg:
1966
1967                if msg.find( 'File exists' ) != -1:
1968
1969                    # Ignore exists errors
1970                    pass
1971
1972                else:
1973
1974                    print msg
1975                    return
1976
1977            debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
1978
1979        if not os.path.exists( rrd_file ):
1980
1981            interval    = self.config.getInterval( self.cluster )
1982            heartbeat    = 8 * int( interval )
1983
1984            params        = [ ]
1985
1986            params.append( '--step' )
1987            params.append( str( interval ) )
1988
1989            params.append( '--start' )
1990            params.append( str( int( timeserial ) - 1 ) )
1991
1992            params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat )
1993            params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) )
1994
1995            self.rrdm.create( str(rrd_file), params )
1996
1997            debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
1998
1999    def update( self, host, metricname, timeserial, metriclist ):
2000        """
2001        Update rrd file for host with metricname
2002        in directory timeserial with metriclist
2003        """
2004
2005        debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
2006
2007        rrd_dir, rrd_file    = self.makeRrdPath( host, metricname, timeserial )
2008
2009        update_list        = self.makeUpdateList( host, metriclist )
2010
2011        if len( update_list ) > 0:
2012            ret = self.rrdm.update( str(rrd_file), update_list )
2013
2014            if ret:
2015                return 1
2016       
2017            debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) )
2018
2019        return 0
2020
2021def daemon():
2022    """daemonized threading"""
2023
2024    # Fork the first child
2025    #
2026    pid = os.fork()
2027
2028    if pid > 0:
2029
2030        sys.exit(0)  # end parent
2031
2032    # creates a session and sets the process group ID
2033    #
2034    os.setsid()
2035
2036    # Fork the second child
2037    #
2038    pid = os.fork()
2039
2040    if pid > 0:
2041
2042        sys.exit(0)  # end parent
2043
2044    write_pidfile()
2045
2046    # Go to the root directory and set the umask
2047    #
2048    os.chdir('/')
2049    os.umask(0)
2050
2051    sys.stdin.close()
2052    sys.stdout.close()
2053    sys.stderr.close()
2054
2055    os.open('/dev/null', os.O_RDWR)
2056    os.dup2(0, 1)
2057    os.dup2(0, 2)
2058
2059    run()
2060
2061def run():
2062    """Threading start"""
2063
2064    config             = GangliaConfigParser( GMETAD_CONF )
2065    s_timeout          = int( config.getLowestInterval() - 1 )
2066
2067    socket.setdefaulttimeout( s_timeout )
2068
2069    myXMLSource        = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] )
2070    myDataStore        = DataSQLStore( JOB_SQL_DBASE.split( '/' )[0], JOB_SQL_DBASE.split( '/' )[1] )
2071
2072    myJobProcessor     = JobXMLProcessor( myXMLSource, myDataStore )
2073    myGangliaProcessor = GangliaXMLProcessor( myXMLSource, myDataStore )
2074
2075    try:
2076        job_xml_thread     = threading.Thread( None, myJobProcessor.run, 'job_proc_thread' )
2077        ganglia_xml_thread = threading.Thread( None, myGangliaProcessor.run, 'ganglia_proc_thread' )
2078
2079        job_xml_thread.start()
2080        ganglia_xml_thread.start()
2081       
2082    except thread.error, msg:
2083        debug_msg( 0, 'FATAL ERROR: Unable to start main threads!: '+ str(msg) )
2084        syslog.closelog()
2085        sys.exit(1)
2086       
2087    debug_msg( 0, 'main threading started.' )
2088
2089def main():
2090    """Program startup"""
2091
2092    global DAEMONIZE, USE_SYSLOG
2093
2094    if not processArgs( sys.argv[1:] ):
2095        sys.exit( 1 )
2096
2097    if( DAEMONIZE and USE_SYSLOG ):
2098        syslog.openlog( 'jobarchived', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
2099
2100    if DAEMONIZE:
2101        daemon()
2102    else:
2103        run()
2104
2105#
2106# Global functions
2107#
2108
2109def check_dir( directory ):
2110    """Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"""
2111
2112    if directory[-1] == '/':
2113        directory = directory[:-1]
2114
2115    return directory
2116
2117def reqtime2epoch( rtime ):
2118
2119    (hours, minutes, seconds )    = rtime.split( ':' )
2120
2121    etime    = int(seconds)
2122    etime    = etime + ( int(minutes) * 60 )
2123    etime    = etime + ( int(hours) * 60 * 60 )
2124
2125    return etime
2126
2127def debug_msg( level, msg ):
2128    """Only print msg if correct levels"""
2129
2130    if (not DAEMONIZE and DEBUG_LEVEL >= level):
2131        sys.stderr.write( printTime() + ' - ' + msg + '\n' )
2132   
2133    if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
2134        syslog.syslog( msg )
2135
2136def printTime( ):
2137    """Print current time in human readable format"""
2138
2139    return time.strftime("%a %d %b %Y %H:%M:%S")
2140
2141def write_pidfile():
2142
2143    # Write pidfile if PIDFILE exists
2144    if PIDFILE:
2145
2146        pid     = os.getpid()
2147
2148        pidfile = open(PIDFILE, 'w')
2149
2150        pidfile.write( str( pid ) )
2151        pidfile.close()
2152
2153# Ooohh, someone started me! Let's go..
2154#
2155if __name__ == '__main__':
2156    main()
Note: See TracBrowser for help on using the repository browser.