1 | #!/usr/bin/env python |
---|
2 | |
---|
3 | import xml.sax |
---|
4 | import xml.sax.handler |
---|
5 | import socket |
---|
6 | import sys |
---|
7 | import string |
---|
8 | import os |
---|
9 | import os.path |
---|
10 | import time |
---|
11 | import threading |
---|
12 | import random |
---|
13 | from types import * |
---|
14 | import DBClass |
---|
15 | |
---|
16 | # Specify debugging level here; |
---|
17 | # |
---|
18 | # 11 = XML: metrics |
---|
19 | # 10 = XML: host, cluster, grid, ganglia |
---|
20 | # 9 = RRD activity, gmetad config parsing |
---|
21 | # 8 = RRD file activity |
---|
22 | # 7 = daemon threading |
---|
23 | # |
---|
24 | DEBUG_LEVEL = 7 |
---|
25 | |
---|
26 | # Where is the gmetad.conf located |
---|
27 | # |
---|
28 | GMETAD_CONF = '/etc/gmetad.conf' |
---|
29 | |
---|
30 | # Where to grab XML data from |
---|
31 | # Normally: local gmetad (port 8651) |
---|
32 | # |
---|
33 | # Syntax: <hostname>:<port> |
---|
34 | # |
---|
35 | ARCHIVE_XMLSOURCE = "localhost:8651" |
---|
36 | |
---|
37 | # List of data_source names to archive for |
---|
38 | # |
---|
39 | # Syntax: [ "<clustername>", "<clustername>" ] |
---|
40 | # |
---|
41 | ARCHIVE_DATASOURCES = [ "LISA Cluster" ] |
---|
42 | |
---|
43 | # Where to store the archived rrd's |
---|
44 | # |
---|
45 | ARCHIVE_PATH = '/data/toga/rrds' |
---|
46 | |
---|
47 | # Amount of hours to store in one single archived .rrd |
---|
48 | # |
---|
49 | ARCHIVE_HOURS_PER_RRD = 12 |
---|
50 | |
---|
51 | # Toga's SQL dbase to use |
---|
52 | # |
---|
53 | # Syntax: <hostname>/<database> |
---|
54 | # |
---|
55 | TOGA_SQL_DBASE = "localhost/toga" |
---|
56 | |
---|
57 | # Wether or not to run as a daemon in background |
---|
58 | # |
---|
59 | DAEMONIZE = 0 |
---|
60 | |
---|
61 | ###################### |
---|
62 | # # |
---|
63 | # Configuration ends # |
---|
64 | # # |
---|
65 | ###################### |
---|
66 | |
---|
67 | ### |
---|
68 | # You'll only want to change anything below here unless you |
---|
69 | # know what you are doing (i.e. your name is Ramon Bastiaans :D ) |
---|
70 | ### |
---|
71 | |
---|
72 | # What XML data types not to store |
---|
73 | # |
---|
74 | UNSUPPORTED_ARCHIVE_TYPES = [ 'string' ] |
---|
75 | |
---|
76 | # Maximum time (in seconds) a parsethread may run |
---|
77 | # |
---|
78 | PARSE_TIMEOUT = 60 |
---|
79 | |
---|
80 | # Maximum time (in seconds) a storethread may run |
---|
81 | # |
---|
82 | STORE_TIMEOUT = 360 |
---|
83 | |
---|
84 | """ |
---|
85 | This is TOrque-GAnglia's data Daemon |
---|
86 | """ |
---|
87 | |
---|
88 | class RRDMutator: |
---|
89 | """A class for performing RRD mutations""" |
---|
90 | |
---|
91 | binary = '/usr/bin/rrdtool' |
---|
92 | |
---|
93 | def __init__( self, binary=None ): |
---|
94 | """Set alternate binary if supplied""" |
---|
95 | |
---|
96 | if binary: |
---|
97 | self.binary = binary |
---|
98 | |
---|
99 | def create( self, filename, args ): |
---|
100 | """Create a new rrd with args""" |
---|
101 | |
---|
102 | return self.perform( 'create', '"' + filename + '"', args ) |
---|
103 | |
---|
104 | def update( self, filename, args ): |
---|
105 | """Update a rrd with args""" |
---|
106 | |
---|
107 | return self.perform( 'update', '"' + filename + '"', args ) |
---|
108 | |
---|
109 | def grabLastUpdate( self, filename ): |
---|
110 | """Determine the last update time of filename rrd""" |
---|
111 | |
---|
112 | last_update = 0 |
---|
113 | |
---|
114 | debug_msg( 8, self.binary + ' info "' + filename + '"' ) |
---|
115 | |
---|
116 | for line in os.popen( self.binary + ' info "' + filename + '"' ).readlines(): |
---|
117 | |
---|
118 | if line.find( 'last_update') != -1: |
---|
119 | |
---|
120 | last_update = line.split( ' = ' )[1] |
---|
121 | |
---|
122 | if last_update: |
---|
123 | return last_update |
---|
124 | else: |
---|
125 | return 0 |
---|
126 | |
---|
127 | def perform( self, action, filename, args ): |
---|
128 | """Perform action on rrd filename with args""" |
---|
129 | |
---|
130 | arg_string = None |
---|
131 | |
---|
132 | if type( args ) is not ListType: |
---|
133 | debug_msg( 8, 'Arguments needs to be of type List' ) |
---|
134 | return 1 |
---|
135 | |
---|
136 | for arg in args: |
---|
137 | |
---|
138 | if not arg_string: |
---|
139 | |
---|
140 | arg_string = arg |
---|
141 | else: |
---|
142 | arg_string = arg_string + ' ' + arg |
---|
143 | |
---|
144 | debug_msg( 8, self.binary + ' ' + action + ' ' + filename + ' ' + arg_string ) |
---|
145 | |
---|
146 | for line in os.popen( self.binary + ' ' + action + ' ' + filename + ' ' + arg_string ).readlines(): |
---|
147 | |
---|
148 | if line.find( 'ERROR' ) != -1: |
---|
149 | |
---|
150 | error_msg = string.join( line.split( ' ' )[1:] ) |
---|
151 | debug_msg( 8, error_msg ) |
---|
152 | return 1 |
---|
153 | |
---|
154 | return 0 |
---|
155 | |
---|
156 | class TorqueXMLHandler( xml.sax.handler.ContentHandler ): |
---|
157 | """Parse Torque's jobinfo XML from our plugin""" |
---|
158 | |
---|
159 | def __init__( self ): |
---|
160 | |
---|
161 | pass |
---|
162 | |
---|
163 | def startElement( self, name, attrs ): |
---|
164 | """ |
---|
165 | This XML will be all gmetric XML |
---|
166 | so there will be no specific start/end element |
---|
167 | just one XML statement with all info |
---|
168 | """ |
---|
169 | |
---|
170 | heartbeat = 0 |
---|
171 | |
---|
172 | if name == 'METRIC': |
---|
173 | |
---|
174 | metricname = attrs.get( 'NAME', "" ) |
---|
175 | |
---|
176 | if metricname == 'TOGA-HEARTBEAT': |
---|
177 | self.heartbeat = attrs.get( 'VAL', "" ) |
---|
178 | |
---|
179 | elif metricname.find( 'TOGA-JOB' ) != -1: |
---|
180 | |
---|
181 | job_id = name.split( 'TOGA-JOB-' )[1] |
---|
182 | val = attrs.get( 'VAL', "" ) |
---|
183 | |
---|
184 | valinfo = val.split( ' ' ) |
---|
185 | print valinfo |
---|
186 | |
---|
187 | for myval in valinfo: |
---|
188 | |
---|
189 | name = valinfo.split( '=' )[0] |
---|
190 | value = valinfo.split( '=' )[1] |
---|
191 | |
---|
192 | #if name == ' |
---|
193 | |
---|
194 | class GangliaXMLHandler( xml.sax.handler.ContentHandler ): |
---|
195 | """Parse Ganglia's XML""" |
---|
196 | |
---|
197 | def __init__( self, config ): |
---|
198 | """Setup initial variables and gather info on existing rrd archive""" |
---|
199 | |
---|
200 | self.config = config |
---|
201 | self.clusters = { } |
---|
202 | debug_msg( 0, printTime() + ' - Checking existing toga rrd archive..' ) |
---|
203 | self.gatherClusters() |
---|
204 | debug_msg( 0, printTime() + ' - Check done.' ) |
---|
205 | |
---|
206 | def gatherClusters( self ): |
---|
207 | """Find all existing clusters in archive dir""" |
---|
208 | |
---|
209 | archive_dir = check_dir(ARCHIVE_PATH) |
---|
210 | |
---|
211 | hosts = [ ] |
---|
212 | |
---|
213 | if os.path.exists( archive_dir ): |
---|
214 | |
---|
215 | dirlist = os.listdir( archive_dir ) |
---|
216 | |
---|
217 | for item in dirlist: |
---|
218 | |
---|
219 | clustername = item |
---|
220 | |
---|
221 | if not self.clusters.has_key( clustername ) and clustername in ARCHIVE_DATASOURCES: |
---|
222 | |
---|
223 | self.clusters[ clustername ] = RRDHandler( self.config, clustername ) |
---|
224 | |
---|
225 | def startElement( self, name, attrs ): |
---|
226 | """Memorize appropriate data from xml start tags""" |
---|
227 | |
---|
228 | if name == 'GANGLIA_XML': |
---|
229 | |
---|
230 | self.XMLSource = attrs.get( 'SOURCE', "" ) |
---|
231 | self.gangliaVersion = attrs.get( 'VERSION', "" ) |
---|
232 | |
---|
233 | debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) ) |
---|
234 | |
---|
235 | elif name == 'GRID': |
---|
236 | |
---|
237 | self.gridName = attrs.get( 'NAME', "" ) |
---|
238 | self.time = attrs.get( 'LOCALTIME', "" ) |
---|
239 | |
---|
240 | debug_msg( 10, '`-Grid found: %s' %( self.gridName ) ) |
---|
241 | |
---|
242 | elif name == 'CLUSTER': |
---|
243 | |
---|
244 | self.clusterName = attrs.get( 'NAME', "" ) |
---|
245 | self.time = attrs.get( 'LOCALTIME', "" ) |
---|
246 | |
---|
247 | if not self.clusters.has_key( self.clusterName ) and self.clusterName in ARCHIVE_DATASOURCES: |
---|
248 | |
---|
249 | self.clusters[ self.clusterName ] = RRDHandler( self.config, self.clusterName ) |
---|
250 | |
---|
251 | debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) ) |
---|
252 | |
---|
253 | elif name == 'HOST' and self.clusterName in ARCHIVE_DATASOURCES: |
---|
254 | |
---|
255 | self.hostName = attrs.get( 'NAME', "" ) |
---|
256 | self.hostIp = attrs.get( 'IP', "" ) |
---|
257 | self.hostReported = attrs.get( 'REPORTED', "" ) |
---|
258 | |
---|
259 | debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) ) |
---|
260 | |
---|
261 | elif name == 'METRIC' and self.clusterName in ARCHIVE_DATASOURCES: |
---|
262 | |
---|
263 | type = attrs.get( 'TYPE', "" ) |
---|
264 | |
---|
265 | if type not in UNSUPPORTED_ARCHIVE_TYPES: |
---|
266 | |
---|
267 | myMetric = { } |
---|
268 | myMetric['name'] = attrs.get( 'NAME', "" ) |
---|
269 | myMetric['val'] = attrs.get( 'VAL', "" ) |
---|
270 | myMetric['time'] = self.hostReported |
---|
271 | |
---|
272 | self.clusters[ self.clusterName ].memMetric( self.hostName, myMetric ) |
---|
273 | |
---|
274 | debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) ) |
---|
275 | |
---|
276 | def storeMetrics( self ): |
---|
277 | """Store metrics of each cluster rrd handler""" |
---|
278 | |
---|
279 | for clustername, rrdh in self.clusters.items(): |
---|
280 | |
---|
281 | ret = rrdh.storeMetrics() |
---|
282 | |
---|
283 | if ret: |
---|
284 | debug_msg( 9, 'An error occured while storing metrics for cluster %s' %clustername ) |
---|
285 | return 1 |
---|
286 | |
---|
287 | return 0 |
---|
288 | |
---|
289 | class XMLErrorHandler( xml.sax.handler.ErrorHandler ): |
---|
290 | |
---|
291 | def error( self, exception ): |
---|
292 | """Recoverable error""" |
---|
293 | |
---|
294 | debug_msg( 0, 'Recoverable error ' + str( exception ) ) |
---|
295 | |
---|
296 | def fatalError( self, exception ): |
---|
297 | """Non-recoverable error""" |
---|
298 | |
---|
299 | exception_str = str( exception ) |
---|
300 | |
---|
301 | # Ignore 'no element found' errors |
---|
302 | if exception_str.find( 'no element found' ) != -1: |
---|
303 | debug_msg( 1, 'No XML data found: probably socket not (re)connected.' ) |
---|
304 | return 0 |
---|
305 | |
---|
306 | debug_msg( 0, 'Non-recoverable error ' + str( exception ) ) |
---|
307 | sys.exit( 1 ) |
---|
308 | |
---|
309 | def warning( self, exception ): |
---|
310 | """Warning""" |
---|
311 | |
---|
312 | debug_msg( 0, 'Warning ' + str( exception ) ) |
---|
313 | |
---|
314 | class GangliaXMLGatherer: |
---|
315 | """Setup a connection and file object to Ganglia's XML""" |
---|
316 | |
---|
317 | s = None |
---|
318 | fd = None |
---|
319 | |
---|
320 | def __init__( self, host, port ): |
---|
321 | """Store host and port for connection""" |
---|
322 | |
---|
323 | self.host = host |
---|
324 | self.port = port |
---|
325 | self.connect() |
---|
326 | self.makeFileDescriptor() |
---|
327 | |
---|
328 | def connect( self ): |
---|
329 | """Setup connection to XML source""" |
---|
330 | |
---|
331 | for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ): |
---|
332 | |
---|
333 | af, socktype, proto, canonname, sa = res |
---|
334 | |
---|
335 | try: |
---|
336 | |
---|
337 | self.s = socket.socket( af, socktype, proto ) |
---|
338 | |
---|
339 | except socket.error, msg: |
---|
340 | |
---|
341 | self.s = None |
---|
342 | continue |
---|
343 | |
---|
344 | try: |
---|
345 | |
---|
346 | self.s.connect( sa ) |
---|
347 | |
---|
348 | except socket.error, msg: |
---|
349 | |
---|
350 | self.disconnect() |
---|
351 | continue |
---|
352 | |
---|
353 | break |
---|
354 | |
---|
355 | if self.s is None: |
---|
356 | |
---|
357 | debug_msg( 0, 'Could not open socket' ) |
---|
358 | sys.exit( 1 ) |
---|
359 | |
---|
360 | def disconnect( self ): |
---|
361 | """Close socket""" |
---|
362 | |
---|
363 | if self.s: |
---|
364 | self.s.shutdown( 2 ) |
---|
365 | self.s.close() |
---|
366 | self.s = None |
---|
367 | |
---|
368 | def __del__( self ): |
---|
369 | """Kill the socket before we leave""" |
---|
370 | |
---|
371 | self.disconnect() |
---|
372 | |
---|
373 | def reconnect( self ): |
---|
374 | """Reconnect""" |
---|
375 | |
---|
376 | if self.s: |
---|
377 | self.disconnect() |
---|
378 | |
---|
379 | self.connect() |
---|
380 | |
---|
381 | def makeFileDescriptor( self ): |
---|
382 | """Make file descriptor that points to our socket connection""" |
---|
383 | |
---|
384 | self.reconnect() |
---|
385 | |
---|
386 | if self.s: |
---|
387 | self.fd = self.s.makefile( 'r' ) |
---|
388 | |
---|
389 | def getFileObject( self ): |
---|
390 | """Connect, and return a file object""" |
---|
391 | |
---|
392 | if self.fd: |
---|
393 | return self.fd |
---|
394 | |
---|
395 | class GangliaXMLProcessor: |
---|
396 | """Main class for processing XML and acting with it""" |
---|
397 | |
---|
398 | def __init__( self ): |
---|
399 | """Setup initial XML connection and handlers""" |
---|
400 | |
---|
401 | self.config = GangliaConfigParser( GMETAD_CONF ) |
---|
402 | |
---|
403 | self.myXMLGatherer = GangliaXMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] ) |
---|
404 | self.myXMLSource = self.myXMLGatherer.getFileObject() |
---|
405 | while( 1 ): |
---|
406 | print 'parse' |
---|
407 | self.myXMLGatherer.makeFileDescriptor() |
---|
408 | self.myXMLSource = self.myXMLGatherer.getFileObject() |
---|
409 | xml.sax.parse( self.myXMLSource, TorqueXMLHandler(), XMLErrorHandler() ) |
---|
410 | print 'sleep' |
---|
411 | time.sleep( 1 ) |
---|
412 | #self.myHandler = GangliaXMLHandler( self.config ) |
---|
413 | #self.myHandler = TorqueXMLHandler( ) |
---|
414 | #self.myParser.setContentHandler( self.myHandler ) |
---|
415 | |
---|
416 | def daemon( self ): |
---|
417 | """Run as daemon forever""" |
---|
418 | |
---|
419 | # Fork the first child |
---|
420 | # |
---|
421 | pid = os.fork() |
---|
422 | |
---|
423 | if pid > 0: |
---|
424 | |
---|
425 | sys.exit(0) # end parent |
---|
426 | |
---|
427 | # creates a session and sets the process group ID |
---|
428 | # |
---|
429 | os.setsid() |
---|
430 | |
---|
431 | # Fork the second child |
---|
432 | # |
---|
433 | pid = os.fork() |
---|
434 | |
---|
435 | if pid > 0: |
---|
436 | |
---|
437 | sys.exit(0) # end parent |
---|
438 | |
---|
439 | # Go to the root directory and set the umask |
---|
440 | # |
---|
441 | os.chdir('/') |
---|
442 | os.umask(0) |
---|
443 | |
---|
444 | sys.stdin.close() |
---|
445 | sys.stdout.close() |
---|
446 | #sys.stderr.close() |
---|
447 | |
---|
448 | os.open('/dev/null', 0) |
---|
449 | os.dup(0) |
---|
450 | os.dup(0) |
---|
451 | |
---|
452 | self.run() |
---|
453 | |
---|
454 | def printTime( self ): |
---|
455 | """Print current time in human readable format for logging""" |
---|
456 | |
---|
457 | return time.strftime("%a %d %b %Y %H:%M:%S") |
---|
458 | |
---|
459 | def run( self ): |
---|
460 | """Main XML processing; start a xml and storethread""" |
---|
461 | |
---|
462 | xmlthread = threading.Thread( None, self.processXML, 'xmlthread' ) |
---|
463 | storethread = threading.Thread( None, self.storeMetrics, 'storethread' ) |
---|
464 | |
---|
465 | while( 1 ): |
---|
466 | |
---|
467 | if not xmlthread.isAlive(): |
---|
468 | # Gather XML at the same interval as gmetad |
---|
469 | |
---|
470 | # threaded call to: self.processXML() |
---|
471 | # |
---|
472 | xmlthread = threading.Thread( None, self.processXML, 'xmlthread' ) |
---|
473 | xmlthread.start() |
---|
474 | |
---|
475 | if not storethread.isAlive(): |
---|
476 | # Store metrics every .. sec |
---|
477 | |
---|
478 | # threaded call to: self.storeMetrics() |
---|
479 | # |
---|
480 | storethread = threading.Thread( None, self.storeMetrics, 'storethread' ) |
---|
481 | storethread.start() |
---|
482 | |
---|
483 | # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway |
---|
484 | time.sleep( 1 ) |
---|
485 | |
---|
486 | def storeMetrics( self ): |
---|
487 | """Store metrics retained in memory to disk""" |
---|
488 | |
---|
489 | debug_msg( 7, self.printTime() + ' - storethread(): started.' ) |
---|
490 | |
---|
491 | # Store metrics somewhere between every 360 and 640 seconds |
---|
492 | # |
---|
493 | STORE_INTERVAL = random.randint( 360, 640 ) |
---|
494 | |
---|
495 | storethread = threading.Thread( None, self.storeThread, 'storemetricthread' ) |
---|
496 | storethread.start() |
---|
497 | |
---|
498 | debug_msg( 7, self.printTime() + ' - storethread(): Sleeping.. (%ss)' %STORE_INTERVAL ) |
---|
499 | time.sleep( STORE_INTERVAL ) |
---|
500 | debug_msg( 7, self.printTime() + ' - storethread(): Done sleeping.' ) |
---|
501 | |
---|
502 | if storethread.isAlive(): |
---|
503 | |
---|
504 | debug_msg( 7, self.printTime() + ' - storethread(): storemetricthread() still running, waiting to finish..' ) |
---|
505 | storethread.join( STORE_TIMEOUT ) # Maximum time is for storing thread to finish |
---|
506 | debug_msg( 7, self.printTime() + ' - storethread(): Done waiting.' ) |
---|
507 | |
---|
508 | debug_msg( 7, self.printTime() + ' - storethread(): finished.' ) |
---|
509 | |
---|
510 | return 0 |
---|
511 | |
---|
512 | def storeThread( self ): |
---|
513 | """Actual metric storing thread""" |
---|
514 | |
---|
515 | debug_msg( 7, self.printTime() + ' - storemetricthread(): started.' ) |
---|
516 | debug_msg( 7, self.printTime() + ' - storemetricthread(): Storing data..' ) |
---|
517 | ret = self.myHandler.storeMetrics() |
---|
518 | debug_msg( 7, self.printTime() + ' - storemetricthread(): Done storing.' ) |
---|
519 | debug_msg( 7, self.printTime() + ' - storemetricthread(): finished.' ) |
---|
520 | |
---|
521 | return ret |
---|
522 | |
---|
523 | def processXML( self ): |
---|
524 | """Process XML""" |
---|
525 | |
---|
526 | debug_msg( 7, self.printTime() + ' - xmlthread(): started.' ) |
---|
527 | |
---|
528 | parsethread = threading.Thread( None, self.parseThread, 'parsethread' ) |
---|
529 | parsethread.start() |
---|
530 | |
---|
531 | debug_msg( 7, self.printTime() + ' - xmlthread(): Sleeping.. (%ss)' %self.config.getLowestInterval() ) |
---|
532 | time.sleep( float( self.config.getLowestInterval() ) ) |
---|
533 | debug_msg( 7, self.printTime() + ' - xmlthread(): Done sleeping.' ) |
---|
534 | |
---|
535 | if parsethread.isAlive(): |
---|
536 | |
---|
537 | debug_msg( 7, self.printTime() + ' - xmlthread(): parsethread() still running, waiting to finish..' ) |
---|
538 | parsethread.join( PARSE_TIMEOUT ) # Maximum time for XML thread to finish |
---|
539 | debug_msg( 7, self.printTime() + ' - xmlthread(): Done waiting.' ) |
---|
540 | |
---|
541 | debug_msg( 7, self.printTime() + ' - xmlthread(): finished.' ) |
---|
542 | |
---|
543 | return 0 |
---|
544 | |
---|
545 | def parseThread( self ): |
---|
546 | """Actual parsing thread""" |
---|
547 | |
---|
548 | debug_msg( 7, self.printTime() + ' - parsethread(): started.' ) |
---|
549 | debug_msg( 7, self.printTime() + ' - parsethread(): Parsing XML..' ) |
---|
550 | #ret = self.myParser.parse( self.myXMLGatherer.getFileObject() ) |
---|
551 | debug_msg( 7, self.printTime() + ' - parsethread(): Done parsing.' ) |
---|
552 | debug_msg( 7, self.printTime() + ' - parsethread(): finished.' ) |
---|
553 | |
---|
554 | return ret |
---|
555 | |
---|
556 | class GangliaConfigParser: |
---|
557 | |
---|
558 | sources = [ ] |
---|
559 | |
---|
560 | def __init__( self, config ): |
---|
561 | """Parse some stuff from our gmetad's config, such as polling interval""" |
---|
562 | |
---|
563 | self.config = config |
---|
564 | self.parseValues() |
---|
565 | |
---|
566 | def parseValues( self ): |
---|
567 | """Parse certain values from gmetad.conf""" |
---|
568 | |
---|
569 | readcfg = open( self.config, 'r' ) |
---|
570 | |
---|
571 | for line in readcfg.readlines(): |
---|
572 | |
---|
573 | if line.count( '"' ) > 1: |
---|
574 | |
---|
575 | if line.find( 'data_source' ) != -1 and line[0] != '#': |
---|
576 | |
---|
577 | source = { } |
---|
578 | source['name'] = line.split( '"' )[1] |
---|
579 | source_words = line.split( '"' )[2].split( ' ' ) |
---|
580 | |
---|
581 | for word in source_words: |
---|
582 | |
---|
583 | valid_interval = 1 |
---|
584 | |
---|
585 | for letter in word: |
---|
586 | |
---|
587 | if letter not in string.digits: |
---|
588 | |
---|
589 | valid_interval = 0 |
---|
590 | |
---|
591 | if valid_interval and len(word) > 0: |
---|
592 | |
---|
593 | source['interval'] = word |
---|
594 | debug_msg( 9, 'polling interval for %s = %s' %(source['name'], source['interval'] ) ) |
---|
595 | |
---|
596 | # No interval found, use Ganglia's default |
---|
597 | if not source.has_key( 'interval' ): |
---|
598 | source['interval'] = 15 |
---|
599 | debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) ) |
---|
600 | |
---|
601 | self.sources.append( source ) |
---|
602 | |
---|
603 | def getInterval( self, source_name ): |
---|
604 | """Return interval for source_name""" |
---|
605 | |
---|
606 | for source in self.sources: |
---|
607 | |
---|
608 | if source['name'] == source_name: |
---|
609 | |
---|
610 | return source['interval'] |
---|
611 | |
---|
612 | return None |
---|
613 | |
---|
614 | def getLowestInterval( self ): |
---|
615 | """Return the lowest interval of all clusters""" |
---|
616 | |
---|
617 | lowest_interval = 0 |
---|
618 | |
---|
619 | for source in self.sources: |
---|
620 | |
---|
621 | if not lowest_interval or source['interval'] <= lowest_interval: |
---|
622 | |
---|
623 | lowest_interval = source['interval'] |
---|
624 | |
---|
625 | # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays |
---|
626 | if lowest_interval: |
---|
627 | return lowest_interval |
---|
628 | else: |
---|
629 | return 15 |
---|
630 | |
---|
631 | class RRDHandler: |
---|
632 | """Class for handling RRD activity""" |
---|
633 | |
---|
634 | myMetrics = { } |
---|
635 | lastStored = { } |
---|
636 | timeserials = { } |
---|
637 | slot = None |
---|
638 | |
---|
639 | def __init__( self, config, cluster ): |
---|
640 | """Setup initial variables""" |
---|
641 | self.block = 0 |
---|
642 | self.cluster = cluster |
---|
643 | self.config = config |
---|
644 | self.slot = threading.Lock() |
---|
645 | self.rrdm = RRDMutator() |
---|
646 | self.gatherLastUpdates() |
---|
647 | |
---|
648 | def gatherLastUpdates( self ): |
---|
649 | """Populate the lastStored list, containing timestamps of all last updates""" |
---|
650 | |
---|
651 | cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster ) |
---|
652 | |
---|
653 | hosts = [ ] |
---|
654 | |
---|
655 | if os.path.exists( cluster_dir ): |
---|
656 | |
---|
657 | dirlist = os.listdir( cluster_dir ) |
---|
658 | |
---|
659 | for dir in dirlist: |
---|
660 | |
---|
661 | hosts.append( dir ) |
---|
662 | |
---|
663 | for host in hosts: |
---|
664 | |
---|
665 | host_dir = cluster_dir + '/' + host |
---|
666 | dirlist = os.listdir( host_dir ) |
---|
667 | |
---|
668 | for dir in dirlist: |
---|
669 | |
---|
670 | if not self.timeserials.has_key( host ): |
---|
671 | |
---|
672 | self.timeserials[ host ] = [ ] |
---|
673 | |
---|
674 | self.timeserials[ host ].append( dir ) |
---|
675 | |
---|
676 | last_serial = self.getLastRrdTimeSerial( host ) |
---|
677 | if last_serial: |
---|
678 | |
---|
679 | metric_dir = cluster_dir + '/' + host + '/' + last_serial |
---|
680 | if os.path.exists( metric_dir ): |
---|
681 | |
---|
682 | dirlist = os.listdir( metric_dir ) |
---|
683 | |
---|
684 | for file in dirlist: |
---|
685 | |
---|
686 | metricname = file.split( '.rrd' )[0] |
---|
687 | |
---|
688 | if not self.lastStored.has_key( host ): |
---|
689 | |
---|
690 | self.lastStored[ host ] = { } |
---|
691 | |
---|
692 | self.lastStored[ host ][ metricname ] = self.rrdm.grabLastUpdate( metric_dir + '/' + file ) |
---|
693 | |
---|
694 | def getClusterName( self ): |
---|
695 | """Return clustername""" |
---|
696 | |
---|
697 | return self.cluster |
---|
698 | |
---|
699 | def memMetric( self, host, metric ): |
---|
700 | """Store metric from host in memory""" |
---|
701 | |
---|
702 | if self.myMetrics.has_key( host ): |
---|
703 | |
---|
704 | if self.myMetrics[ host ].has_key( metric['name'] ): |
---|
705 | |
---|
706 | for mymetric in self.myMetrics[ host ][ metric['name'] ]: |
---|
707 | |
---|
708 | if mymetric['time'] == metric['time']: |
---|
709 | |
---|
710 | # Allready have this metric, abort |
---|
711 | return 1 |
---|
712 | else: |
---|
713 | self.myMetrics[ host ][ metric['name'] ] = [ ] |
---|
714 | else: |
---|
715 | self.myMetrics[ host ] = { } |
---|
716 | self.myMetrics[ host ][ metric['name'] ] = [ ] |
---|
717 | |
---|
718 | # Push new metric onto stack |
---|
719 | # atomic code; only 1 thread at a time may access the stack |
---|
720 | |
---|
721 | # <ATOMIC> |
---|
722 | # |
---|
723 | self.slot.acquire() |
---|
724 | |
---|
725 | self.myMetrics[ host ][ metric['name'] ].append( metric ) |
---|
726 | |
---|
727 | self.slot.release() |
---|
728 | # |
---|
729 | # </ATOMIC> |
---|
730 | |
---|
731 | def makeUpdateList( self, host, metriclist ): |
---|
732 | """ |
---|
733 | Make a list of update values for rrdupdate |
---|
734 | but only those that we didn't store before |
---|
735 | """ |
---|
736 | |
---|
737 | update_list = [ ] |
---|
738 | metric = None |
---|
739 | |
---|
740 | while len( metriclist ) > 0: |
---|
741 | |
---|
742 | metric = metriclist.pop( 0 ) |
---|
743 | |
---|
744 | if self.checkStoreMetric( host, metric ): |
---|
745 | update_list.append( '%s:%s' %( metric['time'], metric['val'] ) ) |
---|
746 | |
---|
747 | return update_list |
---|
748 | |
---|
749 | def checkStoreMetric( self, host, metric ): |
---|
750 | """Check if supplied metric if newer than last one stored""" |
---|
751 | |
---|
752 | if self.lastStored.has_key( host ): |
---|
753 | |
---|
754 | if self.lastStored[ host ].has_key( metric['name'] ): |
---|
755 | |
---|
756 | if metric['time'] <= self.lastStored[ host ][ metric['name'] ]: |
---|
757 | |
---|
758 | # This is old |
---|
759 | return 0 |
---|
760 | |
---|
761 | return 1 |
---|
762 | |
---|
763 | def memLastUpdate( self, host, metricname, metriclist ): |
---|
764 | """ |
---|
765 | Memorize the time of the latest metric from metriclist |
---|
766 | but only if it wasn't allready memorized |
---|
767 | """ |
---|
768 | |
---|
769 | if not self.lastStored.has_key( host ): |
---|
770 | self.lastStored[ host ] = { } |
---|
771 | |
---|
772 | last_update_time = 0 |
---|
773 | |
---|
774 | for metric in metriclist: |
---|
775 | |
---|
776 | if metric['name'] == metricname: |
---|
777 | |
---|
778 | if metric['time'] > last_update_time: |
---|
779 | |
---|
780 | last_update_time = metric['time'] |
---|
781 | |
---|
782 | if self.lastStored[ host ].has_key( metricname ): |
---|
783 | |
---|
784 | if last_update_time <= self.lastStored[ host ][ metricname ]: |
---|
785 | return 1 |
---|
786 | |
---|
787 | self.lastStored[ host ][ metricname ] = last_update_time |
---|
788 | |
---|
789 | def storeMetrics( self ): |
---|
790 | """ |
---|
791 | Store all metrics from memory to disk |
---|
792 | and do it to the RRD's in appropriate timeperiod directory |
---|
793 | """ |
---|
794 | |
---|
795 | for hostname, mymetrics in self.myMetrics.items(): |
---|
796 | |
---|
797 | for metricname, mymetric in mymetrics.items(): |
---|
798 | |
---|
799 | metrics_to_store = [ ] |
---|
800 | |
---|
801 | # Pop metrics from stack for storing until none is left |
---|
802 | # atomic code: only 1 thread at a time may access myMetrics |
---|
803 | |
---|
804 | # <ATOMIC> |
---|
805 | # |
---|
806 | self.slot.acquire() |
---|
807 | |
---|
808 | while len( self.myMetrics[ hostname ][ metricname ] ) > 0: |
---|
809 | |
---|
810 | if len( self.myMetrics[ hostname ][ metricname ] ) > 0: |
---|
811 | metrics_to_store.append( self.myMetrics[ hostname ][ metricname ].pop( 0 ) ) |
---|
812 | |
---|
813 | self.slot.release() |
---|
814 | # |
---|
815 | # </ATOMIC> |
---|
816 | |
---|
817 | # Create a mapping table, each metric to the period where it should be stored |
---|
818 | # |
---|
819 | metric_serial_table = self.determineSerials( hostname, metricname, metrics_to_store ) |
---|
820 | |
---|
821 | update_rets = [ ] |
---|
822 | |
---|
823 | for period, pmetric in metric_serial_table.items(): |
---|
824 | |
---|
825 | self.createCheck( hostname, metricname, period ) |
---|
826 | |
---|
827 | update_ret = self.update( hostname, metricname, period, pmetric ) |
---|
828 | |
---|
829 | if update_ret == 0: |
---|
830 | |
---|
831 | debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) ) |
---|
832 | else: |
---|
833 | debug_msg( 9, 'metric update failed' ) |
---|
834 | |
---|
835 | update_rets.append( update_ret ) |
---|
836 | |
---|
837 | if not (1) in update_rets: |
---|
838 | |
---|
839 | self.memLastUpdate( hostname, metricname, metrics_to_store ) |
---|
840 | |
---|
841 | def makeTimeSerial( self ): |
---|
842 | """Generate a time serial. Seconds since epoch""" |
---|
843 | |
---|
844 | # Seconds since epoch |
---|
845 | mytime = int( time.time() ) |
---|
846 | |
---|
847 | return mytime |
---|
848 | |
---|
849 | def makeRrdPath( self, host, metricname, timeserial ): |
---|
850 | """Make a RRD location/path and filename""" |
---|
851 | |
---|
852 | rrd_dir = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial ) |
---|
853 | rrd_file = '%s/%s.rrd' %( rrd_dir, metricname ) |
---|
854 | |
---|
855 | return rrd_dir, rrd_file |
---|
856 | |
---|
857 | def getLastRrdTimeSerial( self, host ): |
---|
858 | """Find the last timeserial (directory) for this host""" |
---|
859 | |
---|
860 | newest_timeserial = 0 |
---|
861 | |
---|
862 | for dir in self.timeserials[ host ]: |
---|
863 | |
---|
864 | valid_dir = 1 |
---|
865 | |
---|
866 | for letter in dir: |
---|
867 | if letter not in string.digits: |
---|
868 | valid_dir = 0 |
---|
869 | |
---|
870 | if valid_dir: |
---|
871 | timeserial = dir |
---|
872 | if timeserial > newest_timeserial: |
---|
873 | newest_timeserial = timeserial |
---|
874 | |
---|
875 | if newest_timeserial: |
---|
876 | return newest_timeserial |
---|
877 | else: |
---|
878 | return 0 |
---|
879 | |
---|
880 | def determinePeriod( self, host, check_serial ): |
---|
881 | """Determine to which period (directory) this time(serial) belongs""" |
---|
882 | |
---|
883 | period_serial = 0 |
---|
884 | |
---|
885 | if self.timeserials.has_key( host ): |
---|
886 | |
---|
887 | for serial in self.timeserials[ host ]: |
---|
888 | |
---|
889 | if check_serial >= serial and period_serial < serial: |
---|
890 | |
---|
891 | period_serial = serial |
---|
892 | |
---|
893 | return period_serial |
---|
894 | |
---|
895 | def determineSerials( self, host, metricname, metriclist ): |
---|
896 | """ |
---|
897 | Determine the correct serial and corresponding rrd to store |
---|
898 | for a list of metrics |
---|
899 | """ |
---|
900 | |
---|
901 | metric_serial_table = { } |
---|
902 | |
---|
903 | for metric in metriclist: |
---|
904 | |
---|
905 | if metric['name'] == metricname: |
---|
906 | |
---|
907 | period = self.determinePeriod( host, metric['time'] ) |
---|
908 | |
---|
909 | archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60) |
---|
910 | |
---|
911 | if (int( metric['time'] ) - int( period ) ) > archive_secs: |
---|
912 | |
---|
913 | # This one should get it's own new period |
---|
914 | period = metric['time'] |
---|
915 | |
---|
916 | if not self.timeserials.has_key( host ): |
---|
917 | self.timeserials[ host ] = [ ] |
---|
918 | |
---|
919 | self.timeserials[ host ].append( period ) |
---|
920 | |
---|
921 | if not metric_serial_table.has_key( period ): |
---|
922 | |
---|
923 | metric_serial_table[ period ] = [ ] |
---|
924 | |
---|
925 | metric_serial_table[ period ].append( metric ) |
---|
926 | |
---|
927 | return metric_serial_table |
---|
928 | |
---|
929 | def createCheck( self, host, metricname, timeserial ): |
---|
930 | """Check if an rrd allready exists for this metric, create if not""" |
---|
931 | |
---|
932 | debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) ) |
---|
933 | |
---|
934 | rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial ) |
---|
935 | |
---|
936 | if not os.path.exists( rrd_dir ): |
---|
937 | |
---|
938 | try: |
---|
939 | os.makedirs( rrd_dir ) |
---|
940 | |
---|
941 | except OSError, msg: |
---|
942 | |
---|
943 | if msg.find( 'File exists' ) != -1: |
---|
944 | |
---|
945 | # Ignore exists errors |
---|
946 | pass |
---|
947 | |
---|
948 | else: |
---|
949 | |
---|
950 | print msg |
---|
951 | return |
---|
952 | |
---|
953 | debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) ) |
---|
954 | |
---|
955 | if not os.path.exists( rrd_file ): |
---|
956 | |
---|
957 | interval = self.config.getInterval( self.cluster ) |
---|
958 | heartbeat = 8 * int( interval ) |
---|
959 | |
---|
960 | params = [ ] |
---|
961 | |
---|
962 | params.append( '--step' ) |
---|
963 | params.append( str( interval ) ) |
---|
964 | |
---|
965 | params.append( '--start' ) |
---|
966 | params.append( str( int( timeserial ) - 1 ) ) |
---|
967 | |
---|
968 | params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat ) |
---|
969 | params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) ) |
---|
970 | |
---|
971 | self.rrdm.create( str(rrd_file), params ) |
---|
972 | |
---|
973 | debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) ) |
---|
974 | |
---|
975 | def update( self, host, metricname, timeserial, metriclist ): |
---|
976 | """ |
---|
977 | Update rrd file for host with metricname |
---|
978 | in directory timeserial with metriclist |
---|
979 | """ |
---|
980 | |
---|
981 | debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) ) |
---|
982 | |
---|
983 | rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial ) |
---|
984 | |
---|
985 | update_list = self.makeUpdateList( host, metriclist ) |
---|
986 | |
---|
987 | if len( update_list ) > 0: |
---|
988 | ret = self.rrdm.update( str(rrd_file), update_list ) |
---|
989 | |
---|
990 | if ret: |
---|
991 | return 1 |
---|
992 | |
---|
993 | debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) ) |
---|
994 | |
---|
995 | return 0 |
---|
996 | |
---|
997 | def main(): |
---|
998 | """Program startup""" |
---|
999 | |
---|
1000 | myProcessor = GangliaXMLProcessor() |
---|
1001 | |
---|
1002 | if DAEMONIZE: |
---|
1003 | myProcessor.daemon() |
---|
1004 | else: |
---|
1005 | myProcessor.run() |
---|
1006 | |
---|
1007 | def check_dir( directory ): |
---|
1008 | """Check if directory is a proper directory. I.e.: Does _not_ end with a '/'""" |
---|
1009 | |
---|
1010 | if directory[-1] == '/': |
---|
1011 | directory = directory[:-1] |
---|
1012 | |
---|
1013 | return directory |
---|
1014 | |
---|
1015 | def debug_msg( level, msg ): |
---|
1016 | """Only print msg if it is not below our debug level""" |
---|
1017 | |
---|
1018 | if (DEBUG_LEVEL >= level): |
---|
1019 | sys.stderr.write( msg + '\n' ) |
---|
1020 | |
---|
1021 | def printTime( ): |
---|
1022 | """Print current time in human readable format""" |
---|
1023 | |
---|
1024 | return time.strftime("%a %d %b %Y %H:%M:%S") |
---|
1025 | |
---|
1026 | # Ooohh, someone started me! Let's go.. |
---|
1027 | if __name__ == '__main__': |
---|
1028 | main() |
---|