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