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