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