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