source: branches/0.4/jobarchived/jobarchived.py @ 783

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