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