source: trunk/daemon/togad.py @ 17

Last change on this file since 17 was 17, checked in by bastiaans, 19 years ago

daemon/togad.py:

  • RRD's will now be timestamped, like this: disk_free$1111574193.rrd
  • If last timestamp'ed RRD has expired ARCHIVE_HOURS a new one will be created
File size: 9.1 KB
Line 
1#!/usr/bin/env python
2
3from xml.sax import make_parser
4from xml.sax.handler import ContentHandler
5import socket
6import sys
7import rrdtool
8import string
9import os
10import os.path
11import time
12import re
13
14# Specify debugging level here;
15#
16# >10 = metric XML
17# >9  = host,cluster,grid,ganglia XML
18# >8  = RRD activity,gmetad config parsing
19#
20DEBUG_LEVEL = 8
21
22# Where is the gmetad.conf located
23#
24GMETAD_CONF = '/etc/gmetad.conf'
25
26# Where to store the archived rrd's
27#
28ARCHIVE_PATH = '/data/toga/rrds'
29
30# List of data_source names to archive for
31#
32ARCHIVE_SOURCES = [ "LISA Cluster" ]
33
34# Amount of hours to store in one single archived .rrd
35#
36ARCHIVE_HOURS_PER_RRD = 24
37
38######################
39#                    #
40# Configuration ends #
41#                    #
42######################
43
44# What XML data types not to store
45#
46UNSUPPORTED_ARCHIVE_TYPES = [ 'string' ]
47
48"""
49This is TOrque-GAnglia's data Daemon
50"""
51
52class GangliaXMLHandler( ContentHandler ):
53        "Parse Ganglia's XML"
54
55        metrics = [ ]
56
57        def startElement( self, name, attrs ):
58                "Store appropriate data from xml start tags"
59
60                if name == 'GANGLIA_XML':
61                        self.XMLSource = attrs.get('SOURCE',"")
62                        self.gangliaVersion = attrs.get('VERSION',"")
63                        debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) )
64
65                elif name == 'GRID':
66                        self.gridName = attrs.get('NAME',"")
67                        self.time = attrs.get('LOCALTIME',"")
68                        debug_msg( 10, '`-Grid found: %s' %( self.gridName ) )
69
70                elif name == 'CLUSTER':
71                        self.clusterName = attrs.get('NAME',"")
72                        self.time = attrs.get('LOCALTIME',"")
73                        self.rrd = RRDHandler( self.clusterName )
74                        debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) )
75
76                elif name == 'HOST' and self.clusterName in ARCHIVE_SOURCES:     
77                        self.hostName = attrs.get('NAME',"")
78                        self.hostIp = attrs.get('IP',"")
79                        self.hostReported = attrs.get('REPORTED',"")
80                        # Reset the metrics list for each host
81                        self.metrics = [ ]
82                        debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) )
83
84                elif name == 'METRIC' and self.clusterName in ARCHIVE_SOURCES:
85                        myMetric = { }
86                        myMetric['name'] = attrs.get('NAME',"")
87                        myMetric['val'] = attrs.get('VAL',"")
88                        myMetric['time'] = self.time
89                        myMetric['type'] = attrs.get('TYPE',"")
90
91                        self.metrics.append( myMetric ) 
92                        debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) )
93
94                return
95
96        def endElement( self, name ):
97                #if name == 'GANGLIA_XML':
98
99                #if name == 'GRID':
100
101                #if name == 'CLUSTER':
102
103                if name == 'HOST' and self.clusterName in ARCHIVE_SOURCES:     
104                        self.storeMetrics( self.hostName )
105
106                #if name == 'METRIC':
107
108        def storeMetrics( self, hostname ):
109
110                for metric in self.metrics:
111                        if metric['type'] not in UNSUPPORTED_ARCHIVE_TYPES:
112
113                                self.rrd.createCheck( hostname, metric )       
114                                self.rrd.update( hostname, metric )
115                                debug_msg( 9, 'stored metric %s for %s: %s' %( hostname, metric['name'], metric['val'] ) )
116                                sys.exit(1)
117       
118
119class GangliaXMLGatherer:
120        "Setup a connection and file object to Ganglia's XML"
121
122        s = None
123
124        def __init__( self, host, port ):
125                "Store host and port for connection"
126
127                self.host = host
128                self.port = port
129
130        def __del__( self ):
131                "Kill the socket before we leave"
132
133                self.s.close()
134
135        def getFileObject( self ):
136                "Connect, and return a file object"
137
138                for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ):
139                        af, socktype, proto, canonname, sa = res
140                        try:
141                                self.s = socket.socket( af, socktype, proto )
142                        except socket.error, msg:
143                                self.s = None
144                                continue
145                        try:
146                                self.s.connect( sa )
147                        except socket.error, msg:
148                                self.s.close()
149                                self.s = None
150                                continue
151                        break
152
153                if self.s is None:
154                        print 'Could not open socket'
155                        sys.exit(1)
156
157                return self.s.makefile( 'r' )
158
159class GangliaXMLProcessor:
160
161        def daemon( self ):
162                "Run as daemon forever"
163
164                self.DAEMON = 1
165
166                # Fork the first child
167                #
168                pid = os.fork()
169                if pid > 0:
170                        sys.exit(0)  # end parrent
171
172                # creates a session and sets the process group ID
173                #
174                os.setsid()
175
176                # Fork the second child
177                #
178                pid = os.fork()
179                if pid > 0:
180                        sys.exit(0)  # end parrent
181
182                # Go to the root directory and set the umask
183                #
184                os.chdir('/')
185                os.umask(0)
186
187                sys.stdin.close()
188                sys.stdout.close()
189                if (DEBUGLEVEL == 0):
190                        sys.stderr.close()
191
192                os.open('/dev/null', 0)
193                os.dup(0)
194                os.dup(0)
195
196                self.run()
197
198        def run( self ):
199                "Main thread"
200
201                while ( 1 ):
202                        self.processXML()
203                        time.sleep( 5 )
204
205        def processXML( self ):
206                "Process XML"
207
208                myXMLGatherer = GangliaXMLGatherer( 'localhost', 8651 ) 
209
210                myParser = make_parser()   
211                myHandler = GangliaXMLHandler()
212                myParser.setContentHandler( myHandler )
213
214                myParser.parse( myXMLGatherer.getFileObject() )
215
216class GangliaConfigParser:
217
218        sources = [ ]
219
220        def __init__( self, config ):
221                self.config = config
222                self.parseValues()
223
224        def parseValues(self):
225                "Parse certain values from gmetad.conf"
226
227                readcfg = open( self.config, 'r' )
228
229                for line in readcfg.readlines():
230
231                        if line.count( '"' ) > 1:
232
233                                if line.find( 'data_source' ) != -1 and line[0] != '#':
234
235                                        source = { }
236                                        source['name'] = line.split( '"' )[1]
237                                        source_words = line.split( '"' )[2].split( ' ' )
238
239                                        for word in source_words:
240
241                                                valid_interval = 1
242
243                                                for letter in word:
244                                                        if letter not in string.digits:
245                                                                valid_interval = 0
246
247                                                if valid_interval and len(word) > 0:
248                                                        source['interval'] = word
249                                                        debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) )
250               
251                # No interval found, use Ganglia's default     
252                if not source.has_key( 'interval' ):
253                        source['interval'] = 15
254                        debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) )
255
256                self.sources.append( source )
257
258        def getInterval( self, source_name ):
259                for source in self.sources:
260                        if source['name'] == source_name:
261                                return source['interval']
262                return None
263
264class RRDHandler:
265
266        def __init__( self, cluster ):
267                self.cluster = cluster
268
269                self.gmetad_conf = GangliaConfigParser( GMETAD_CONF )
270
271        def makeTimeSerial( self ):
272
273                # YYYYMMDDhhmmss: 20050321143411
274                #mytime = time.strftime( "%Y%m%d%H%M%S" )
275
276                # Seconds since epoch
277                mytime = int( time.time() )
278
279                return mytime
280
281        def makeRrdPath( self, host, metric, timeserial='notime' ):
282
283                rrd_dir = '%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host )
284                rrd_file = '%s/%s$%s.rrd' %( rrd_dir, metric['name'], timeserial )
285
286                return rrd_dir, rrd_file
287
288        def getLastRrdTimeSerial( self, host, metric ):
289
290                rrd_dir, rrd_file = self.makeRrdPath( host, metric )
291
292                if os.path.exists( rrd_dir ):
293                        for root, dirs, files in os.walk( rrd_dir ):
294
295                                newest_timeserial = 0
296
297                                for file in files:
298
299                                        myre = re.match( '(\S+)\$(\d+).rrd', file )
300
301                                        if not myre:
302                                                continue
303
304                                        mymetric = myre.group(1)
305
306                                        if mymetric == metric['name']:
307
308                                                timeserial = myre.group(2)
309                                                if timeserial > newest_timeserial:
310                                                        newest_timeserial = timeserial
311
312                if newest_timeserial:
313                        return timeserial
314                else:
315                        return 0
316
317        def checkNewRrdPeriod( self, host, metric ):
318
319                cur_timeserial = int( self.makeTimeSerial() )
320                last_timeserial = int( self.getLastRrdTimeSerial( host, metric ) )
321
322                if not last_timeserial:
323                        return 0, 0
324
325                archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60)
326
327                if (cur_timeserial - last_timeserial) >= archive_secs:
328                        return 1, last_timeserial
329                else:
330                        return 0, last_timeserial
331
332        def createCheck( self, host, metric ):
333                "Check if an .rrd allready exists for this metric, create if not"
334
335                need_new, last_timeserial = self.checkNewRrdPeriod( host, metric )
336
337                if need_new or not last_timeserial:
338                        timeserial = self.makeTimeSerial()
339                else:
340                        timeserial = last_timeserial
341
342                rrd_dir, rrd_file = self.makeRrdPath( host, metric, timeserial )
343
344                if not os.path.exists( rrd_dir ):
345                        os.makedirs( rrd_dir )
346                        debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) )
347
348                if not os.path.exists( rrd_file ):
349
350                        interval = self.gmetad_conf.getInterval( self.cluster )
351                        heartbeat = 8 * int(interval)
352
353                        param_step1 = '--step'
354                        param_step2 = str( interval )
355
356                        param_start1 = '--start'
357                        param_start2 = str( int( metric['time'] ) - 1 )
358
359                        param_ds = 'DS:sum:GAUGE:%d:U:U' %heartbeat
360                        param_rra = 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240)
361
362                        rrdtool.create( str(rrd_file), param_step1, param_step2, param_start1, param_start2, param_ds, param_rra )
363
364                        debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) )
365
366        def update( self, host, metric ):
367
368                rrd_dir = '%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host )
369                rrd_file = '%s/%s.rrd' %( rrd_dir, metric['name'] )
370
371                timestamp = metric['time']
372                val = metric['val']
373
374                update_string = '%s:%s' %(timestamp, val)
375
376                rrdtool.update( str(rrd_file), str(update_string) )
377                debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), update_string ) )
378
379def main():
380        "Program startup"
381
382        myProcessor = GangliaXMLProcessor()
383        myProcessor.processXML()
384
385def check_dir( directory ):
386        "Check if directory is a proper directory. I.e.: Does _not_ end with a '/'"
387
388        if directory[-1] == '/':
389                directory = directory[:-1]
390
391        return directory
392
393def debug_msg( level, msg ):
394
395        if (DEBUG_LEVEL >= level):
396                sys.stderr.write( msg + '\n' )
397
398# Let's go
399if __name__ == '__main__':
400        main()
Note: See TracBrowser for help on using the repository browser.