source: trunk/jobarchived/jobarchived.py @ 224

Last change on this file since 224 was 224, checked in by bastiaans, 18 years ago

jobarchived/examples:

  • added

jobmond/jobmond.py:

  • removed config option comments

jobarchived/jobarchived.py:

  • removed config option comments
  • added RRDTOOL option

jobmond/jobmond.conf:

  • added config option comments

jobarchived/jobarchived.conf:

  • added config option comments
  • added RRDTOOL option
File size: 35.5 KB
Line 
1#!/usr/bin/env python
2
3import getopt, syslog, ConfigParser, sys
4
5def processArgs( args ):
6
7        SHORT_L = 'c:'
8        LONG_L = 'config='
9
10        config_filename = None
11
12        try:
13
14                opts, args = getopt.getopt( args, SHORT_L, LONG_L )
15
16        except getopt.error, detail:
17
18                print detail
19                sys.exit(1)
20
21        for opt, value in opts:
22
23                if opt in [ '--config', '-c' ]:
24
25                        config_filename = value
26
27        if not config_filename:
28
29                config_filename = '/etc/jobarchived.conf'
30
31        try:
32                return loadConfig( config_filename )
33
34        except ConfigParser.NoOptionError, detail:
35
36                print detail
37                sys.exit( 1 )
38
39def loadConfig( filename ):
40
41        def getlist( cfg_string ):
42
43                my_list = [ ]
44
45                for item_txt in cfg_string.split( ',' ):
46
47                        sep_char = None
48
49                        item_txt = item_txt.strip()
50
51                        for s_char in [ "'", '"' ]:
52
53                                if item_txt.find( s_char ) != -1:
54
55                                        if item_txt.count( s_char ) != 2:
56
57                                                print 'Missing quote: %s' %item_txt
58                                                sys.exit( 1 )
59
60                                        else:
61
62                                                sep_char = s_char
63                                                break
64
65                        if sep_char:
66
67                                item_txt = item_txt.split( sep_char )[1]
68
69                        my_list.append( item_txt )
70
71                return my_list
72
73        cfg = ConfigParser.ConfigParser()
74
75        cfg.read( filename )
76
77        global DEBUG_LEVEL, USE_SYSLOG, SYSLOG_LEVEL, SYSLOG_FACILITY, GMETAD_CONF, ARCHIVE_XMLSOURCE, ARCHIVE_DATASOURCES, ARCHIVE_PATH, ARCHIVE_HOURS_PER_RRD, ARCHIVE_EXCLUDE_METRICS, JOB_SQL_DBASE, DAEMONIZE, RRDTOOL
78
79        ARCHIVE_PATH = cfg.get( 'DEFAULT', 'ARCHIVE_PATH' )
80
81        ARCHIVE_HOURS_PER_RRD = cfg.getint( 'DEFAULT', 'ARCHIVE_HOURS_PER_RRD' )
82
83        DEBUG_LEVEL = cfg.getint( 'DEFAULT', 'DEBUG_LEVEL' )
84
85        USE_SYSLOG = cfg.getboolean( 'DEFAULT', 'USE_SYSLOG' )
86
87        SYSLOG_LEVEL = cfg.getint( 'DEFAULT', 'SYSLOG_LEVEL' )
88
89        try:
90
91                SYSLOG_FACILITY = eval( 'syslog.LOG_' + cfg.get( 'DEFAULT', 'SYSLOG_FACILITY' ) )
92
93        except AttributeError, detail:
94
95                print 'Unknown syslog facility'
96                sys.exit( 1 )
97
98        GMETAD_CONF = cfg.get( 'DEFAULT', 'GMETAD_CONF' )
99
100        ARCHIVE_XMLSOURCE = cfg.get( 'DEFAULT', 'ARCHIVE_XMLSOURCE' )
101
102        ARCHIVE_DATASOURCES = getlist( cfg.get( 'DEFAULT', 'ARCHIVE_DATASOURCES' ) )
103
104        ARCHIVE_EXCLUDE_METRICS = getlist( cfg.get( 'DEFAULT', 'ARCHIVE_EXCLUDE_METRICS' ) )
105
106        JOB_SQL_DBASE = cfg.get( 'DEFAULT', 'JOB_SQL_DBASE' )
107
108        DAEMONIZE = cfg.getboolean( 'DEFAULT', 'DAEMONIZE' )
109
110        RRDTOOL = cfg.get( 'DEFAULT', 'RRDTOOL' )
111
112        return True
113
114# What XML data types not to store
115#
116UNSUPPORTED_ARCHIVE_TYPES = [ 'string' ]
117
118# Maximum time (in seconds) a parsethread may run
119#
120PARSE_TIMEOUT = 60
121
122# Maximum time (in seconds) a storethread may run
123#
124STORE_TIMEOUT = 360
125
126"""
127The Job Archiving Daemon
128"""
129
130from types import *
131
132import DBClass
133import xml.sax, xml.sax.handler, socket, string, os, os.path, time, thread, threading, random, re
134
135class DataSQLStore:
136
137        db_vars = None
138        dbc = None
139
140        def __init__( self, hostname, database ):
141
142                self.db_vars = DBClass.InitVars(DataBaseName=database,
143                                User='root',
144                                Host=hostname,
145                                Password='',
146                                Dictionary='true')
147
148                try:
149                        self.dbc     = DBClass.DB(self.db_vars)
150                except DBClass.DBError, details:
151                        debug_msg( 0, 'FATAL ERROR: Unable to connect to database!: ' +str(details) )
152                        sys.exit(1)
153
154        def setDatabase(self, statement):
155                ret = self.doDatabase('set', statement)
156                return ret
157               
158        def getDatabase(self, statement):
159                ret = self.doDatabase('get', statement)
160                return ret
161
162        def doDatabase(self, type, statement):
163
164                debug_msg( 6, 'doDatabase(): %s: %s' %(type, statement) )
165                try:
166                        if type == 'set':
167                                result = self.dbc.Set( statement )
168                                self.dbc.Commit()
169                        elif type == 'get':
170                                result = self.dbc.Get( statement )
171                               
172                except DBClass.DBError, detail:
173                        operation = statement.split(' ')[0]
174                        debug_msg( 0, 'FATAL ERROR: ' +operation+ ' on database failed while doing ['+statement+'] full msg: '+str(detail) )
175                        sys.exit(1)
176
177                debug_msg( 6, 'doDatabase(): result: %s' %(result) )
178                return result
179
180        def getJobNodeId( self, job_id, node_id ):
181
182                id = self.getDatabase( "SELECT job_id,node_id FROM job_nodes WHERE job_id = '%s' AND node_id = '%s'" %(job_id, node_id) )
183                if len( id ) > 0:
184
185                        if len( id[0] ) > 0 and id[0] != '':
186                       
187                                return 1
188
189                return 0
190
191        def getNodeId( self, hostname ):
192
193                id = self.getDatabase( "SELECT node_id FROM nodes WHERE node_hostname = '%s'" %hostname )
194
195                if len( id ) > 0:
196
197                        id = id[0][0]
198
199                        return id
200                else:
201                        return None
202
203        def getNodeIds( self, hostnames ):
204
205                ids = [ ]
206
207                for node in hostnames:
208
209                        id = self.getNodeId( node )
210
211                        if id:
212                                ids.append( id )
213
214                return ids
215
216        def getJobId( self, jobid ):
217
218                id = self.getDatabase( "SELECT job_id FROM jobs WHERE job_id = '%s'" %jobid )
219
220                if id:
221                        id = id[0][0]
222
223                        return id
224                else:
225                        return None
226
227        def addJob( self, job_id, jobattrs ):
228
229                if not self.getJobId( job_id ):
230
231                        self.mutateJob( 'insert', job_id, jobattrs ) 
232                else:
233                        self.mutateJob( 'update', job_id, jobattrs )
234
235        def mutateJob( self, action, job_id, jobattrs ):
236
237                job_values = [ 'name', 'queue', 'owner', 'requested_time', 'requested_memory', 'ppn', 'status', 'start_timestamp', 'stop_timestamp' ]
238
239                insert_col_str = 'job_id'
240                insert_val_str = "'%s'" %job_id
241                update_str = None
242
243                debug_msg( 6, 'mutateJob(): %s %s' %(action,job_id))
244
245                ids = [ ]
246
247                for valname, value in jobattrs.items():
248
249                        if valname in job_values and value != '':
250
251                                column_name = 'job_' + valname
252
253                                if action == 'insert':
254
255                                        if not insert_col_str:
256                                                insert_col_str = column_name
257                                        else:
258                                                insert_col_str = insert_col_str + ',' + column_name
259
260                                        if not insert_val_str:
261                                                insert_val_str = value
262                                        else:
263                                                insert_val_str = insert_val_str + ",'%s'" %value
264
265                                elif action == 'update':
266                                       
267                                        if not update_str:
268                                                update_str = "%s='%s'" %(column_name, value)
269                                        else:
270                                                update_str = update_str + ",%s='%s'" %(column_name, value)
271
272                        elif valname == 'nodes' and value:
273
274                                node_valid = 1
275
276                                if len(value) == 1:
277                               
278                                        if jobattrs['status'] == 'Q':
279
280                                                node_valid = 0
281
282                                        else:
283
284                                                node_valid = 0
285
286                                                for node_char in str(value[0]):
287
288                                                        if string.find( string.digits, node_char ) != -1 and not node_valid:
289
290                                                                node_valid = 1
291
292                                if node_valid:
293
294                                        ids = self.addNodes( value, jobattrs['domain'] )
295
296                if action == 'insert':
297
298                        self.setDatabase( "INSERT INTO jobs ( %s ) VALUES ( %s )" %( insert_col_str, insert_val_str ) )
299
300                elif action == 'update':
301
302                        self.setDatabase( "UPDATE jobs SET %s WHERE job_id=%s" %(update_str, job_id) )
303
304                if len( ids ) > 0:
305                        self.addJobNodes( job_id, ids )
306
307        def addNodes( self, hostnames, domain ):
308
309                ids = [ ]
310
311                for node in hostnames:
312
313                        node = '%s.%s' %( node, domain )
314                        id = self.getNodeId( node )
315       
316                        if not id:
317                                self.setDatabase( "INSERT INTO nodes ( node_hostname ) VALUES ( '%s' )" %node )
318                                id = self.getNodeId( node )
319
320                        ids.append( id )
321
322                return ids
323
324        def addJobNodes( self, jobid, nodes ):
325
326                for node in nodes:
327
328                        if not self.getJobNodeId( jobid, node ):
329
330                                self.addJobNode( jobid, node )
331
332        def addJobNode( self, jobid, nodeid ):
333
334                self.setDatabase( "INSERT INTO job_nodes (job_id,node_id) VALUES ( %s,%s )" %(jobid, nodeid) )
335
336        def storeJobInfo( self, jobid, jobattrs ):
337
338                self.addJob( jobid, jobattrs )
339
340class RRDMutator:
341        """A class for performing RRD mutations"""
342
343        binary = RRDTOOL
344
345        def __init__( self, binary=None ):
346                """Set alternate binary if supplied"""
347
348                if binary:
349                        self.binary = binary
350
351        def create( self, filename, args ):
352                """Create a new rrd with args"""
353
354                return self.perform( 'create', '"' + filename + '"', args )
355
356        def update( self, filename, args ):
357                """Update a rrd with args"""
358
359                return self.perform( 'update', '"' + filename + '"', args )
360
361        def grabLastUpdate( self, filename ):
362                """Determine the last update time of filename rrd"""
363
364                last_update = 0
365
366                debug_msg( 8, self.binary + ' info "' + filename + '"' )
367
368                for line in os.popen( self.binary + ' info "' + filename + '"' ).readlines():
369
370                        if line.find( 'last_update') != -1:
371
372                                last_update = line.split( ' = ' )[1]
373
374                if last_update:
375                        return last_update
376                else:
377                        return 0
378
379        def perform( self, action, filename, args ):
380                """Perform action on rrd filename with args"""
381
382                arg_string = None
383
384                if type( args ) is not ListType:
385                        debug_msg( 8, 'Arguments needs to be of type List' )
386                        return 1
387
388                for arg in args:
389
390                        if not arg_string:
391
392                                arg_string = arg
393                        else:
394                                arg_string = arg_string + ' ' + arg
395
396                debug_msg( 8, self.binary + ' ' + action + ' ' + filename + ' ' + arg_string  )
397
398                cmd = os.popen( self.binary + ' ' + action + ' ' + filename + ' ' + arg_string )
399                lines = cmd.readlines()
400                cmd.close()
401
402                for line in lines:
403
404                        if line.find( 'ERROR' ) != -1:
405
406                                error_msg = string.join( line.split( ' ' )[1:] )
407                                debug_msg( 8, error_msg )
408                                return 1
409
410                return 0
411
412class XMLProcessor:
413        """Skeleton class for XML processor's"""
414
415        def run( self ):
416                """Do main processing of XML here"""
417
418                pass
419
420class TorqueXMLProcessor( XMLProcessor ):
421        """Main class for processing XML and acting with it"""
422
423        def __init__( self ):
424                """Setup initial XML connection and handlers"""
425
426                self.myXMLGatherer = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] ) 
427                self.myXMLSource = self.myXMLGatherer.getFileObject()
428                self.myXMLHandler = TorqueXMLHandler()
429                self.myXMLError = XMLErrorHandler()
430                self.config = GangliaConfigParser( GMETAD_CONF )
431
432        def run( self ):
433                """Main XML processing"""
434
435                debug_msg( 1, 'torque_xml_thread(): started.' )
436
437                while( 1 ):
438
439                        self.myXMLSource = self.myXMLGatherer.getFileObject()
440                        debug_msg( 1, 'torque_xml_thread(): Parsing..' )
441
442                        try:
443                                xml.sax.parse( self.myXMLSource, self.myXMLHandler, self.myXMLError )
444                        except socket.error, msg:
445                                debug_msg( 0, 'ERROR: Socket error in connect to datasource!: %s' %msg )
446                               
447                        debug_msg( 1, 'torque_xml_thread(): Done parsing.' )
448                        debug_msg( 1, 'torque_xml_thread(): Sleeping.. (%ss)' %(str( self.config.getLowestInterval() ) ) )
449                        time.sleep( self.config.getLowestInterval() )
450
451class TorqueXMLHandler( xml.sax.handler.ContentHandler ):
452        """Parse Torque's jobinfo XML from our plugin"""
453
454        jobAttrs = { }
455
456        def __init__( self ):
457
458                self.ds = DataSQLStore( JOB_SQL_DBASE.split( '/' )[0], JOB_SQL_DBASE.split( '/' )[1] )
459                self.jobs_processed = [ ]
460                self.jobs_to_store = [ ]
461
462        def startDocument( self ):
463
464                self.heartbeat = 0
465
466        def startElement( self, name, attrs ):
467                """
468                This XML will be all gmetric XML
469                so there will be no specific start/end element
470                just one XML statement with all info
471                """
472               
473                jobinfo = { }
474
475                if name == 'CLUSTER':
476
477                        self.clustername = attrs.get( 'NAME', "" )
478
479                elif name == 'METRIC' and self.clustername in ARCHIVE_DATASOURCES:
480
481                        metricname = attrs.get( 'NAME', "" )
482
483                        if metricname == 'TOGA-HEARTBEAT':
484                                self.heartbeat = attrs.get( 'VAL', "" )
485
486                        elif metricname.find( 'TOGA-JOB' ) != -1:
487
488                                job_id = metricname.split( 'TOGA-JOB-' )[1]
489                                val = attrs.get( 'VAL', "" )
490
491                                if not job_id in self.jobs_processed:
492                                        self.jobs_processed.append( job_id )
493
494                                check_change = 0
495
496                                if self.jobAttrs.has_key( job_id ):
497                                        check_change = 1
498
499                                valinfo = val.split( ' ' )
500
501                                for myval in valinfo:
502
503                                        if len( myval.split( '=' ) ) > 1:
504
505                                                valname = myval.split( '=' )[0]
506                                                value = myval.split( '=' )[1]
507
508                                                if valname == 'nodes':
509                                                        value = value.split( ';' )
510
511                                                jobinfo[ valname ] = value
512
513                                if check_change:
514                                        if self.jobinfoChanged( self.jobAttrs, job_id, jobinfo ) and self.jobAttrs[ job_id ]['status'] in [ 'R', 'Q' ]:
515                                                self.jobAttrs[ job_id ]['stop_timestamp'] = ''
516                                                self.jobAttrs[ job_id ] = self.setJobAttrs( self.jobAttrs[ job_id ], jobinfo )
517                                                if not job_id in self.jobs_to_store:
518                                                        self.jobs_to_store.append( job_id )
519
520                                                debug_msg( 6, 'jobinfo for job %s has changed' %job_id )
521                                else:
522                                        self.jobAttrs[ job_id ] = jobinfo
523
524                                        if not job_id in self.jobs_to_store:
525                                                self.jobs_to_store.append( job_id )
526
527                                        debug_msg( 6, 'jobinfo for job %s has changed' %job_id )
528                                       
529        def endDocument( self ):
530                """When all metrics have gone, check if any jobs have finished"""
531
532                if self.heartbeat:
533                        for jobid, jobinfo in self.jobAttrs.items():
534
535                                # This is an old job, not in current jobinfo list anymore
536                                # it must have finished, since we _did_ get a new heartbeat
537                                #
538                                mytime = int( jobinfo['reported'] ) + int( jobinfo['poll_interval'] )
539
540                                if (mytime < self.heartbeat) and (jobid not in self.jobs_processed) and (jobinfo['status'] == 'R'):
541
542                                        if not jobid in self.jobs_processed:
543                                                self.jobs_processed.append( jobid )
544
545                                        self.jobAttrs[ jobid ]['status'] = 'F'
546                                        self.jobAttrs[ jobid ]['stop_timestamp'] = str( mytime )
547
548                                        if not jobid in self.jobs_to_store:
549                                                self.jobs_to_store.append( jobid )
550
551                        debug_msg( 1, 'torque_xml_thread(): Storing..' )
552
553                        for jobid in self.jobs_to_store:
554                                if self.jobAttrs[ jobid ]['status'] in [ 'R', 'Q', 'F' ]:
555
556                                        self.ds.storeJobInfo( jobid, self.jobAttrs[ jobid ] )
557
558                                        if self.jobAttrs[ jobid ]['status'] == 'F':
559                                                del self.jobAttrs[ jobid ]
560
561                        debug_msg( 1, 'torque_xml_thread(): Done storing.' )
562
563                        self.jobs_processed = [ ]
564                        self.jobs_to_store = [ ]
565
566        def setJobAttrs( self, old, new ):
567                """
568                Set new job attributes in old, but not lose existing fields
569                if old attributes doesn't have those
570                """
571
572                for valname, value in new.items():
573                        old[ valname ] = value
574
575                return old
576               
577
578        def jobinfoChanged( self, jobattrs, jobid, jobinfo ):
579                """
580                Check if jobinfo has changed from jobattrs[jobid]
581                if it's report time is bigger than previous one
582                and it is report time is recent (equal to heartbeat)
583                """
584
585                ignore_changes = [ 'reported' ]
586
587                if jobattrs.has_key( jobid ):
588
589                        for valname, value in jobinfo.items():
590
591                                if valname not in ignore_changes:
592
593                                        if jobattrs[ jobid ].has_key( valname ):
594
595                                                if value != jobattrs[ jobid ][ valname ]:
596
597                                                        if jobinfo['reported'] > jobattrs[ jobid ][ 'reported' ] and jobinfo['reported'] == self.heartbeat:
598                                                                return 1
599
600                                        else:
601                                                return 1
602
603                return 0
604
605class GangliaXMLHandler( xml.sax.handler.ContentHandler ):
606        """Parse Ganglia's XML"""
607
608        def __init__( self, config ):
609                """Setup initial variables and gather info on existing rrd archive"""
610
611                self.config = config
612                self.clusters = { }
613                debug_msg( 1, 'Checking existing toga rrd archive..' )
614                self.gatherClusters()
615                debug_msg( 1, 'Check done.' )
616
617        def gatherClusters( self ):
618                """Find all existing clusters in archive dir"""
619
620                archive_dir = check_dir(ARCHIVE_PATH)
621
622                hosts = [ ]
623
624                if os.path.exists( archive_dir ):
625
626                        dirlist = os.listdir( archive_dir )
627
628                        for item in dirlist:
629
630                                clustername = item
631
632                                if not self.clusters.has_key( clustername ) and clustername in ARCHIVE_DATASOURCES:
633
634                                        self.clusters[ clustername ] = RRDHandler( self.config, clustername )
635
636        def startElement( self, name, attrs ):
637                """Memorize appropriate data from xml start tags"""
638
639                if name == 'GANGLIA_XML':
640
641                        self.XMLSource = attrs.get( 'SOURCE', "" )
642                        self.gangliaVersion = attrs.get( 'VERSION', "" )
643
644                        debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
645
646                elif name == 'GRID':
647
648                        self.gridName = attrs.get( 'NAME', "" )
649                        self.time = attrs.get( 'LOCALTIME', "" )
650
651                        debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
652
653                elif name == 'CLUSTER':
654
655                        self.clusterName = attrs.get( 'NAME', "" )
656                        self.time = attrs.get( 'LOCALTIME', "" )
657
658                        if not self.clusters.has_key( self.clusterName ) and self.clusterName in ARCHIVE_DATASOURCES:
659
660                                self.clusters[ self.clusterName ] = RRDHandler( self.config, self.clusterName )
661
662                                debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
663
664                elif name == 'HOST' and self.clusterName in ARCHIVE_DATASOURCES:     
665
666                        self.hostName = attrs.get( 'NAME', "" )
667                        self.hostIp = attrs.get( 'IP', "" )
668                        self.hostReported = attrs.get( 'REPORTED', "" )
669
670                        debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
671
672                elif name == 'METRIC' and self.clusterName in ARCHIVE_DATASOURCES:
673
674                        type = attrs.get( 'TYPE', "" )
675                       
676                        exclude_metric = False
677                       
678                        for ex_metricstr in ARCHIVE_EXCLUDE_METRICS:
679
680                                orig_name = attrs.get( 'NAME', "" )     
681
682                                if string.lower( orig_name ) == string.lower( ex_metricstr ):
683                               
684                                        exclude_metric = True
685
686                                elif re.match( ex_metricstr, orig_name ):
687
688                                        exclude_metric = True
689
690                        if type not in UNSUPPORTED_ARCHIVE_TYPES and not exclude_metric:
691
692                                myMetric = { }
693                                myMetric['name'] = attrs.get( 'NAME', "" )
694                                myMetric['val'] = attrs.get( 'VAL', "" )
695                                myMetric['time'] = self.hostReported
696
697                                self.clusters[ self.clusterName ].memMetric( self.hostName, myMetric )
698
699                                debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
700
701        def storeMetrics( self ):
702                """Store metrics of each cluster rrd handler"""
703
704                for clustername, rrdh in self.clusters.items():
705
706                        ret = rrdh.storeMetrics()
707
708                        if ret:
709                                debug_msg( 9, 'An error occured while storing metrics for cluster %s' %clustername )
710                                return 1
711
712                return 0
713
714class XMLErrorHandler( xml.sax.handler.ErrorHandler ):
715
716        def error( self, exception ):
717                """Recoverable error"""
718
719                debug_msg( 0, 'Recoverable XML error ' + str( exception ) + ' ignored.' )
720
721        def fatalError( self, exception ):
722                """Non-recoverable error"""
723
724                exception_str = str( exception )
725
726                # Ignore 'no element found' errors
727                if exception_str.find( 'no element found' ) != -1:
728                        debug_msg( 0, 'No XML data found: Socket not (re)connected or datasource not available.' )
729                        return 0
730
731                debug_msg( 0, 'FATAL ERROR: Non-recoverable XML error ' + str( exception ) )
732                sys.exit( 1 )
733
734        def warning( self, exception ):
735                """Warning"""
736
737                debug_msg( 0, 'Warning ' + str( exception ) )
738
739class XMLGatherer:
740        """Setup a connection and file object to Ganglia's XML"""
741
742        s = None
743        fd = None
744
745        def __init__( self, host, port ):
746                """Store host and port for connection"""
747
748                self.host = host
749                self.port = port
750                self.connect()
751                self.makeFileDescriptor()
752
753        def connect( self ):
754                """Setup connection to XML source"""
755
756                for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ):
757
758                        af, socktype, proto, canonname, sa = res
759
760                        try:
761
762                                self.s = socket.socket( af, socktype, proto )
763
764                        except socket.error, msg:
765
766                                self.s = None
767                                continue
768
769                        try:
770
771                                self.s.connect( sa )
772
773                        except socket.error, msg:
774
775                                self.disconnect()
776                                continue
777
778                        break
779
780                if self.s is None:
781
782                        debug_msg( 0, 'FATAL ERROR: Could not open socket or unable to connect to datasource!' )
783                        sys.exit( 1 )
784
785        def disconnect( self ):
786                """Close socket"""
787
788                if self.s:
789                        self.s.shutdown( 2 )
790                        self.s.close()
791                        self.s = None
792
793        def __del__( self ):
794                """Kill the socket before we leave"""
795
796                self.disconnect()
797
798        def reconnect( self ):
799                """Reconnect"""
800
801                if self.s:
802                        self.disconnect()
803
804                self.connect()
805
806        def makeFileDescriptor( self ):
807                """Make file descriptor that points to our socket connection"""
808
809                self.reconnect()
810
811                if self.s:
812                        self.fd = self.s.makefile( 'r' )
813
814        def getFileObject( self ):
815                """Connect, and return a file object"""
816
817                self.makeFileDescriptor()
818
819                if self.fd:
820                        return self.fd
821
822class GangliaXMLProcessor( XMLProcessor ):
823        """Main class for processing XML and acting with it"""
824
825        def __init__( self ):
826                """Setup initial XML connection and handlers"""
827
828                self.config = GangliaConfigParser( GMETAD_CONF )
829
830                self.myXMLGatherer = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] ) 
831                self.myXMLSource = self.myXMLGatherer.getFileObject()
832                self.myXMLHandler = GangliaXMLHandler( self.config )
833                self.myXMLError = XMLErrorHandler()
834
835        def run( self ):
836                """Main XML processing; start a xml and storethread"""
837
838                xml_thread = threading.Thread( None, self.processXML, 'xmlthread' )
839                store_thread = threading.Thread( None, self.storeMetrics, 'storethread' )
840
841                while( 1 ):
842
843                        if not xml_thread.isAlive():
844                                # Gather XML at the same interval as gmetad
845
846                                # threaded call to: self.processXML()
847                                #
848                                try:
849                                        xml_thread = threading.Thread( None, self.processXML, 'xml_thread' )
850                                        xml_thread.start()
851                                except thread.error, msg:
852                                        debug_msg( 0, 'ERROR: Unable to start xml_thread!: '+str(msg))
853                                        #return 1
854
855                        if not store_thread.isAlive():
856                                # Store metrics every .. sec
857
858                                # threaded call to: self.storeMetrics()
859                                #
860                                try:
861                                        store_thread = threading.Thread( None, self.storeMetrics, 'store_thread' )
862                                        store_thread.start()
863                                except thread.error, msg:
864                                        debug_msg( 0, 'ERROR: Unable to start store_thread!: '+str(msg))
865                                        #return 1
866               
867                        # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway
868                        time.sleep( 1 ) 
869
870        def storeMetrics( self ):
871                """Store metrics retained in memory to disk"""
872
873                # Store metrics somewhere between every 360 and 640 seconds
874                #
875                STORE_INTERVAL = random.randint( 360, 640 )
876
877                try:
878                        store_metric_thread = threading.Thread( None, self.storeThread, 'store_metric_thread' )
879                        store_metric_thread.start()
880                except thread.error, msg:
881                        debug_msg( 0, 'ERROR: Unable to start ganglia_store_thread()!: '+str(msg) )
882                        return 1
883
884                debug_msg( 1, 'ganglia_store_thread(): started.' )
885
886                debug_msg( 1, 'ganglia_store_thread(): Sleeping.. (%ss)' %STORE_INTERVAL )
887                time.sleep( STORE_INTERVAL )
888                debug_msg( 1, 'ganglia_store_thread(): Done sleeping.' )
889
890                if store_metric_thread.isAlive():
891
892                        debug_msg( 1, 'ganglia_store_thread(): storemetricthread() still running, waiting to finish..' )
893                        store_metric_thread.join( STORE_TIMEOUT ) # Maximum time is for storing thread to finish
894                        debug_msg( 1, 'ganglia_store_thread(): Done waiting.' )
895
896                debug_msg( 1, 'ganglia_store_thread(): finished.' )
897
898                return 0
899
900        def storeThread( self ):
901                """Actual metric storing thread"""
902
903                debug_msg( 1, 'ganglia_store_metric_thread(): started.' )
904                debug_msg( 1, 'ganglia_store_metric_thread(): Storing data..' )
905                ret = self.myXMLHandler.storeMetrics()
906                if ret > 0:
907                        debug_msg( 0, 'ganglia_store_metric_thread(): UNKNOWN ERROR %s while storing Metrics!' %str(ret) )
908                debug_msg( 1, 'ganglia_store_metric_thread(): Done storing.' )
909                debug_msg( 1, 'ganglia_store_metric_thread(): finished.' )
910               
911                return 0
912
913        def processXML( self ):
914                """Process XML"""
915
916                try:
917                        parsethread = threading.Thread( None, self.parseThread, 'parsethread' )
918                        parsethread.start()
919                except thread.error, msg:
920                        debug_msg( 0, 'ERROR: Unable to start ganglia_xml_thread()!: ' + str(msg) )
921                        return 1
922
923                debug_msg( 1, 'ganglia_xml_thread(): started.' )
924
925                debug_msg( 1, 'ganglia_xml_thread(): Sleeping.. (%ss)' %self.config.getLowestInterval() )
926                time.sleep( float( self.config.getLowestInterval() ) ) 
927                debug_msg( 1, 'ganglia_xml_thread(): Done sleeping.' )
928
929                if parsethread.isAlive():
930
931                        debug_msg( 1, 'ganglia_xml_thread(): parsethread() still running, waiting (%ss) to finish..' %PARSE_TIMEOUT )
932                        parsethread.join( PARSE_TIMEOUT ) # Maximum time for XML thread to finish
933                        debug_msg( 1, 'ganglia_xml_thread(): Done waiting.' )
934
935                debug_msg( 1, 'ganglia_xml_thread(): finished.' )
936
937                return 0
938
939        def parseThread( self ):
940                """Actual parsing thread"""
941
942                debug_msg( 1, 'ganglia_parse_thread(): started.' )
943                debug_msg( 1, 'ganglia_parse_thread(): Parsing XML..' )
944                self.myXMLSource = self.myXMLGatherer.getFileObject()
945
946                try:
947                        xml.sax.parse( self.myXMLSource, self.myXMLHandler, self.myXMLError )
948                except socket.error, msg:
949                        debug_msg( 0, 'ERROR: Socket error in connect to datasource!: %s' %msg )
950
951                debug_msg( 1, 'ganglia_parse_thread(): Done parsing.' )
952                debug_msg( 1, 'ganglia_parse_thread(): finished.' )
953
954                return 0
955
956class GangliaConfigParser:
957
958        sources = [ ]
959
960        def __init__( self, config ):
961                """Parse some stuff from our gmetad's config, such as polling interval"""
962
963                self.config = config
964                self.parseValues()
965
966        def parseValues( self ):
967                """Parse certain values from gmetad.conf"""
968
969                readcfg = open( self.config, 'r' )
970
971                for line in readcfg.readlines():
972
973                        if line.count( '"' ) > 1:
974
975                                if line.find( 'data_source' ) != -1 and line[0] != '#':
976
977                                        source = { }
978                                        source['name'] = line.split( '"' )[1]
979                                        source_words = line.split( '"' )[2].split( ' ' )
980
981                                        for word in source_words:
982
983                                                valid_interval = 1
984
985                                                for letter in word:
986
987                                                        if letter not in string.digits:
988
989                                                                valid_interval = 0
990
991                                                if valid_interval and len(word) > 0:
992
993                                                        source['interval'] = word
994                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
995       
996                                        # No interval found, use Ganglia's default     
997                                        if not source.has_key( 'interval' ):
998                                                source['interval'] = 15
999                                                debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
1000
1001                                        self.sources.append( source )
1002
1003        def getInterval( self, source_name ):
1004                """Return interval for source_name"""
1005
1006                for source in self.sources:
1007
1008                        if source['name'] == source_name:
1009
1010                                return source['interval']
1011
1012                return None
1013
1014        def getLowestInterval( self ):
1015                """Return the lowest interval of all clusters"""
1016
1017                lowest_interval = 0
1018
1019                for source in self.sources:
1020
1021                        if not lowest_interval or source['interval'] <= lowest_interval:
1022
1023                                lowest_interval = source['interval']
1024
1025                # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays
1026                if lowest_interval:
1027                        return lowest_interval
1028                else:
1029                        return 15
1030
1031class RRDHandler:
1032        """Class for handling RRD activity"""
1033
1034        myMetrics = { }
1035        lastStored = { }
1036        timeserials = { }
1037        slot = None
1038
1039        def __init__( self, config, cluster ):
1040                """Setup initial variables"""
1041
1042                self.block = 0
1043                self.cluster = cluster
1044                self.config = config
1045                self.slot = threading.Lock()
1046                self.rrdm = RRDMutator()
1047                self.gatherLastUpdates()
1048
1049        def gatherLastUpdates( self ):
1050                """Populate the lastStored list, containing timestamps of all last updates"""
1051
1052                cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster )
1053
1054                hosts = [ ]
1055
1056                if os.path.exists( cluster_dir ):
1057
1058                        dirlist = os.listdir( cluster_dir )
1059
1060                        for dir in dirlist:
1061
1062                                hosts.append( dir )
1063
1064                for host in hosts:
1065
1066                        host_dir = cluster_dir + '/' + host
1067                        dirlist = os.listdir( host_dir )
1068
1069                        for dir in dirlist:
1070
1071                                if not self.timeserials.has_key( host ):
1072
1073                                        self.timeserials[ host ] = [ ]
1074
1075                                self.timeserials[ host ].append( dir )
1076
1077                        last_serial = self.getLastRrdTimeSerial( host )
1078                        if last_serial:
1079
1080                                metric_dir = cluster_dir + '/' + host + '/' + last_serial
1081                                if os.path.exists( metric_dir ):
1082
1083                                        dirlist = os.listdir( metric_dir )
1084
1085                                        for file in dirlist:
1086
1087                                                metricname = file.split( '.rrd' )[0]
1088
1089                                                if not self.lastStored.has_key( host ):
1090
1091                                                        self.lastStored[ host ] = { }
1092
1093                                                self.lastStored[ host ][ metricname ] = self.rrdm.grabLastUpdate( metric_dir + '/' + file )
1094
1095        def getClusterName( self ):
1096                """Return clustername"""
1097
1098                return self.cluster
1099
1100        def memMetric( self, host, metric ):
1101                """Store metric from host in memory"""
1102
1103                # <ATOMIC>
1104                #
1105                self.slot.acquire()
1106               
1107                if self.myMetrics.has_key( host ):
1108
1109                        if self.myMetrics[ host ].has_key( metric['name'] ):
1110
1111                                for mymetric in self.myMetrics[ host ][ metric['name'] ]:
1112
1113                                        if mymetric['time'] == metric['time']:
1114
1115                                                # Allready have this metric, abort
1116                                                self.slot.release()
1117                                                return 1
1118                        else:
1119                                self.myMetrics[ host ][ metric['name'] ] = [ ]
1120                else:
1121                        self.myMetrics[ host ] = { }
1122                        self.myMetrics[ host ][ metric['name'] ] = [ ]
1123
1124                # Push new metric onto stack
1125                # atomic code; only 1 thread at a time may access the stack
1126
1127                self.myMetrics[ host ][ metric['name'] ].append( metric )
1128
1129                self.slot.release()
1130                #
1131                # </ATOMIC>
1132
1133        def makeUpdateList( self, host, metriclist ):
1134                """
1135                Make a list of update values for rrdupdate
1136                but only those that we didn't store before
1137                """
1138
1139                update_list = [ ]
1140                metric = None
1141
1142                while len( metriclist ) > 0:
1143
1144                        metric = metriclist.pop( 0 )
1145
1146                        if self.checkStoreMetric( host, metric ):
1147                                update_list.append( '%s:%s' %( metric['time'], metric['val'] ) )
1148
1149                return update_list
1150
1151        def checkStoreMetric( self, host, metric ):
1152                """Check if supplied metric if newer than last one stored"""
1153
1154                if self.lastStored.has_key( host ):
1155
1156                        if self.lastStored[ host ].has_key( metric['name'] ):
1157
1158                                if metric['time'] <= self.lastStored[ host ][ metric['name'] ]:
1159
1160                                        # This is old
1161                                        return 0
1162
1163                return 1
1164
1165        def memLastUpdate( self, host, metricname, metriclist ):
1166                """
1167                Memorize the time of the latest metric from metriclist
1168                but only if it wasn't allready memorized
1169                """
1170
1171                if not self.lastStored.has_key( host ):
1172                        self.lastStored[ host ] = { }
1173
1174                last_update_time = 0
1175
1176                for metric in metriclist:
1177
1178                        if metric['name'] == metricname:
1179
1180                                if metric['time'] > last_update_time:
1181
1182                                        last_update_time = metric['time']
1183
1184                if self.lastStored[ host ].has_key( metricname ):
1185                       
1186                        if last_update_time <= self.lastStored[ host ][ metricname ]:
1187                                return 1
1188
1189                self.lastStored[ host ][ metricname ] = last_update_time
1190
1191        def storeMetrics( self ):
1192                """
1193                Store all metrics from memory to disk
1194                and do it to the RRD's in appropriate timeperiod directory
1195                """
1196
1197                for hostname, mymetrics in self.myMetrics.items():     
1198
1199                        for metricname, mymetric in mymetrics.items():
1200
1201                                metrics_to_store = [ ]
1202
1203                                # Pop metrics from stack for storing until none is left
1204                                # atomic code: only 1 thread at a time may access myMetrics
1205
1206                                # <ATOMIC>
1207                                #
1208                                self.slot.acquire() 
1209
1210                                while len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1211
1212                                        if len( self.myMetrics[ hostname ][ metricname ] ) > 0:
1213
1214                                                try:
1215                                                        metrics_to_store.append( self.myMetrics[ hostname ][ metricname ].pop( 0 ) )
1216                                                except IndexError, msg:
1217
1218                                                        # Somehow sometimes myMetrics[ hostname ][ metricname ]
1219                                                        # is still len 0 when the statement is executed.
1220                                                        # Just ignore indexerror's..
1221                                                        pass
1222
1223                                self.slot.release()
1224                                #
1225                                # </ATOMIC>
1226
1227                                # Create a mapping table, each metric to the period where it should be stored
1228                                #
1229                                metric_serial_table = self.determineSerials( hostname, metricname, metrics_to_store )
1230
1231                                update_rets = [ ]
1232
1233                                for period, pmetric in metric_serial_table.items():
1234
1235                                        create_ret = self.createCheck( hostname, metricname, period )   
1236
1237                                        update_ret = self.update( hostname, metricname, period, pmetric )
1238
1239                                        if update_ret == 0:
1240
1241                                                debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) )
1242                                        else:
1243                                                debug_msg( 9, 'metric update failed' )
1244
1245                                        update_rets.append( create_ret )
1246                                        update_rets.append( update_ret )
1247
1248                                # Lets ignore errors here for now, we need to make sure last update time
1249                                # is correct!
1250                                #
1251                                #if not (1) in update_rets:
1252
1253                                self.memLastUpdate( hostname, metricname, metrics_to_store )
1254
1255        def makeTimeSerial( self ):
1256                """Generate a time serial. Seconds since epoch"""
1257
1258                # Seconds since epoch
1259                mytime = int( time.time() )
1260
1261                return mytime
1262
1263        def makeRrdPath( self, host, metricname, timeserial ):
1264                """Make a RRD location/path and filename"""
1265
1266                rrd_dir = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial )
1267                rrd_file = '%s/%s.rrd' %( rrd_dir, metricname )
1268
1269                return rrd_dir, rrd_file
1270
1271        def getLastRrdTimeSerial( self, host ):
1272                """Find the last timeserial (directory) for this host"""
1273
1274                newest_timeserial = 0
1275
1276                for dir in self.timeserials[ host ]:
1277
1278                        valid_dir = 1
1279
1280                        for letter in dir:
1281                                if letter not in string.digits:
1282                                        valid_dir = 0
1283
1284                        if valid_dir:
1285                                timeserial = dir
1286                                if timeserial > newest_timeserial:
1287                                        newest_timeserial = timeserial
1288
1289                if newest_timeserial:
1290                        return newest_timeserial
1291                else:
1292                        return 0
1293
1294        def determinePeriod( self, host, check_serial ):
1295                """Determine to which period (directory) this time(serial) belongs"""
1296
1297                period_serial = 0
1298
1299                if self.timeserials.has_key( host ):
1300
1301                        for serial in self.timeserials[ host ]:
1302
1303                                if check_serial >= serial and period_serial < serial:
1304
1305                                        period_serial = serial
1306
1307                return period_serial
1308
1309        def determineSerials( self, host, metricname, metriclist ):
1310                """
1311                Determine the correct serial and corresponding rrd to store
1312                for a list of metrics
1313                """
1314
1315                metric_serial_table = { }
1316
1317                for metric in metriclist:
1318
1319                        if metric['name'] == metricname:
1320
1321                                period = self.determinePeriod( host, metric['time'] )   
1322
1323                                archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60)
1324
1325                                if (int( metric['time'] ) - int( period ) ) > archive_secs:
1326
1327                                        # This one should get it's own new period
1328                                        period = metric['time']
1329
1330                                        if not self.timeserials.has_key( host ):
1331                                                self.timeserials[ host ] = [ ]
1332
1333                                        self.timeserials[ host ].append( period )
1334
1335                                if not metric_serial_table.has_key( period ):
1336
1337                                        metric_serial_table[ period ] = [ ]
1338
1339                                metric_serial_table[ period ].append( metric )
1340
1341                return metric_serial_table
1342
1343        def createCheck( self, host, metricname, timeserial ):
1344                """Check if an rrd allready exists for this metric, create if not"""
1345
1346                debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1347               
1348                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
1349
1350                if not os.path.exists( rrd_dir ):
1351
1352                        try:
1353                                os.makedirs( rrd_dir )
1354
1355                        except os.OSError, msg:
1356
1357                                if msg.find( 'File exists' ) != -1:
1358
1359                                        # Ignore exists errors
1360                                        pass
1361
1362                                else:
1363
1364                                        print msg
1365                                        return
1366
1367                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
1368
1369                if not os.path.exists( rrd_file ):
1370
1371                        interval = self.config.getInterval( self.cluster )
1372                        heartbeat = 8 * int( interval )
1373
1374                        params = [ ]
1375
1376                        params.append( '--step' )
1377                        params.append( str( interval ) )
1378
1379                        params.append( '--start' )
1380                        params.append( str( int( timeserial ) - 1 ) )
1381
1382                        params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat )
1383                        params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) )
1384
1385                        self.rrdm.create( str(rrd_file), params )
1386
1387                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
1388
1389        def update( self, host, metricname, timeserial, metriclist ):
1390                """
1391                Update rrd file for host with metricname
1392                in directory timeserial with metriclist
1393                """
1394
1395                debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) )
1396
1397                rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial )
1398
1399                update_list = self.makeUpdateList( host, metriclist )
1400
1401                if len( update_list ) > 0:
1402                        ret = self.rrdm.update( str(rrd_file), update_list )
1403
1404                        if ret:
1405                                return 1
1406               
1407                        debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) )
1408
1409                return 0
1410
1411def daemon():
1412        """daemonized threading"""
1413
1414        # Fork the first child
1415        #
1416        pid = os.fork()
1417
1418        if pid > 0:
1419
1420                sys.exit(0)  # end parent
1421
1422        # creates a session and sets the process group ID
1423        #
1424        os.setsid()
1425
1426        # Fork the second child
1427        #
1428        pid = os.fork()
1429
1430        if pid > 0:
1431
1432                sys.exit(0)  # end parent
1433
1434        # Go to the root directory and set the umask
1435        #
1436        os.chdir('/')
1437        os.umask(0)
1438
1439        sys.stdin.close()
1440        sys.stdout.close()
1441        sys.stderr.close()
1442
1443        os.open('/dev/null', 0)
1444        os.dup(0)
1445        os.dup(0)
1446
1447        run()
1448
1449def run():
1450        """Threading start"""
1451
1452        myTorqueProcessor = TorqueXMLProcessor()
1453        myGangliaProcessor = GangliaXMLProcessor()
1454
1455        try:
1456                torque_xml_thread = threading.Thread( None, myTorqueProcessor.run, 'torque_proc_thread' )
1457                ganglia_xml_thread = threading.Thread( None, myGangliaProcessor.run, 'ganglia_proc_thread' )
1458
1459                torque_xml_thread.start()
1460                ganglia_xml_thread.start()
1461               
1462        except thread.error, msg:
1463                debug_msg( 0, 'FATAL ERROR: Unable to start main threads!: '+ str(msg) )
1464                syslog.closelog()
1465                sys.exit(1)
1466               
1467        debug_msg( 0, 'main threading started.' )
1468
1469def main():
1470        """Program startup"""
1471
1472        if not processArgs( sys.argv[1:] ):
1473                sys.exit( 1 )
1474
1475        if( DAEMONIZE and USE_SYSLOG ):
1476                syslog.openlog( 'jobarchived', syslog.LOG_NOWAIT, SYSLOG_FACILITY )
1477
1478        if DAEMONIZE:
1479                daemon()
1480        else:
1481                run()
1482
1483#
1484# Global functions
1485#
1486
1487def check_dir( directory ):
1488        """Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"""
1489
1490        if directory[-1] == '/':
1491                directory = directory[:-1]
1492
1493        return directory
1494
1495def debug_msg( level, msg ):
1496        """Only print msg if correct levels"""
1497
1498        if (not DAEMONIZE and DEBUG_LEVEL >= level):
1499                sys.stderr.write( printTime() + ' - ' + msg + '\n' )
1500       
1501        if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level):
1502                syslog.syslog( msg )
1503
1504def printTime( ):
1505        """Print current time in human readable format"""
1506
1507        return time.strftime("%a %d %b %Y %H:%M:%S")
1508
1509# Ooohh, someone started me! Let's go..
1510if __name__ == '__main__':
1511        main()
Note: See TracBrowser for help on using the repository browser.