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

Last change on this file since 782 was 782, checked in by ramonb, 11 years ago
  • trying to fix job parsing and detection: not everything seen/stored
  • all job checking should be done post-parsing, not while parsing
  • some cleanup
  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 58.8 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 782 2013-03-31 19:25:23Z 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        debug_msg( 1, "XML: Processed "+str(self.elementct)+ " elements - found "+str(len(self.jobs_processed))+" jobs" )
892
893        if self.heartbeat == 0:
894            return None
895
896        for jobid, jobinfo in self.jobAttrs.items():
897
898            if jobinfo['reported'] != self.heartbeat:
899
900                if (jobinfo['status'] != 'R'):
901                    debug_msg( 1, 'job %s report time %s does not match current heartbeat %s : ignoring job' %(jobid, jobinfo['reported'], self.heartbeat ) )
902                    del self.jobAttrs[ jobid ]
903
904                    if jobid in self.jobs_to_store:
905                        del self.jobs_to_store[ jobid ]
906
907                    continue
908
909                elif jobid not in self.jobs_processed:
910                    # Was running previous heartbeat but not anymore: must be finished
911                    self.jobAttrs[ jobid ]['status'] = 'F'
912                    self.jobAttrs[ jobid ]['stop_timestamp'] = str( self.heartbeat )
913                    debug_msg( 1, 'job %s appears to have finished' %jobid )
914
915                    if not jobid in self.jobs_to_store:
916                        self.jobs_to_store.append( jobid )
917
918                    continue
919
920            elif self.jobAttrsSaved.has_key( jobid ):
921
922                if self.jobinfoChanged( jobid, jobinfo ):
923
924                    self.jobAttrs[ jobid ]['stop_timestamp'] = ''
925                    self.jobAttrs[ jobid ]                   = self.setJobAttrs( self.jobAttrs[ jobid ], jobinfo )
926
927                    if not jobid in self.jobs_to_store:
928
929                        self.jobs_to_store.append( jobid )
930
931                    debug_msg( 10, 'jobinfo for job %s has changed' %jobid )
932            else:
933                debug_msg( 1, 'new job %s' %jobid )
934
935                if not jobid in self.jobs_to_store:
936
937                    self.jobs_to_store.append( jobid )
938
939        debug_msg( 1, 'job_xml_thread(): Found %s updated jobs.' %len(self.jobs_to_store) )
940
941        if len( self.jobs_to_store ) > 0:
942
943            debug_msg( 1, 'job_xml_thread(): Storing jobs to database..' )
944
945            while len( self.jobs_to_store ) > 0:
946
947                jobid = self.jobs_to_store.pop( 0 )
948
949                self.ds.storeJobInfo( jobid, self.jobAttrs[ jobid ] )
950
951                self.jobAttrsSaved[ jobid ] = self.jobAttrs[ jobid ]
952
953                if self.jobAttrs[ jobid ]['status'] == 'F':
954
955                    del self.jobAttrs[ jobid ]
956
957            debug_msg( 1, 'job_xml_thread(): Done storing.' )
958
959        else:
960            debug_msg( 1, 'job_xml_thread(): No jobs to store.' )
961
962        self.jobs_processed = [ ]
963
964    def setJobAttrs( self, old, new ):
965        """
966        Set new job attributes in old, but not lose existing fields
967        if old attributes doesn't have those
968        """
969
970        for valname, value in new.items():
971            old[ valname ] = value
972
973        return old
974       
975
976    def jobinfoChanged( self, jobid, jobinfo ):
977        """
978        Check if jobinfo has changed from jobattrs[jobid]
979        if it's report time is bigger than previous one
980        and it is report time is recent (equal to heartbeat)
981        """
982
983        ignore_changes = [ 'reported' ]
984
985        if self.jobAttrsSaved.has_key( jobid ):
986
987            for valname, value in jobinfo.items():
988
989                if valname not in ignore_changes:
990
991                    if self.jobAttrsSaved[ jobid ].has_key( valname ):
992
993                        if value != self.jobAttrsSaved[ jobid ][ valname ]:
994
995                            if jobinfo['reported'] > self.jobAttrsSaved[ jobid ][ 'reported' ]:
996
997                                debug_msg( 1, "job %s field '%s' changed since saved from: %s to: %s" %( jobid, valname, value, self.jobAttrsSaved[ jobid ][ valname ] ) )
998
999                                return True
1000
1001                    else:
1002                        debug_msg( 1, "job %s did not have field '%s'" %( jobid, valname )  )
1003                        return True
1004
1005        return False
1006
1007class GangliaXMLHandler( xml.sax.handler.ContentHandler ):
1008    """Parse Ganglia's XML"""
1009
1010    def __init__( self, config, datastore ):
1011        """Setup initial variables and gather info on existing rrd archive"""
1012
1013        self.config    = config
1014        self.clusters    = { }
1015        self.ds        = datastore
1016
1017        debug_msg( 1, 'Checking database..' )
1018
1019        global DEBUG_LEVEL
1020
1021        if DEBUG_LEVEL <= 2:
1022            self.ds.checkStaleJobs()
1023
1024        debug_msg( 1, 'Check done.' )
1025        debug_msg( 1, 'Checking rrd archive..' )
1026        self.gatherClusters()
1027        debug_msg( 1, 'Check done.' )
1028
1029    def gatherClusters( self ):
1030        """Find all existing clusters in archive dir"""
1031
1032        archive_dir    = check_dir(ARCHIVE_PATH)
1033
1034        hosts        = [ ]
1035
1036        if os.path.exists( archive_dir ):
1037
1038            dirlist    = os.listdir( archive_dir )
1039
1040            for cfgcluster in ARCHIVE_DATASOURCES:
1041
1042                if cfgcluster not in dirlist:
1043
1044                    # Autocreate a directory for this cluster
1045                    # assume it is new
1046                    #
1047                    cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), cfgcluster )
1048
1049                    os.mkdir( cluster_dir )
1050
1051                    dirlist.append( cfgcluster )
1052
1053            for item in dirlist:
1054
1055                clustername = item
1056
1057                if not self.clusters.has_key( clustername ) and clustername in ARCHIVE_DATASOURCES:
1058
1059                    self.clusters[ clustername ] = RRDHandler( self.config, clustername )
1060
1061        debug_msg( 9, "Found "+str(len(self.clusters.keys()))+" clusters" )
1062
1063    def startElement( self, name, attrs ):
1064        """Memorize appropriate data from xml start tags"""
1065
1066        if name == 'GANGLIA_XML':
1067
1068            self.XMLSource      = str( attrs.get( 'SOURCE',  "" ) )
1069            self.gangliaVersion = str( attrs.get( 'VERSION', "" ) )
1070
1071            debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
1072
1073        elif name == 'GRID':
1074
1075            self.gridName    = str( attrs.get( 'NAME', "" ) )
1076            self.time    = str( attrs.get( 'LOCALTIME', "" ) )
1077
1078            debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
1079
1080        elif name == 'CLUSTER':
1081
1082            self.clusterName = str( attrs.get( 'NAME',      "" ) )
1083            self.time        = str( attrs.get( 'LOCALTIME', "" ) )
1084
1085            if not self.clusters.has_key( self.clusterName ) and self.clusterName in ARCHIVE_DATASOURCES:
1086
1087                self.clusters[ self.clusterName ] = RRDHandler( self.config, self.clusterName )
1088
1089                debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
1090
1091        elif name == 'HOST' and self.clusterName in ARCHIVE_DATASOURCES:     
1092
1093            self.hostName     = str( attrs.get( 'NAME',     "" ) )
1094            self.hostIp       = str( attrs.get( 'IP',       "" ) )
1095            self.hostReported = str( attrs.get( 'REPORTED', "" ) )
1096
1097            debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
1098
1099        elif name == 'METRIC' and self.clusterName in ARCHIVE_DATASOURCES:
1100
1101            type = str( attrs.get( 'TYPE', "" ) )
1102           
1103            exclude_metric = False
1104           
1105            for ex_metricstr in ARCHIVE_EXCLUDE_METRICS:
1106
1107                orig_name = str( attrs.get( 'NAME', "" ) )
1108
1109                if string.lower( orig_name ) == string.lower( ex_metricstr ):
1110               
1111                    exclude_metric = True
1112
1113                elif re.match( ex_metricstr, orig_name ):
1114
1115                    exclude_metric = True
1116
1117            if type not in UNSUPPORTED_ARCHIVE_TYPES and not exclude_metric:
1118
1119                myMetric         = { }
1120                myMetric['name'] = str( attrs.get( 'NAME', "" ) )
1121                myMetric['val']  = str( attrs.get( 'VAL',  "" ) )
1122                myMetric['time'] = self.hostReported
1123
1124                self.clusters[ self.clusterName ].memMetric( self.hostName, myMetric )
1125
1126                debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
1127
1128    def storeMetrics( self ):
1129        """Store metrics of each cluster rrd handler"""
1130
1131        for clustername, rrdh in self.clusters.items():
1132
1133            ret = rrdh.storeMetrics()
1134
1135            if ret:
1136                debug_msg( 9, 'An error occured while storing metrics for cluster %s' %clustername )
1137                return 1
1138
1139        return 0
1140
1141class XMLErrorHandler( xml.sax.handler.ErrorHandler ):
1142
1143    def error( self, exception ):
1144        """Recoverable error"""
1145
1146        debug_msg( 0, 'Recoverable XML error ' + str( exception ) + ' ignored.' )
1147
1148    def fatalError( self, exception ):
1149        """Non-recoverable error"""
1150
1151        exception_str = str( exception )
1152
1153        # Ignore 'no element found' errors
1154        if exception_str.find( 'no element found' ) != -1:
1155            debug_msg( 0, 'No XML data found: Socket not (re)connected or datasource not available.' )
1156            return 0
1157
1158        debug_msg( 0, 'FATAL ERROR: Non-recoverable XML error ' + str( exception ) )
1159        sys.exit( 1 )
1160
1161    def warning( self, exception ):
1162        """Warning"""
1163
1164        debug_msg( 0, 'Warning ' + str( exception ) )
1165
1166class XMLGatherer:
1167    """Setup a connection and file object to Ganglia's XML"""
1168
1169    s        = None
1170    fd        = None
1171    data        = None
1172    slot        = None
1173
1174    # Time since the last update
1175    #
1176    LAST_UPDATE    = 0
1177
1178    # Minimum interval between updates
1179    #
1180    MIN_UPDATE_INT    = 10
1181
1182    # Is a update occuring now
1183    #
1184    update_now    = False
1185
1186    def __init__( self, host, port ):
1187        """Store host and port for connection"""
1188
1189        self.host    = host
1190        self.port    = port
1191        self.slot    = threading.Lock()
1192
1193        self.retrieveData()
1194
1195    def retrieveData( self ):
1196        """Setup connection to XML source"""
1197
1198        self.update_now    = True
1199
1200        self.slot.acquire()
1201
1202        self.data    = None
1203
1204        for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ):
1205
1206            af, socktype, proto, canonname, sa = res
1207
1208            try:
1209
1210                self.s = socket.socket( af, socktype, proto )
1211
1212            except ( socket.error, socket.gaierror, socket.herror, socket.timeout ), msg:
1213
1214                self.s = None
1215                continue
1216
1217            try:
1218
1219                self.s.connect( sa )
1220
1221            except ( socket.error, socket.gaierror, socket.herror, socket.timeout ), msg:
1222
1223                self.disconnect()
1224                continue
1225
1226            break
1227
1228        if self.s is None:
1229
1230            debug_msg( 0, 'FATAL ERROR: Could not open socket or unable to connect to datasource!' )
1231            self.update_now    = False
1232            #sys.exit( 1 )
1233
1234        else:
1235            #self.s.send( '\n' )
1236
1237            my_fp            = self.s.makefile( 'r' )
1238            my_data          = my_fp.readlines()
1239            my_data          = string.join( my_data, '' )
1240
1241            self.data        = my_data
1242
1243            self.LAST_UPDATE = time.time()
1244
1245        self.slot.release()
1246
1247        self.update_now    = False
1248
1249    def disconnect( self ):
1250        """Close socket"""
1251
1252        if self.s:
1253            #self.s.shutdown( 2 )
1254            self.s.close()
1255            self.s = None
1256
1257    def __del__( self ):
1258        """Kill the socket before we leave"""
1259
1260        self.disconnect()
1261
1262    def reGetData( self ):
1263        """Reconnect"""
1264
1265        while self.update_now:
1266
1267            # Must be another update in progress:
1268            # Wait until the update is complete
1269            #
1270            time.sleep( 1 )
1271
1272        if self.s:
1273            self.disconnect()
1274
1275        self.retrieveData()
1276
1277    def getData( self ):
1278
1279        """Return the XML data"""
1280
1281        # If more than MIN_UPDATE_INT seconds passed since last data update
1282        # update the XML first before returning it
1283        #
1284
1285        cur_time    = time.time()
1286
1287        if ( cur_time - self.LAST_UPDATE ) > self.MIN_UPDATE_INT:
1288
1289            self.reGetData()
1290
1291        while self.update_now:
1292
1293            # Must be another update in progress:
1294            # Wait until the update is complete
1295            #
1296            time.sleep( 1 )
1297           
1298        return self.data
1299
1300    def makeFileDescriptor( self ):
1301        """Make file descriptor that points to our socket connection"""
1302
1303        self.reconnect()
1304
1305        if self.s:
1306            self.fd = self.s.makefile( 'r' )
1307
1308    def getFileObject( self ):
1309        """Connect, and return a file object"""
1310
1311        self.makeFileDescriptor()
1312
1313        if self.fd:
1314            return self.fd
1315
1316class GangliaXMLProcessor( XMLProcessor ):
1317    """Main class for processing XML and acting with it"""
1318
1319    def __init__( self, XMLSource, DataStore ):
1320        """Setup initial XML connection and handlers"""
1321
1322        self.config       = GangliaConfigParser( GMETAD_CONF )
1323        self.myXMLSource  = XMLSource
1324        self.ds           = DataStore
1325        self.myXMLHandler = GangliaXMLHandler( self.config, self.ds )
1326        self.myXMLError   = XMLErrorHandler()
1327
1328    def run( self ):
1329        """Main XML processing; start a xml and storethread"""
1330
1331        xml_thread   = threading.Thread( None, self.processXML,   'xmlthread' )
1332        store_thread = threading.Thread( None, self.storeMetrics, 'storethread' )
1333
1334        while( 1 ):
1335
1336            if not xml_thread.isAlive():
1337                # Gather XML at the same interval as gmetad
1338
1339                # threaded call to: self.processXML()
1340                #
1341                try:
1342                    xml_thread = threading.Thread( None, self.processXML, 'xml_thread' )
1343                    xml_thread.start()
1344                except thread.error, msg:
1345                    debug_msg( 0, 'ERROR: Unable to start xml_thread!: '+str(msg))
1346                    #return 1
1347
1348            if not store_thread.isAlive():
1349                # Store metrics every .. sec
1350
1351                # threaded call to: self.storeMetrics()
1352                #
1353                try:
1354                    store_thread = threading.Thread( None, self.storeMetrics, 'store_thread' )
1355                    store_thread.start()
1356                except thread.error, msg:
1357                    debug_msg( 0, 'ERROR: Unable to start store_thread!: '+str(msg))
1358                    #return 1
1359       
1360            # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway
1361            time.sleep( 1 )   
1362
1363    def storeMetrics( self ):
1364        """Store metrics retained in memory to disk"""
1365
1366        global DEBUG_LEVEL
1367
1368        # Store metrics somewhere between every 360 and 640 seconds
1369        #
1370        if DEBUG_LEVEL >= 1:
1371            STORE_INTERVAL = 60
1372        else:
1373            STORE_INTERVAL = random.randint( 360, 640 )
1374
1375        try:
1376            store_metric_thread = threading.Thread( None, self.storeThread, 'store_metric_thread' )
1377            store_metric_thread.start()
1378        except thread.error, msg:
1379            debug_msg( 0, 'ERROR: Unable to start ganglia_store_thread()!: '+str(msg) )
1380            return 1
1381
1382        debug_msg( 1, 'ganglia_store_thread(): started.' )
1383
1384        debug_msg( 1, 'ganglia_store_thread(): Sleeping.. (%ss)' %STORE_INTERVAL )
1385        time.sleep( STORE_INTERVAL )
1386        debug_msg( 1, 'ganglia_store_thread(): Done sleeping.' )
1387
1388        if store_metric_thread.isAlive():
1389
1390            debug_msg( 1, 'ganglia_store_thread(): storemetricthread() still running, waiting to finish..' )
1391            store_metric_thread.join( STORE_TIMEOUT ) # Maximum time is for storing thread to finish
1392
1393            if store_metric_thread.isAlive():
1394
1395                debug_msg( 1, 'ganglia_store_thread(): Done waiting: storemetricthread() still running :( now what?' )
1396            else:
1397                debug_msg( 1, 'ganglia_store_thread(): Done waiting: storemetricthread() has finished' )
1398
1399        debug_msg( 1, 'ganglia_store_thread(): finished.' )
1400
1401        return 0
1402
1403    def storeThread( self ):
1404        """Actual metric storing thread"""
1405
1406        debug_msg( 1, 'ganglia_store_metric_thread(): started.' )
1407        debug_msg( 1, 'ganglia_store_metric_thread(): Storing data..' )
1408
1409        ret = self.myXMLHandler.storeMetrics()
1410        if ret > 0:
1411            debug_msg( 0, 'ganglia_store_metric_thread(): UNKNOWN ERROR %s while storing Metrics!' %str(ret) )
1412
1413        debug_msg( 1, 'ganglia_store_metric_thread(): Done storing.' )
1414        debug_msg( 1, 'ganglia_store_metric_thread(): finished.' )
1415       
1416        return 0
1417
1418    def processXML( self ):
1419        """Process XML"""
1420
1421        try:
1422            parsethread = threading.Thread( None, self.parseThread, 'parsethread' )
1423            parsethread.start()
1424        except thread.error, msg:
1425            debug_msg( 0, 'ERROR: Unable to start ganglia_xml_thread()!: ' + str(msg) )
1426            return 1
1427
1428        debug_msg( 1, 'ganglia_xml_thread(): started.' )
1429
1430        debug_msg( 1, 'ganglia_xml_thread(): Sleeping.. (%ss)' %self.config.getLowestInterval() )
1431        time.sleep( float( self.config.getLowestInterval() ) )   
1432        debug_msg( 1, 'ganglia_xml_thread(): Done sleeping.' )
1433
1434        if parsethread.isAlive():
1435
1436            debug_msg( 1, 'ganglia_xml_thread(): parsethread() still running, waiting (%ss) to finish..' %PARSE_TIMEOUT )
1437            parsethread.join( PARSE_TIMEOUT ) # Maximum time for XML thread to finish
1438
1439            if parsethread.isAlive():
1440                debug_msg( 1, 'ganglia_xml_thread(): Done waiting: parsethread() still running :( now what?' )
1441            else:
1442                debug_msg( 1, 'ganglia_xml_thread(): Done waiting: parsethread() finished' )
1443
1444        debug_msg( 1, 'ganglia_xml_thread(): finished.' )
1445
1446        return 0
1447
1448    def parseThread( self ):
1449        """Actual parsing thread"""
1450
1451        debug_msg( 1, 'ganglia_parse_thread(): started.' )
1452        debug_msg( 1, 'ganglia_parse_thread(): Retrieving XML data..' )
1453       
1454        my_data    = self.myXMLSource.getData()
1455
1456        debug_msg( 1, 'ganglia_parse_thread(): Done retrieving: data size %d' %len(my_data) )
1457
1458        if my_data:
1459            debug_msg( 1, 'ganglia_parse_thread(): Parsing XML..' )
1460            xml.sax.parseString( my_data, self.myXMLHandler, self.myXMLError )
1461            debug_msg( 1, 'ganglia_parse_thread(): Done parsing.' )
1462
1463        debug_msg( 1, 'ganglia_parse_thread(): finished.' )
1464
1465        return 0
1466
1467class GangliaConfigParser:
1468
1469    sources = [ ]
1470
1471    def __init__( self, config ):
1472        """Parse some stuff from our gmetad's config, such as polling interval"""
1473
1474        self.config = config
1475        self.parseValues()
1476
1477    def parseValues( self ):
1478        """Parse certain values from gmetad.conf"""
1479
1480        readcfg = open( self.config, 'r' )
1481
1482        for line in readcfg.readlines():
1483
1484            if line.count( '"' ) > 1:
1485
1486                if line.find( 'data_source' ) != -1 and line[0] != '#':
1487
1488                    source        = { }
1489                    source['name']    = line.split( '"' )[1]
1490                    source_words    = line.split( '"' )[2].split( ' ' )
1491
1492                    for word in source_words:
1493
1494                        valid_interval = 1
1495
1496                        for letter in word:
1497
1498                            if letter not in string.digits:
1499
1500                                valid_interval = 0
1501
1502                        if valid_interval and len(word) > 0:
1503
1504                            source['interval'] = word
1505                            debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
1506   
1507                    # No interval found, use Ganglia's default   
1508                    if not source.has_key( 'interval' ):
1509                        source['interval'] = 15
1510                        debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
1511
1512                    self.sources.append( source )
1513
1514    def getInterval( self, source_name ):
1515        """Return interval for source_name"""
1516
1517        for source in self.sources:
1518
1519            if source['name'] == source_name:
1520
1521                return source['interval']
1522
1523        return None
1524
1525    def getLowestInterval( self ):
1526        """Return the lowest interval of all clusters"""
1527
1528        lowest_interval = 0
1529
1530        for source in self.sources:
1531
1532            if not lowest_interval or source['interval'] <= lowest_interval:
1533
1534                lowest_interval = source['interval']
1535
1536        # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays
1537        if lowest_interval:
1538            return lowest_interval
1539        else:
1540            return 15
1541
1542class RRDHandler:
1543    """Class for handling RRD activity"""
1544
1545    myMetrics = { }
1546    lastStored = { }
1547    timeserials = { }
1548    slot = None
1549
1550    def __init__( self, config, cluster ):
1551        """Setup initial variables"""
1552
1553        global MODRRDTOOL
1554
1555        self.block    = 0
1556        self.cluster    = cluster
1557        self.config    = config
1558        self.slot    = threading.Lock()
1559
1560        if MODRRDTOOL:
1561
1562            self.rrdm    = RRDMutator()
1563        else:
1564            self.rrdm    = RRDMutator( RRDTOOL )
1565
1566        global DEBUG_LEVEL
1567
1568        if DEBUG_LEVEL <= 2:
1569            self.gatherLastUpdates()
1570
1571    def gatherLastUpdates( self ):
1572        """Populate the lastStored list, containing timestamps of all last updates"""
1573
1574        cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster )
1575
1576        hosts = [ ]
1577
1578        if os.path.exists( cluster_dir ):
1579
1580            dirlist = os.listdir( cluster_dir )
1581
1582            for dir in dirlist:
1583
1584                hosts.append( dir )
1585
1586        for host in hosts:
1587
1588            host_dir    = cluster_dir + '/' + host
1589            dirlist        = os.listdir( host_dir )
1590
1591            for dir in dirlist:
1592
1593                if not self.timeserials.has_key( host ):
1594
1595                    self.timeserials[ host ] = [ ]
1596
1597                self.timeserials[ host ].append( dir )
1598
1599            last_serial = self.getLastRrdTimeSerial( host )
1600
1601            if last_serial:
1602
1603                metric_dir = cluster_dir + '/' + host + '/' + last_serial
1604
1605                if os.path.exists( metric_dir ):
1606
1607                    dirlist = os.listdir( metric_dir )
1608
1609                    for file in dirlist:
1610
1611                        metricname = file.split( '.rrd' )[0]
1612
1613                        if not self.lastStored.has_key( host ):
1614
1615                            self.lastStored[ host ] = { }
1616
1617                        self.lastStored[ host ][ metricname ] = self.rrdm.grabLastUpdate( metric_dir + '/' + file )
1618
1619    def getClusterName( self ):
1620        """Return clustername"""
1621
1622        return self.cluster
1623
1624    def memMetric( self, host, metric ):
1625        """Store metric from host in memory"""
1626
1627        # <ATOMIC>
1628        #
1629        self.slot.acquire()
1630       
1631        if self.myMetrics.has_key( host ):
1632
1633            if self.myMetrics[ host ].has_key( metric['name'] ):
1634
1635                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
1636
1637                    if mymetric['time'] == metric['time']:
1638
1639                        # Allready have this metric, abort
1640                        self.slot.release()
1641                        return 1
1642            else:
1643                self.myMetrics[ host ][ metric['name'] ] = [ ]
1644        else:
1645            self.myMetrics[ host ]                = { }
1646            self.myMetrics[ host ][ metric['name'] ]    = [ ]
1647
1648        # Push new metric onto stack
1649        # atomic code; only 1 thread at a time may access the stack
1650
1651        self.myMetrics[ host ][ metric['name'] ].append( metric )
1652
1653        self.slot.release()
1654        #
1655        # </ATOMIC>
1656
1657    def makeUpdateList( self, host, metriclist ):
1658        """
1659        Make a list of update values for rrdupdate
1660        but only those that we didn't store before
1661        """
1662
1663        update_list    = [ ]
1664        metric        = None
1665
1666        while len( metriclist ) > 0:
1667
1668            metric = metriclist.pop( 0 )
1669
1670            if self.checkStoreMetric( host, metric ):
1671
1672                u_val    = str( metric['time'] ) + ':' + str( metric['val'] )
1673                #update_list.append( str('%s:%s') %( metric['time'], metric['val'] ) )
1674                update_list.append( u_val )
1675
1676        return update_list
1677
1678    def checkStoreMetric( self, host, metric ):
1679        """Check if supplied metric if newer than last one stored"""
1680
1681        if self.lastStored.has_key( host ):
1682
1683            if self.lastStored[ host ].has_key( metric['name'] ):
1684
1685                if metric['time'] <= self.lastStored[ host ][ metric['name'] ]:
1686
1687                    # This is old
1688                    return 0
1689
1690        return 1
1691
1692    def memLastUpdate( self, host, metricname, metriclist ):
1693        """
1694        Memorize the time of the latest metric from metriclist
1695        but only if it wasn't allready memorized
1696        """
1697
1698        if not self.lastStored.has_key( host ):
1699            self.lastStored[ host ] = { }
1700
1701        last_update_time = 0
1702
1703        for metric in metriclist:
1704
1705            if metric['name'] == metricname:
1706
1707                if metric['time'] > last_update_time:
1708
1709                    last_update_time = metric['time']
1710
1711        if self.lastStored[ host ].has_key( metricname ):
1712           
1713            if last_update_time <= self.lastStored[ host ][ metricname ]:
1714                return 1
1715
1716        self.lastStored[ host ][ metricname ] = last_update_time
1717
1718    def storeMetrics( self ):
1719        """
1720        Store all metrics from memory to disk
1721        and do it to the RRD's in appropriate timeperiod directory
1722        """
1723
1724        debug_msg( 5, "Entering storeMetrics()")
1725
1726        count_values  = 0
1727        count_metrics = 0
1728        count_bits    = 0
1729
1730        for hostname, mymetrics in self.myMetrics.items():   
1731
1732            for metricname, mymetric in mymetrics.items():
1733
1734                count_metrics += 1
1735
1736                for dmetric in mymetric:
1737
1738                    count_values += 1
1739
1740                    count_bits   += len( dmetric['time'] )
1741                    count_bits   += len( dmetric['val'] )
1742
1743        count_bytes    = count_bits / 8
1744
1745        debug_msg( 5, "size of cluster '" + self.cluster + "': " + 
1746            str( len( self.myMetrics.keys() ) ) + " hosts " + 
1747            str( count_metrics ) + " metrics " + str( count_values ) + " values " +
1748            str( count_bits ) + " bits " + str( count_bytes ) + " bytes " )
1749
1750        for hostname, mymetrics in self.myMetrics.items():   
1751
1752            for metricname, mymetric in mymetrics.items():
1753
1754                metrics_to_store = [ ]
1755
1756                # Pop metrics from stack for storing until none is left
1757                # atomic code: only 1 thread at a time may access myMetrics
1758
1759                # <ATOMIC>
1760                #
1761                self.slot.acquire() 
1762
1763                while len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1764
1765                    if len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1766
1767                        try:
1768                            metrics_to_store.append( self.myMetrics[ hostname ][ metricname ].pop( 0 ) )
1769                        except IndexError, msg:
1770
1771                            # Somehow sometimes myMetrics[ hostname ][ metricname ]
1772                            # is still len 0 when the statement is executed.
1773                            # Just ignore indexerror's..
1774                            pass
1775
1776                self.slot.release()
1777                #
1778                # </ATOMIC>
1779
1780                # Create a mapping table, each metric to the period where it should be stored
1781                #
1782                metric_serial_table = self.determineSerials( hostname, metricname, metrics_to_store )
1783
1784                update_rets = [ ]
1785
1786                for period, pmetric in metric_serial_table.items():
1787
1788                    create_ret = self.createCheck( hostname, metricname, period )   
1789
1790                    update_ret = self.update( hostname, metricname, period, pmetric )
1791
1792                    if update_ret == 0:
1793
1794                        debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
1795                    else:
1796                        debug_msg( 9, 'metric update failed' )
1797
1798                    update_rets.append( create_ret )
1799                    update_rets.append( update_ret )
1800
1801                # Lets ignore errors here for now, we need to make sure last update time
1802                # is correct!
1803                #
1804                #if not (1) in update_rets:
1805
1806                self.memLastUpdate( hostname, metricname, metrics_to_store )
1807
1808        debug_msg( 5, "Leaving storeMetrics()")
1809
1810    def makeTimeSerial( self ):
1811        """Generate a time serial. Seconds since epoch"""
1812
1813        # Seconds since epoch
1814        mytime = int( time.time() )
1815
1816        return mytime
1817
1818    def makeRrdPath( self, host, metricname, timeserial ):
1819        """Make a RRD location/path and filename"""
1820
1821        rrd_dir        = '%s/%s/%s/%s'    %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
1822        rrd_file    = '%s/%s.rrd'    %( rrd_dir, metricname )
1823
1824        return rrd_dir, rrd_file
1825
1826    def getLastRrdTimeSerial( self, host ):
1827        """Find the last timeserial (directory) for this host"""
1828
1829        newest_timeserial = 0
1830
1831        for dir in self.timeserials[ host ]:
1832
1833            valid_dir = 1
1834
1835            for letter in dir:
1836                if letter not in string.digits:
1837                    valid_dir = 0
1838
1839            if valid_dir:
1840                timeserial = dir
1841                if timeserial > newest_timeserial:
1842                    newest_timeserial = timeserial
1843
1844        if newest_timeserial:
1845            return newest_timeserial
1846        else:
1847            return 0
1848
1849    def determinePeriod( self, host, check_serial ):
1850        """Determine to which period (directory) this time(serial) belongs"""
1851
1852        period_serial = 0
1853
1854        if self.timeserials.has_key( host ):
1855
1856            for serial in self.timeserials[ host ]:
1857
1858                if check_serial >= serial and period_serial < serial:
1859
1860                    period_serial = serial
1861
1862        return period_serial
1863
1864    def determineSerials( self, host, metricname, metriclist ):
1865        """
1866        Determine the correct serial and corresponding rrd to store
1867        for a list of metrics
1868        """
1869
1870        metric_serial_table = { }
1871
1872        for metric in metriclist:
1873
1874            if metric['name'] == metricname:
1875
1876                period        = self.determinePeriod( host, metric['time'] )   
1877
1878                archive_secs    = ARCHIVE_HOURS_PER_RRD * (60 * 60)
1879
1880                if (int( metric['time'] ) - int( period ) ) > archive_secs:
1881
1882                    # This one should get it's own new period
1883                    period = metric['time']
1884
1885                    if not self.timeserials.has_key( host ):
1886                        self.timeserials[ host ] = [ ]
1887
1888                    self.timeserials[ host ].append( period )
1889
1890                if not metric_serial_table.has_key( period ):
1891
1892                    metric_serial_table[ period ] = [ ]
1893
1894                metric_serial_table[ period ].append( metric )
1895
1896        return metric_serial_table
1897
1898    def createCheck( self, host, metricname, timeserial ):
1899        """Check if an rrd allready exists for this metric, create if not"""
1900
1901        debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1902       
1903        rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
1904
1905        if not os.path.exists( rrd_dir ):
1906
1907            try:
1908                os.makedirs( rrd_dir )
1909
1910            except os.OSError, msg:
1911
1912                if msg.find( 'File exists' ) != -1:
1913
1914                    # Ignore exists errors
1915                    pass
1916
1917                else:
1918
1919                    print msg
1920                    return
1921
1922            debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
1923
1924        if not os.path.exists( rrd_file ):
1925
1926            interval    = self.config.getInterval( self.cluster )
1927            heartbeat    = 8 * int( interval )
1928
1929            params        = [ ]
1930
1931            params.append( '--step' )
1932            params.append( str( interval ) )
1933
1934            params.append( '--start' )
1935            params.append( str( int( timeserial ) - 1 ) )
1936
1937            params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat )
1938            params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) )
1939
1940            self.rrdm.create( str(rrd_file), params )
1941
1942            debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
1943
1944    def update( self, host, metricname, timeserial, metriclist ):
1945        """
1946        Update rrd file for host with metricname
1947        in directory timeserial with metriclist
1948        """
1949
1950        debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1951
1952        rrd_dir, rrd_file    = self.makeRrdPath( host, metricname, timeserial )
1953
1954        update_list        = self.makeUpdateList( host, metriclist )
1955
1956        if len( update_list ) > 0:
1957            ret = self.rrdm.update( str(rrd_file), update_list )
1958
1959            if ret:
1960                return 1
1961       
1962            debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) )
1963
1964        return 0
1965
1966def daemon():
1967    """daemonized threading"""
1968
1969    # Fork the first child
1970    #
1971    pid = os.fork()
1972
1973    if pid > 0:
1974
1975        sys.exit(0)  # end parent
1976
1977    # creates a session and sets the process group ID
1978    #
1979    os.setsid()
1980
1981    # Fork the second child
1982    #
1983    pid = os.fork()
1984
1985    if pid > 0:
1986
1987        sys.exit(0)  # end parent
1988
1989    write_pidfile()
1990
1991    # Go to the root directory and set the umask
1992    #
1993    os.chdir('/')
1994    os.umask(0)
1995
1996    sys.stdin.close()
1997    sys.stdout.close()
1998    sys.stderr.close()
1999
2000    os.open('/dev/null', os.O_RDWR)
2001    os.dup2(0, 1)
2002    os.dup2(0, 2)
2003
2004    run()
2005
2006def run():
2007    """Threading start"""
2008
2009    config             = GangliaConfigParser( GMETAD_CONF )
2010    s_timeout          = int( config.getLowestInterval() - 1 )
2011
2012    socket.setdefaulttimeout( s_timeout )
2013
2014    myXMLSource        = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] )
2015    myDataStore        = DataSQLStore( JOB_SQL_DBASE.split( '/' )[0], JOB_SQL_DBASE.split( '/' )[1] )
2016
2017    myJobProcessor     = JobXMLProcessor( myXMLSource, myDataStore )
2018    myGangliaProcessor = GangliaXMLProcessor( myXMLSource, myDataStore )
2019
2020    try:
2021        job_xml_thread     = threading.Thread( None, myJobProcessor.run, 'job_proc_thread' )
2022        ganglia_xml_thread = threading.Thread( None, myGangliaProcessor.run, 'ganglia_proc_thread' )
2023
2024        job_xml_thread.start()
2025        ganglia_xml_thread.start()
2026       
2027    except thread.error, msg:
2028        debug_msg( 0, 'FATAL ERROR: Unable to start main threads!: '+ str(msg) )
2029        syslog.closelog()
2030        sys.exit(1)
2031       
2032    debug_msg( 0, 'main threading started.' )
2033
2034def main():
2035    """Program startup"""
2036
2037    global DAEMONIZE, USE_SYSLOG
2038
2039    if not processArgs( sys.argv[1:] ):
2040        sys.exit( 1 )
2041
2042    if( DAEMONIZE and USE_SYSLOG ):
2043        syslog.openlog( 'jobarchived', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
2044
2045    if DAEMONIZE:
2046        daemon()
2047    else:
2048        run()
2049
2050#
2051# Global functions
2052#
2053
2054def check_dir( directory ):
2055    """Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"""
2056
2057    if directory[-1] == '/':
2058        directory = directory[:-1]
2059
2060    return directory
2061
2062def reqtime2epoch( rtime ):
2063
2064    (hours, minutes, seconds )    = rtime.split( ':' )
2065
2066    etime    = int(seconds)
2067    etime    = etime + ( int(minutes) * 60 )
2068    etime    = etime + ( int(hours) * 60 * 60 )
2069
2070    return etime
2071
2072def debug_msg( level, msg ):
2073    """Only print msg if correct levels"""
2074
2075    if (not DAEMONIZE and DEBUG_LEVEL >= level):
2076        sys.stderr.write( printTime() + ' - ' + msg + '\n' )
2077   
2078    if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
2079        syslog.syslog( msg )
2080
2081def printTime( ):
2082    """Print current time in human readable format"""
2083
2084    return time.strftime("%a %d %b %Y %H:%M:%S")
2085
2086def write_pidfile():
2087
2088    # Write pidfile if PIDFILE exists
2089    if PIDFILE:
2090
2091        pid     = os.getpid()
2092
2093        pidfile = open(PIDFILE, 'w')
2094
2095        pidfile.write( str( pid ) )
2096        pidfile.close()
2097
2098# Ooohh, someone started me! Let's go..
2099#
2100if __name__ == '__main__':
2101    main()
Note: See TracBrowser for help on using the repository browser.