[3] | 1 | #!/usr/bin/env python |
---|
[225] | 2 | # |
---|
| 3 | # This file is part of Jobmonarch |
---|
| 4 | # |
---|
[771] | 5 | # Copyright (C) 2006-2013 Ramon Bastiaans |
---|
[225] | 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 | # |
---|
[230] | 21 | # SVN $Id: jobarchived.py 928 2013-07-31 14:17:51Z ramonb $ |
---|
| 22 | # |
---|
[3] | 23 | |
---|
[466] | 24 | import getopt, syslog, ConfigParser, sys |
---|
[3] | 25 | |
---|
[913] | 26 | VERSION='__VERSION__' |
---|
[284] | 27 | |
---|
[466] | 28 | def usage( ver ): |
---|
[284] | 29 | |
---|
[770] | 30 | print 'jobarchived %s' %VERSION |
---|
[284] | 31 | |
---|
[770] | 32 | if ver: |
---|
| 33 | return 0 |
---|
[284] | 34 | |
---|
[770] | 35 | print |
---|
| 36 | print 'Purpose:' |
---|
| 37 | print ' The Job Archive Daemon (jobarchived) stores batch job information in a SQL database' |
---|
| 38 | print ' and node statistics in a RRD archive' |
---|
| 39 | print |
---|
| 40 | print 'Usage: jobarchived [OPTIONS]' |
---|
| 41 | print |
---|
| 42 | print ' -c, --config=FILE The configuration file to use (default: /etc/jobarchived.conf)' |
---|
| 43 | print ' -p, --pidfile=FILE Use pid file to store the process id' |
---|
| 44 | print ' -h, --help Print help and exit' |
---|
| 45 | print ' -v, --version Print version and exit' |
---|
| 46 | print |
---|
[435] | 47 | |
---|
[214] | 48 | def processArgs( args ): |
---|
[6] | 49 | |
---|
[858] | 50 | SHORT_L = 'p:hvc:' |
---|
[773] | 51 | LONG_L = [ 'help', 'config=', 'pidfile=', 'version' ] |
---|
[169] | 52 | |
---|
[773] | 53 | config_filename = '/etc/jobarchived.conf' |
---|
[169] | 54 | |
---|
[770] | 55 | global PIDFILE |
---|
[435] | 56 | |
---|
[858] | 57 | PIDFILE = None |
---|
[435] | 58 | |
---|
[773] | 59 | try: |
---|
[169] | 60 | |
---|
[773] | 61 | opts, args = getopt.getopt( args, SHORT_L, LONG_L ) |
---|
[9] | 62 | |
---|
[773] | 63 | except getopt.error, detail: |
---|
[60] | 64 | |
---|
[773] | 65 | print detail |
---|
| 66 | sys.exit(1) |
---|
[9] | 67 | |
---|
[773] | 68 | for opt, value in opts: |
---|
[60] | 69 | |
---|
[773] | 70 | if opt in [ '--config', '-c' ]: |
---|
[13] | 71 | |
---|
[773] | 72 | config_filename = value |
---|
[198] | 73 | |
---|
[770] | 74 | if opt in [ '--pidfile', '-p' ]: |
---|
[435] | 75 | |
---|
[770] | 76 | PIDFILE = value |
---|
[435] | 77 | |
---|
[770] | 78 | if opt in [ '--help', '-h' ]: |
---|
[435] | 79 | |
---|
[770] | 80 | usage( False ) |
---|
| 81 | sys.exit( 0 ) |
---|
[435] | 82 | |
---|
[770] | 83 | if opt in [ '--version', '-v' ]: |
---|
[60] | 84 | |
---|
[770] | 85 | usage( True ) |
---|
| 86 | sys.exit( 0 ) |
---|
[22] | 87 | |
---|
[770] | 88 | try: |
---|
| 89 | return loadConfig( config_filename ) |
---|
[13] | 90 | |
---|
[770] | 91 | except ConfigParser.NoOptionError, detail: |
---|
[214] | 92 | |
---|
[770] | 93 | print detail |
---|
| 94 | sys.exit( 1 ) |
---|
[214] | 95 | |
---|
| 96 | def loadConfig( filename ): |
---|
| 97 | |
---|
[770] | 98 | def getlist( cfg_string ): |
---|
[214] | 99 | |
---|
[770] | 100 | my_list = [ ] |
---|
[214] | 101 | |
---|
[770] | 102 | for item_txt in cfg_string.split( ',' ): |
---|
[214] | 103 | |
---|
[770] | 104 | sep_char = None |
---|
[214] | 105 | |
---|
[770] | 106 | item_txt = item_txt.strip() |
---|
[214] | 107 | |
---|
[770] | 108 | for s_char in [ "'", '"' ]: |
---|
[214] | 109 | |
---|
[770] | 110 | if item_txt.find( s_char ) != -1: |
---|
[214] | 111 | |
---|
[770] | 112 | if item_txt.count( s_char ) != 2: |
---|
[214] | 113 | |
---|
[770] | 114 | print 'Missing quote: %s' %item_txt |
---|
| 115 | sys.exit( 1 ) |
---|
[214] | 116 | |
---|
[770] | 117 | else: |
---|
[214] | 118 | |
---|
[770] | 119 | sep_char = s_char |
---|
| 120 | break |
---|
[214] | 121 | |
---|
[770] | 122 | if sep_char: |
---|
[214] | 123 | |
---|
[770] | 124 | item_txt = item_txt.split( sep_char )[1] |
---|
[214] | 125 | |
---|
[770] | 126 | my_list.append( item_txt ) |
---|
[214] | 127 | |
---|
[770] | 128 | return my_list |
---|
[214] | 129 | |
---|
[770] | 130 | cfg = ConfigParser.ConfigParser() |
---|
[214] | 131 | |
---|
[770] | 132 | cfg.read( filename ) |
---|
[214] | 133 | |
---|
[770] | 134 | global DEBUG_LEVEL, USE_SYSLOG, SYSLOG_LEVEL, SYSLOG_FACILITY, GMETAD_CONF, ARCHIVE_XMLSOURCE |
---|
| 135 | global ARCHIVE_DATASOURCES, ARCHIVE_PATH, ARCHIVE_HOURS_PER_RRD, ARCHIVE_EXCLUDE_METRICS |
---|
[774] | 136 | global JOB_SQL_DBASE, DAEMONIZE, RRDTOOL, JOB_TIMEOUT, MODRRDTOOL, JOB_SQL_PASSWORD, JOB_SQL_USER |
---|
[214] | 137 | |
---|
[858] | 138 | ARCHIVE_PATH = cfg.get( 'DEFAULT', 'ARCHIVE_PATH' ) |
---|
[214] | 139 | |
---|
[858] | 140 | ARCHIVE_HOURS_PER_RRD = cfg.getint( 'DEFAULT', 'ARCHIVE_HOURS_PER_RRD' ) |
---|
[214] | 141 | |
---|
[858] | 142 | DEBUG_LEVEL = cfg.getint( 'DEFAULT', 'DEBUG_LEVEL' ) |
---|
[214] | 143 | |
---|
[858] | 144 | USE_SYSLOG = cfg.getboolean( 'DEFAULT', 'USE_SYSLOG' ) |
---|
[214] | 145 | |
---|
[858] | 146 | SYSLOG_LEVEL = cfg.getint( 'DEFAULT', 'SYSLOG_LEVEL' ) |
---|
[214] | 147 | |
---|
[858] | 148 | MODRRDTOOL = False |
---|
[375] | 149 | |
---|
[770] | 150 | try: |
---|
| 151 | global rrdtool |
---|
| 152 | import rrdtool |
---|
[214] | 153 | |
---|
[770] | 154 | MODRRDTOOL = True |
---|
[375] | 155 | |
---|
[770] | 156 | except ImportError: |
---|
[375] | 157 | |
---|
[770] | 158 | MODRRDTOOL = False |
---|
[375] | 159 | |
---|
[770] | 160 | print "ERROR: py-rrdtool import FAILED: failing back to DEPRECATED use of rrdtool binary. This will slow down jobarchived significantly!" |
---|
[375] | 161 | |
---|
[770] | 162 | RRDTOOL = cfg.get( 'DEFAULT', 'RRDTOOL' ) |
---|
[455] | 163 | |
---|
[770] | 164 | try: |
---|
[375] | 165 | |
---|
[770] | 166 | SYSLOG_FACILITY = eval( 'syslog.LOG_' + cfg.get( 'DEFAULT', 'SYSLOG_FACILITY' ) ) |
---|
[214] | 167 | |
---|
[770] | 168 | except AttributeError, detail: |
---|
[214] | 169 | |
---|
[770] | 170 | print 'Unknown syslog facility' |
---|
| 171 | sys.exit( 1 ) |
---|
[214] | 172 | |
---|
[858] | 173 | GMETAD_CONF = cfg.get( 'DEFAULT', 'GMETAD_CONF' ) |
---|
[214] | 174 | |
---|
[858] | 175 | ARCHIVE_XMLSOURCE = cfg.get( 'DEFAULT', 'ARCHIVE_XMLSOURCE' ) |
---|
[214] | 176 | |
---|
[858] | 177 | ARCHIVE_DATASOURCES = getlist( cfg.get( 'DEFAULT', 'ARCHIVE_DATASOURCES' ) ) |
---|
[214] | 178 | |
---|
[858] | 179 | ARCHIVE_EXCLUDE_METRICS = getlist( cfg.get( 'DEFAULT', 'ARCHIVE_EXCLUDE_METRICS' ) ) |
---|
[214] | 180 | |
---|
[858] | 181 | JOB_SQL_DBASE = cfg.get( 'DEFAULT', 'JOB_SQL_DBASE' ) |
---|
| 182 | JOB_SQL_USER = cfg.get( 'DEFAULT', 'JOB_SQL_USER' ) |
---|
[774] | 183 | JOB_SQL_PASSWORD = cfg.get( 'DEFAULT', 'JOB_SQL_PASSWORD' ) |
---|
[214] | 184 | |
---|
[858] | 185 | JOB_TIMEOUT = cfg.getint( 'DEFAULT', 'JOB_TIMEOUT' ) |
---|
[295] | 186 | |
---|
[858] | 187 | DAEMONIZE = cfg.getboolean( 'DEFAULT', 'DAEMONIZE' ) |
---|
[214] | 188 | |
---|
[770] | 189 | return True |
---|
[214] | 190 | |
---|
[17] | 191 | # What XML data types not to store |
---|
[13] | 192 | # |
---|
[17] | 193 | UNSUPPORTED_ARCHIVE_TYPES = [ 'string' ] |
---|
[9] | 194 | |
---|
[47] | 195 | # Maximum time (in seconds) a parsethread may run |
---|
| 196 | # |
---|
| 197 | PARSE_TIMEOUT = 60 |
---|
| 198 | |
---|
| 199 | # Maximum time (in seconds) a storethread may run |
---|
| 200 | # |
---|
| 201 | STORE_TIMEOUT = 360 |
---|
| 202 | |
---|
[8] | 203 | """ |
---|
[224] | 204 | The Job Archiving Daemon |
---|
[8] | 205 | """ |
---|
| 206 | |
---|
[214] | 207 | from types import * |
---|
| 208 | |
---|
| 209 | import xml.sax, xml.sax.handler, socket, string, os, os.path, time, thread, threading, random, re |
---|
| 210 | |
---|
[486] | 211 | try: |
---|
[773] | 212 | import psycopg2 |
---|
[486] | 213 | |
---|
| 214 | except ImportError, details: |
---|
| 215 | |
---|
[773] | 216 | print "FATAL ERROR: psycopg2 python module not found" |
---|
[770] | 217 | sys.exit( 1 ) |
---|
[486] | 218 | |
---|
[379] | 219 | class InitVars: |
---|
| 220 | Vars = {} |
---|
| 221 | |
---|
| 222 | def __init__(self, **key_arg): |
---|
| 223 | for (key, value) in key_arg.items(): |
---|
| 224 | if value: |
---|
| 225 | self.Vars[key] = value |
---|
| 226 | else: |
---|
| 227 | self.Vars[key] = None |
---|
| 228 | |
---|
| 229 | def __call__(self, *key): |
---|
| 230 | key = "%s" % key |
---|
| 231 | return self.Vars[key] |
---|
| 232 | |
---|
| 233 | def __getitem__(self, key): |
---|
| 234 | return self.Vars[key] |
---|
| 235 | |
---|
| 236 | def __repr__(self): |
---|
| 237 | return repr(self.Vars) |
---|
| 238 | |
---|
| 239 | def keys(self): |
---|
| 240 | barf = map(None, self.Vars.keys()) |
---|
| 241 | return barf |
---|
| 242 | |
---|
| 243 | def values(self): |
---|
| 244 | barf = map(None, self.Vars.values()) |
---|
| 245 | return barf |
---|
| 246 | |
---|
| 247 | def has_key(self, key): |
---|
| 248 | if self.Vars.has_key(key): |
---|
| 249 | return 1 |
---|
| 250 | else: |
---|
| 251 | return 0 |
---|
| 252 | |
---|
| 253 | class DBError(Exception): |
---|
| 254 | def __init__(self, msg=''): |
---|
| 255 | self.msg = msg |
---|
| 256 | Exception.__init__(self, msg) |
---|
| 257 | def __repr__(self): |
---|
| 258 | return self.msg |
---|
| 259 | __str__ = __repr__ |
---|
| 260 | |
---|
| 261 | # |
---|
| 262 | # Class to connect to a database |
---|
| 263 | # and return the queury in a list or dictionairy. |
---|
| 264 | # |
---|
| 265 | class DB: |
---|
[773] | 266 | def __init__(self, db_vars): |
---|
[379] | 267 | |
---|
[773] | 268 | self.dict = db_vars |
---|
[379] | 269 | |
---|
[773] | 270 | if self.dict.has_key('User'): |
---|
| 271 | self.user = self.dict['User'] |
---|
| 272 | else: |
---|
| 273 | self.user = 'postgres' |
---|
[379] | 274 | |
---|
[773] | 275 | if self.dict.has_key('Host'): |
---|
| 276 | self.host = self.dict['Host'] |
---|
| 277 | else: |
---|
| 278 | self.host = 'localhost' |
---|
[379] | 279 | |
---|
[773] | 280 | if self.dict.has_key('Password'): |
---|
| 281 | self.passwd = self.dict['Password'] |
---|
| 282 | else: |
---|
| 283 | self.passwd = '' |
---|
[379] | 284 | |
---|
[773] | 285 | if self.dict.has_key('DataBaseName'): |
---|
| 286 | self.db = self.dict['DataBaseName'] |
---|
| 287 | else: |
---|
| 288 | self.db = 'jobarchive' |
---|
[379] | 289 | |
---|
[773] | 290 | # connect_string = 'host:port:database:user:password: |
---|
| 291 | dsn = "host='%s' dbname='%s' user='%s' password='%s'" %(self.host, self.db, self.user, self.passwd) |
---|
[379] | 292 | |
---|
[773] | 293 | try: |
---|
| 294 | self.SQL = psycopg2.connect(dsn) |
---|
| 295 | except psycopg2.Error, details: |
---|
| 296 | str = "%s" %details |
---|
| 297 | raise DBError(str) |
---|
[379] | 298 | |
---|
[773] | 299 | def __repr__(self): |
---|
| 300 | return repr(self.result) |
---|
[379] | 301 | |
---|
[773] | 302 | def __nonzero__(self): |
---|
| 303 | return not(self.result == None) |
---|
[379] | 304 | |
---|
[773] | 305 | def __len__(self): |
---|
| 306 | return len(self.result) |
---|
[379] | 307 | |
---|
[773] | 308 | def __getitem__(self,i): |
---|
| 309 | return self.result[i] |
---|
[379] | 310 | |
---|
[773] | 311 | def __getslice__(self,i,j): |
---|
| 312 | return self.result[i:j] |
---|
[379] | 313 | |
---|
[773] | 314 | def Get(self, q_str): |
---|
| 315 | c = self.SQL.cursor() |
---|
| 316 | try: |
---|
| 317 | c.execute(q_str) |
---|
| 318 | result = c.fetchall() |
---|
| 319 | except psycopg2.Error, details: |
---|
| 320 | c.close() |
---|
| 321 | str = "%s" %details |
---|
| 322 | raise DBError(str) |
---|
[379] | 323 | |
---|
[773] | 324 | c.close() |
---|
| 325 | return result |
---|
[379] | 326 | |
---|
[773] | 327 | def Set(self, q_str): |
---|
| 328 | c = self.SQL.cursor() |
---|
| 329 | try: |
---|
| 330 | c.execute(q_str) |
---|
[379] | 331 | |
---|
[773] | 332 | except psycopg2.Error, details: |
---|
| 333 | c.close() |
---|
| 334 | str = "%s" %details |
---|
| 335 | raise DBError(str) |
---|
[379] | 336 | |
---|
[773] | 337 | c.close() |
---|
[774] | 338 | return True |
---|
[379] | 339 | |
---|
[773] | 340 | def Commit(self): |
---|
[379] | 341 | |
---|
[792] | 342 | return self.SQL.commit() |
---|
| 343 | |
---|
| 344 | def Rollback( self ): |
---|
| 345 | |
---|
| 346 | return self.SQL.rollback() |
---|
| 347 | |
---|
[84] | 348 | class DataSQLStore: |
---|
| 349 | |
---|
[770] | 350 | db_vars = None |
---|
| 351 | dbc = None |
---|
[84] | 352 | |
---|
[770] | 353 | def __init__( self, hostname, database ): |
---|
[84] | 354 | |
---|
[774] | 355 | global JOB_SQL_USER, JOB_SQL_PASSWORD |
---|
| 356 | |
---|
[770] | 357 | self.db_vars = InitVars(DataBaseName=database, |
---|
[774] | 358 | User=JOB_SQL_USER, |
---|
[770] | 359 | Host=hostname, |
---|
[774] | 360 | Password=JOB_SQL_PASSWORD, |
---|
[770] | 361 | Dictionary='true') |
---|
[84] | 362 | |
---|
[770] | 363 | try: |
---|
| 364 | self.dbc = DB(self.db_vars) |
---|
| 365 | except DBError, details: |
---|
| 366 | debug_msg( 0, 'FATAL ERROR: Unable to connect to database!: ' +str(details) ) |
---|
| 367 | sys.exit(1) |
---|
[84] | 368 | |
---|
[770] | 369 | def setDatabase(self, statement): |
---|
[792] | 370 | |
---|
[770] | 371 | ret = self.doDatabase('set', statement) |
---|
| 372 | return ret |
---|
| 373 | |
---|
| 374 | def getDatabase(self, statement): |
---|
[792] | 375 | |
---|
[770] | 376 | ret = self.doDatabase('get', statement) |
---|
| 377 | return ret |
---|
[84] | 378 | |
---|
[792] | 379 | def doCommit( self ): |
---|
| 380 | |
---|
| 381 | return self.dbc.Commit() |
---|
| 382 | |
---|
| 383 | def doRollback( self ): |
---|
| 384 | |
---|
| 385 | return self.dbc.Rollback() |
---|
| 386 | |
---|
[770] | 387 | def doDatabase(self, type, statement): |
---|
[84] | 388 | |
---|
[770] | 389 | debug_msg( 10, 'doDatabase(): %s: %s' %(type, statement) ) |
---|
| 390 | try: |
---|
| 391 | if type == 'set': |
---|
| 392 | result = self.dbc.Set( statement ) |
---|
| 393 | elif type == 'get': |
---|
| 394 | result = self.dbc.Get( statement ) |
---|
| 395 | |
---|
| 396 | except DBError, detail: |
---|
| 397 | operation = statement.split(' ')[0] |
---|
[792] | 398 | debug_msg( 0, 'ERROR: ' +operation+ ' on database failed while doing ['+statement+'] full msg: '+str(detail) ) |
---|
| 399 | return False |
---|
[84] | 400 | |
---|
[770] | 401 | debug_msg( 10, 'doDatabase(): result: %s' %(result) ) |
---|
| 402 | return result |
---|
[84] | 403 | |
---|
[770] | 404 | def getJobNodeId( self, job_id, node_id ): |
---|
[191] | 405 | |
---|
[770] | 406 | id = self.getDatabase( "SELECT job_id,node_id FROM job_nodes WHERE job_id = '%s' AND node_id = '%s'" %(job_id, node_id) ) |
---|
[792] | 407 | if not id: |
---|
| 408 | return False |
---|
| 409 | |
---|
[770] | 410 | if len( id ) > 0: |
---|
[191] | 411 | |
---|
[770] | 412 | if len( id[0] ) > 0 and id[0] != '': |
---|
| 413 | |
---|
[792] | 414 | return True |
---|
[191] | 415 | |
---|
[792] | 416 | return False |
---|
[191] | 417 | |
---|
[770] | 418 | def getNodeId( self, hostname ): |
---|
[84] | 419 | |
---|
[770] | 420 | id = self.getDatabase( "SELECT node_id FROM nodes WHERE node_hostname = '%s'" %hostname ) |
---|
[84] | 421 | |
---|
[770] | 422 | if len( id ) > 0: |
---|
[84] | 423 | |
---|
[770] | 424 | id = id[0][0] |
---|
[89] | 425 | |
---|
[770] | 426 | return id |
---|
| 427 | else: |
---|
| 428 | return None |
---|
[84] | 429 | |
---|
[770] | 430 | def getNodeIds( self, hostnames ): |
---|
[84] | 431 | |
---|
[770] | 432 | ids = [ ] |
---|
[84] | 433 | |
---|
[770] | 434 | for node in hostnames: |
---|
[84] | 435 | |
---|
[770] | 436 | id = self.getNodeId( node ) |
---|
[84] | 437 | |
---|
[770] | 438 | if id: |
---|
| 439 | ids.append( id ) |
---|
[84] | 440 | |
---|
[770] | 441 | return ids |
---|
[84] | 442 | |
---|
[770] | 443 | def getJobId( self, jobid ): |
---|
[84] | 444 | |
---|
[770] | 445 | id = self.getDatabase( "SELECT job_id FROM jobs WHERE job_id = '%s'" %jobid ) |
---|
[84] | 446 | |
---|
[770] | 447 | if id: |
---|
| 448 | id = id[0][0] |
---|
[84] | 449 | |
---|
[770] | 450 | return id |
---|
| 451 | else: |
---|
| 452 | return None |
---|
[84] | 453 | |
---|
[770] | 454 | def addJob( self, job_id, jobattrs ): |
---|
[84] | 455 | |
---|
[770] | 456 | if not self.getJobId( job_id ): |
---|
[84] | 457 | |
---|
[792] | 458 | return self.mutateJob( 'insert', job_id, jobattrs ) |
---|
[770] | 459 | else: |
---|
[792] | 460 | return self.mutateJob( 'update', job_id, jobattrs ) |
---|
[84] | 461 | |
---|
[770] | 462 | def mutateJob( self, action, job_id, jobattrs ): |
---|
[84] | 463 | |
---|
[782] | 464 | job_values = [ 'name', 'queue', 'owner', 'requested_time', 'requested_memory', 'ppn', 'status', 'start_timestamp', 'stop_timestamp' ] |
---|
[84] | 465 | |
---|
[782] | 466 | insert_col_str = 'job_id' |
---|
| 467 | insert_val_str = "'%s'" %job_id |
---|
| 468 | update_str = None |
---|
[84] | 469 | |
---|
[770] | 470 | debug_msg( 10, 'mutateJob(): %s %s' %(action,job_id)) |
---|
[84] | 471 | |
---|
[770] | 472 | ids = [ ] |
---|
[99] | 473 | |
---|
[770] | 474 | for valname, value in jobattrs.items(): |
---|
[84] | 475 | |
---|
[770] | 476 | if valname in job_values and value != '': |
---|
[84] | 477 | |
---|
[770] | 478 | column_name = 'job_' + valname |
---|
[84] | 479 | |
---|
[770] | 480 | if action == 'insert': |
---|
[84] | 481 | |
---|
[770] | 482 | if not insert_col_str: |
---|
| 483 | insert_col_str = column_name |
---|
| 484 | else: |
---|
| 485 | insert_col_str = insert_col_str + ',' + column_name |
---|
[84] | 486 | |
---|
[770] | 487 | if not insert_val_str: |
---|
| 488 | insert_val_str = value |
---|
| 489 | else: |
---|
| 490 | insert_val_str = insert_val_str + ",'%s'" %value |
---|
[84] | 491 | |
---|
[770] | 492 | elif action == 'update': |
---|
| 493 | |
---|
| 494 | if not update_str: |
---|
| 495 | update_str = "%s='%s'" %(column_name, value) |
---|
| 496 | else: |
---|
| 497 | update_str = update_str + ",%s='%s'" %(column_name, value) |
---|
[84] | 498 | |
---|
[770] | 499 | elif valname == 'nodes' and value: |
---|
[84] | 500 | |
---|
[770] | 501 | node_valid = 1 |
---|
[190] | 502 | |
---|
[770] | 503 | if len(value) == 1: |
---|
| 504 | |
---|
| 505 | if jobattrs['status'] == 'Q': |
---|
[190] | 506 | |
---|
[770] | 507 | node_valid = 0 |
---|
[190] | 508 | |
---|
[770] | 509 | else: |
---|
[190] | 510 | |
---|
[770] | 511 | node_valid = 0 |
---|
[190] | 512 | |
---|
[770] | 513 | for node_char in str(value[0]): |
---|
[190] | 514 | |
---|
[770] | 515 | if string.find( string.digits, node_char ) != -1 and not node_valid: |
---|
[190] | 516 | |
---|
[770] | 517 | node_valid = 1 |
---|
[84] | 518 | |
---|
[770] | 519 | if node_valid: |
---|
[191] | 520 | |
---|
[770] | 521 | ids = self.addNodes( value, jobattrs['domain'] ) |
---|
[191] | 522 | |
---|
[770] | 523 | if action == 'insert': |
---|
[84] | 524 | |
---|
[792] | 525 | db_ret = self.setDatabase( "INSERT INTO jobs ( %s ) VALUES ( %s )" %( insert_col_str, insert_val_str ) ) |
---|
[86] | 526 | |
---|
[770] | 527 | elif action == 'update': |
---|
[84] | 528 | |
---|
[792] | 529 | db_ret = self.setDatabase( "UPDATE jobs SET %s WHERE job_id='%s'" %(update_str, job_id) ) |
---|
[84] | 530 | |
---|
[770] | 531 | if len( ids ) > 0: |
---|
| 532 | self.addJobNodes( job_id, ids ) |
---|
[190] | 533 | |
---|
[792] | 534 | return db_ret |
---|
| 535 | |
---|
[770] | 536 | def addNodes( self, hostnames, domain ): |
---|
[84] | 537 | |
---|
[770] | 538 | ids = [ ] |
---|
[98] | 539 | |
---|
[770] | 540 | for node in hostnames: |
---|
[84] | 541 | |
---|
[770] | 542 | node = '%s.%s' %( node, domain ) |
---|
| 543 | id = self.getNodeId( node ) |
---|
| 544 | |
---|
| 545 | if not id: |
---|
| 546 | self.setDatabase( "INSERT INTO nodes ( node_hostname ) VALUES ( '%s' )" %node ) |
---|
| 547 | id = self.getNodeId( node ) |
---|
[84] | 548 | |
---|
[770] | 549 | ids.append( id ) |
---|
[98] | 550 | |
---|
[770] | 551 | return ids |
---|
[98] | 552 | |
---|
[770] | 553 | def addJobNodes( self, jobid, nodes ): |
---|
[86] | 554 | |
---|
[770] | 555 | for node in nodes: |
---|
[86] | 556 | |
---|
[770] | 557 | if not self.getJobNodeId( jobid, node ): |
---|
[191] | 558 | |
---|
[770] | 559 | self.addJobNode( jobid, node ) |
---|
[191] | 560 | |
---|
[770] | 561 | def addJobNode( self, jobid, nodeid ): |
---|
[84] | 562 | |
---|
[774] | 563 | self.setDatabase( "INSERT INTO job_nodes (job_id,node_id) VALUES ( '%s',%s )" %(jobid, nodeid) ) |
---|
[84] | 564 | |
---|
[770] | 565 | def storeJobInfo( self, jobid, jobattrs ): |
---|
[84] | 566 | |
---|
[792] | 567 | return self.addJob( jobid, jobattrs ) |
---|
[84] | 568 | |
---|
[857] | 569 | def checkTimedoutJobs( self ): |
---|
[295] | 570 | |
---|
[857] | 571 | debug_msg( 1, 'Housekeeping: checking database for timed out jobs..' ) |
---|
| 572 | |
---|
[770] | 573 | # Locate all jobs in the database that are not set to finished |
---|
| 574 | # |
---|
| 575 | q = "SELECT * from jobs WHERE job_status != 'F'" |
---|
[295] | 576 | |
---|
[770] | 577 | r = self.getDatabase( q ) |
---|
[295] | 578 | |
---|
[770] | 579 | if len( r ) == 0: |
---|
[295] | 580 | |
---|
[770] | 581 | return None |
---|
[295] | 582 | |
---|
[857] | 583 | timeoutjobs = [ ] |
---|
[295] | 584 | |
---|
[857] | 585 | jobtimeout_sec = JOB_TIMEOUT * (60 * 60) |
---|
| 586 | cur_time = time.time() |
---|
[295] | 587 | |
---|
[770] | 588 | for row in r: |
---|
[295] | 589 | |
---|
[857] | 590 | job_id = row[0] |
---|
| 591 | job_requested_time = row[4] |
---|
| 592 | job_status = row[7] |
---|
| 593 | job_start_timestamp = row[8] |
---|
[295] | 594 | |
---|
[770] | 595 | # If it was set to queued and we didn't see it started |
---|
| 596 | # there's not point in keeping it around |
---|
| 597 | # |
---|
[857] | 598 | if job_status == 'R' and job_start_timestamp: |
---|
[295] | 599 | |
---|
[770] | 600 | start_timestamp = int( job_start_timestamp ) |
---|
[295] | 601 | |
---|
[770] | 602 | # If it was set to running longer than JOB_TIMEOUT |
---|
| 603 | # close the job: it probably finished while we were not running |
---|
| 604 | # |
---|
| 605 | if ( cur_time - start_timestamp ) > jobtimeout_sec: |
---|
[295] | 606 | |
---|
[770] | 607 | if job_requested_time: |
---|
[295] | 608 | |
---|
[770] | 609 | rtime_epoch = reqtime2epoch( job_requested_time ) |
---|
| 610 | else: |
---|
| 611 | rtime_epoch = None |
---|
| 612 | |
---|
| 613 | timeoutjobs.append( (job_id, job_start_timestamp, rtime_epoch) ) |
---|
[295] | 614 | |
---|
[857] | 615 | debug_msg( 1, 'Housekeeping: Found ' + str( len( timeoutjobs ) ) + ' timed out jobs in database: closing entries' ) |
---|
[295] | 616 | |
---|
[857] | 617 | ret_jobids_clean = [ ] |
---|
[295] | 618 | |
---|
[770] | 619 | # Close these jobs in the database |
---|
| 620 | # update the stop_timestamp to: start_timestamp + requested wallclock |
---|
| 621 | # and set state: finished |
---|
| 622 | # |
---|
| 623 | for j in timeoutjobs: |
---|
[295] | 624 | |
---|
[770] | 625 | ( i, s, r ) = j |
---|
[295] | 626 | |
---|
[770] | 627 | if r: |
---|
| 628 | new_end_timestamp = int( s ) + r |
---|
[295] | 629 | |
---|
[857] | 630 | q = "UPDATE jobs SET job_status='F',job_stop_timestamp = '" + str( new_end_timestamp ) + "' WHERE job_id = '" + str(i) + "'" |
---|
| 631 | self.setDatabase( q ) |
---|
| 632 | else: |
---|
| 633 | |
---|
| 634 | # Requested walltime unknown: cannot guess end time: sorry delete them |
---|
| 635 | q = "DELETE FROM jobs WHERE job_id = '" + str( i ) + "'" |
---|
| 636 | self.setDatabase( q ) |
---|
| 637 | |
---|
| 638 | ret_jobids_clean.append( i ) |
---|
| 639 | |
---|
| 640 | debug_msg( 1, 'Housekeeping: done.' ) |
---|
| 641 | |
---|
| 642 | return ret_jobids_clean |
---|
| 643 | |
---|
| 644 | def checkStaleJobs( self ): |
---|
| 645 | |
---|
| 646 | debug_msg( 1, 'Housekeeping: checking database for stale jobs..' ) |
---|
| 647 | |
---|
| 648 | # Locate all jobs in the database that are not set to finished |
---|
| 649 | # |
---|
| 650 | q = "SELECT * from jobs WHERE job_status != 'F'" |
---|
| 651 | |
---|
| 652 | r = self.getDatabase( q ) |
---|
| 653 | |
---|
| 654 | if len( r ) == 0: |
---|
| 655 | |
---|
| 656 | return None |
---|
| 657 | |
---|
| 658 | cleanjobs = [ ] |
---|
| 659 | |
---|
| 660 | cur_time = time.time() |
---|
| 661 | |
---|
| 662 | for row in r: |
---|
| 663 | |
---|
| 664 | job_id = row[0] |
---|
| 665 | job_requested_time = row[4] |
---|
| 666 | job_status = row[7] |
---|
| 667 | job_start_timestamp = row[8] |
---|
| 668 | |
---|
| 669 | # If it was set to queued and we didn't see it started |
---|
| 670 | # there's not point in keeping it around |
---|
| 671 | # |
---|
| 672 | if job_status == 'Q' or not job_start_timestamp: |
---|
| 673 | |
---|
| 674 | cleanjobs.append( job_id ) |
---|
| 675 | |
---|
| 676 | debug_msg( 1, 'Housekeeping: Found ' + str( len( cleanjobs ) ) + ' stale jobs in database: deleting entries' ) |
---|
| 677 | |
---|
| 678 | # Purge these from database |
---|
| 679 | # |
---|
| 680 | for j in cleanjobs: |
---|
| 681 | |
---|
| 682 | q = "DELETE FROM jobs WHERE job_id = '" + str( j ) + "'" |
---|
[770] | 683 | self.setDatabase( q ) |
---|
[295] | 684 | |
---|
[857] | 685 | debug_msg( 1, 'Housekeeping: done.' ) |
---|
| 686 | |
---|
| 687 | return cleanjobs |
---|
| 688 | |
---|
[37] | 689 | class RRDMutator: |
---|
[770] | 690 | """A class for performing RRD mutations""" |
---|
[37] | 691 | |
---|
[770] | 692 | binary = None |
---|
[37] | 693 | |
---|
[770] | 694 | def __init__( self, binary=None ): |
---|
| 695 | """Set alternate binary if supplied""" |
---|
[37] | 696 | |
---|
[770] | 697 | if binary: |
---|
| 698 | self.binary = binary |
---|
[37] | 699 | |
---|
[770] | 700 | def create( self, filename, args ): |
---|
| 701 | """Create a new rrd with args""" |
---|
[63] | 702 | |
---|
[770] | 703 | global MODRRDTOOL |
---|
[37] | 704 | |
---|
[770] | 705 | if MODRRDTOOL: |
---|
| 706 | return self.perform( 'create', filename, args ) |
---|
| 707 | else: |
---|
| 708 | return self.perform( 'create', '"' + filename + '"', args ) |
---|
[375] | 709 | |
---|
[770] | 710 | def update( self, filename, args ): |
---|
| 711 | """Update a rrd with args""" |
---|
[63] | 712 | |
---|
[770] | 713 | global MODRRDTOOL |
---|
[37] | 714 | |
---|
[770] | 715 | if MODRRDTOOL: |
---|
| 716 | return self.perform( 'update', filename, args ) |
---|
| 717 | else: |
---|
| 718 | return self.perform( 'update', '"' + filename + '"', args ) |
---|
[375] | 719 | |
---|
[770] | 720 | def grabLastUpdate( self, filename ): |
---|
| 721 | """Determine the last update time of filename rrd""" |
---|
[42] | 722 | |
---|
[770] | 723 | global MODRRDTOOL |
---|
[375] | 724 | |
---|
[770] | 725 | last_update = 0 |
---|
[42] | 726 | |
---|
[770] | 727 | # Use the py-rrdtool module if it's available on this system |
---|
| 728 | # |
---|
| 729 | if MODRRDTOOL: |
---|
[53] | 730 | |
---|
[770] | 731 | debug_msg( 8, 'rrdtool.info( ' + filename + ' )' ) |
---|
[42] | 732 | |
---|
[770] | 733 | rrd_header = { } |
---|
[292] | 734 | |
---|
[770] | 735 | try: |
---|
| 736 | rrd_header = rrdtool.info( filename ) |
---|
| 737 | except rrdtool.error, msg: |
---|
| 738 | debug_msg( 8, str( msg ) ) |
---|
[375] | 739 | |
---|
[770] | 740 | if rrd_header.has_key( 'last_update' ): |
---|
| 741 | return last_update |
---|
| 742 | else: |
---|
| 743 | return 0 |
---|
[375] | 744 | |
---|
[770] | 745 | # For backwards compatiblity: use the rrdtool binary if py-rrdtool is unavailable |
---|
| 746 | # DEPRECATED (slow!) |
---|
| 747 | # |
---|
| 748 | else: |
---|
| 749 | debug_msg( 8, self.binary + ' info ' + filename ) |
---|
[42] | 750 | |
---|
[770] | 751 | my_pipe = os.popen( self.binary + ' info "' + filename + '"' ) |
---|
[375] | 752 | |
---|
[770] | 753 | for line in my_pipe.readlines(): |
---|
[375] | 754 | |
---|
[770] | 755 | if line.find( 'last_update') != -1: |
---|
[375] | 756 | |
---|
[770] | 757 | last_update = line.split( ' = ' )[1] |
---|
[375] | 758 | |
---|
[770] | 759 | if my_pipe: |
---|
[375] | 760 | |
---|
[770] | 761 | my_pipe.close() |
---|
[375] | 762 | |
---|
[770] | 763 | if last_update: |
---|
| 764 | return last_update |
---|
| 765 | else: |
---|
| 766 | return 0 |
---|
[375] | 767 | |
---|
| 768 | |
---|
[770] | 769 | def perform( self, action, filename, args ): |
---|
| 770 | """Perform action on rrd filename with args""" |
---|
[37] | 771 | |
---|
[770] | 772 | global MODRRDTOOL |
---|
[375] | 773 | |
---|
[770] | 774 | arg_string = None |
---|
[37] | 775 | |
---|
[770] | 776 | if type( args ) is not ListType: |
---|
| 777 | debug_msg( 8, 'Arguments needs to be of type List' ) |
---|
| 778 | return 1 |
---|
[40] | 779 | |
---|
[770] | 780 | for arg in args: |
---|
[37] | 781 | |
---|
[770] | 782 | if not arg_string: |
---|
[37] | 783 | |
---|
[770] | 784 | arg_string = arg |
---|
| 785 | else: |
---|
| 786 | arg_string = arg_string + ' ' + arg |
---|
[37] | 787 | |
---|
[770] | 788 | if MODRRDTOOL: |
---|
[37] | 789 | |
---|
[770] | 790 | debug_msg( 8, 'rrdtool.' + action + "( " + filename + ' ' + arg_string + ")" ) |
---|
[292] | 791 | |
---|
[770] | 792 | try: |
---|
| 793 | debug_msg( 8, "filename '" + str(filename) + "' type "+ str(type(filename)) + " args " + str( args ) ) |
---|
[37] | 794 | |
---|
[770] | 795 | if action == 'create': |
---|
[146] | 796 | |
---|
[770] | 797 | rrdtool.create( str( filename ), *args ) |
---|
[37] | 798 | |
---|
[770] | 799 | elif action == 'update': |
---|
[37] | 800 | |
---|
[770] | 801 | rrdtool.update( str( filename ), *args ) |
---|
[365] | 802 | |
---|
[770] | 803 | except rrdtool.error, msg: |
---|
[365] | 804 | |
---|
[770] | 805 | error_msg = str( msg ) |
---|
| 806 | debug_msg( 8, error_msg ) |
---|
| 807 | return 1 |
---|
[375] | 808 | |
---|
[770] | 809 | else: |
---|
[375] | 810 | |
---|
[770] | 811 | debug_msg( 8, self.binary + ' ' + action + ' ' + filename + ' ' + arg_string ) |
---|
[375] | 812 | |
---|
[770] | 813 | cmd = os.popen( self.binary + ' ' + action + ' ' + filename + ' ' + arg_string ) |
---|
| 814 | lines = cmd.readlines() |
---|
[375] | 815 | |
---|
[770] | 816 | cmd.close() |
---|
[375] | 817 | |
---|
[770] | 818 | for line in lines: |
---|
[375] | 819 | |
---|
[770] | 820 | if line.find( 'ERROR' ) != -1: |
---|
[375] | 821 | |
---|
[770] | 822 | error_msg = string.join( line.split( ' ' )[1:] ) |
---|
| 823 | debug_msg( 8, error_msg ) |
---|
| 824 | return 1 |
---|
[375] | 825 | |
---|
[770] | 826 | return 0 |
---|
[37] | 827 | |
---|
[78] | 828 | class XMLProcessor: |
---|
[770] | 829 | """Skeleton class for XML processor's""" |
---|
[78] | 830 | |
---|
[770] | 831 | def run( self ): |
---|
| 832 | """Do main processing of XML here""" |
---|
[78] | 833 | |
---|
[770] | 834 | pass |
---|
[78] | 835 | |
---|
[782] | 836 | class JobXMLProcessor( XMLProcessor ): |
---|
[770] | 837 | """Main class for processing XML and acting with it""" |
---|
[78] | 838 | |
---|
[770] | 839 | def __init__( self, XMLSource, DataStore ): |
---|
| 840 | """Setup initial XML connection and handlers""" |
---|
[78] | 841 | |
---|
[782] | 842 | self.myXMLSource = XMLSource |
---|
| 843 | self.myXMLHandler = JobXMLHandler( DataStore ) |
---|
| 844 | self.myXMLError = XMLErrorHandler() |
---|
[78] | 845 | |
---|
[782] | 846 | self.config = GangliaConfigParser( GMETAD_CONF ) |
---|
[287] | 847 | |
---|
[782] | 848 | self.kill_thread = False |
---|
| 849 | |
---|
| 850 | def killThread( self ): |
---|
| 851 | |
---|
| 852 | self.kill_thread = True |
---|
| 853 | |
---|
[770] | 854 | def run( self ): |
---|
| 855 | """Main XML processing""" |
---|
[78] | 856 | |
---|
[782] | 857 | debug_msg( 1, 'job_xml_thread(): started.' ) |
---|
[87] | 858 | |
---|
[770] | 859 | while( 1 ): |
---|
[78] | 860 | |
---|
[782] | 861 | debug_msg( 1, 'job_xml_thread(): Retrieving XML data..' ) |
---|
[176] | 862 | |
---|
[770] | 863 | my_data = self.myXMLSource.getData() |
---|
[287] | 864 | |
---|
[782] | 865 | debug_msg( 1, 'job_xml_thread(): Done retrieving: data size %d' %len(my_data) ) |
---|
[469] | 866 | |
---|
[770] | 867 | if my_data: |
---|
[782] | 868 | debug_msg( 1, 'job_xml_thread(): Parsing XML..' ) |
---|
[469] | 869 | |
---|
[770] | 870 | xml.sax.parseString( my_data, self.myXMLHandler, self.myXMLError ) |
---|
[469] | 871 | |
---|
[926] | 872 | if self.myXMLError.isFatal(): |
---|
| 873 | |
---|
| 874 | sys.exit( 1 ) |
---|
| 875 | |
---|
[782] | 876 | debug_msg( 1, 'job_xml_thread(): Done parsing.' ) |
---|
[774] | 877 | else: |
---|
[782] | 878 | debug_msg( 1, 'job_xml_thread(): Got no data.' ) |
---|
[774] | 879 | |
---|
[782] | 880 | if self.kill_thread: |
---|
| 881 | |
---|
| 882 | debug_msg( 1, 'job_xml_thread(): killed.' ) |
---|
| 883 | return None |
---|
[770] | 884 | |
---|
[782] | 885 | debug_msg( 1, 'job_xml_thread(): Sleeping.. (%ss)' %(str( self.config.getLowestInterval() ) ) ) |
---|
[770] | 886 | time.sleep( self.config.getLowestInterval() ) |
---|
[78] | 887 | |
---|
[782] | 888 | class JobXMLHandler( xml.sax.handler.ContentHandler ): |
---|
| 889 | """Parse Job's jobinfo XML from our plugin""" |
---|
[63] | 890 | |
---|
[770] | 891 | def __init__( self, datastore ): |
---|
[84] | 892 | |
---|
[782] | 893 | self.ds = datastore |
---|
| 894 | self.jobs_processed = [ ] |
---|
| 895 | self.jobs_to_store = [ ] |
---|
| 896 | self.jobAttrs = { } |
---|
| 897 | self.jobAttrsSaved = { } |
---|
| 898 | |
---|
[857] | 899 | self.iteration = 0 |
---|
| 900 | |
---|
| 901 | self.ds.checkTimedoutJobs() |
---|
| 902 | self.ds.checkStaleJobs() |
---|
| 903 | |
---|
[774] | 904 | debug_msg( 1, "XML: Handler created" ) |
---|
[84] | 905 | |
---|
[770] | 906 | def startDocument( self ): |
---|
[183] | 907 | |
---|
[782] | 908 | self.jobs_processed = [ ] |
---|
| 909 | self.heartbeat = 0 |
---|
| 910 | self.elementct = 0 |
---|
[857] | 911 | self.iteration = self.iteration + 1 |
---|
[782] | 912 | |
---|
[857] | 913 | if self.iteration > 20: |
---|
[183] | 914 | |
---|
[857] | 915 | timedout_jobs = self.ds.checkTimedoutJobs() |
---|
| 916 | self.iteration = 0 |
---|
| 917 | |
---|
[925] | 918 | if timedout_jobs != None: |
---|
[857] | 919 | |
---|
[925] | 920 | for j in timedout_jobs: |
---|
[857] | 921 | |
---|
[925] | 922 | del self.jobAttrs[ j ] |
---|
| 923 | del self.jobAttrsSaved[ j ] |
---|
| 924 | |
---|
[857] | 925 | debug_msg( 1, "XML: Start document: iteration %s" %str(self.iteration) ) |
---|
| 926 | |
---|
[770] | 927 | def startElement( self, name, attrs ): |
---|
| 928 | """ |
---|
| 929 | This XML will be all gmetric XML |
---|
| 930 | so there will be no specific start/end element |
---|
| 931 | just one XML statement with all info |
---|
| 932 | """ |
---|
[782] | 933 | |
---|
[928] | 934 | global ARCHIVE_DATASOURCES |
---|
| 935 | |
---|
[770] | 936 | jobinfo = { } |
---|
[63] | 937 | |
---|
[770] | 938 | self.elementct += 1 |
---|
[365] | 939 | |
---|
[770] | 940 | if name == 'CLUSTER': |
---|
[63] | 941 | |
---|
[770] | 942 | self.clustername = str( attrs.get( 'NAME', "" ) ) |
---|
[199] | 943 | |
---|
[770] | 944 | elif name == 'METRIC' and self.clustername in ARCHIVE_DATASOURCES: |
---|
[199] | 945 | |
---|
[770] | 946 | metricname = str( attrs.get( 'NAME', "" ) ) |
---|
[63] | 947 | |
---|
[772] | 948 | if metricname == 'zplugin_monarch_heartbeat': |
---|
[782] | 949 | |
---|
[770] | 950 | self.heartbeat = str( attrs.get( 'VAL', "" ) ) |
---|
[63] | 951 | |
---|
[772] | 952 | elif metricname.find( 'zplugin_monarch_job' ) != -1: |
---|
[63] | 953 | |
---|
[782] | 954 | job_id = metricname.split( 'zplugin_monarch_job_' )[1].split( '_' )[1] |
---|
| 955 | val = str( attrs.get( 'VAL', "" ) ) |
---|
[63] | 956 | |
---|
[770] | 957 | valinfo = val.split( ' ' ) |
---|
[63] | 958 | |
---|
[770] | 959 | for myval in valinfo: |
---|
[63] | 960 | |
---|
[770] | 961 | if len( myval.split( '=' ) ) > 1: |
---|
[63] | 962 | |
---|
[782] | 963 | valname = myval.split( '=' )[0] |
---|
| 964 | value = myval.split( '=' )[1] |
---|
[70] | 965 | |
---|
[770] | 966 | if valname == 'nodes': |
---|
[782] | 967 | |
---|
[770] | 968 | value = value.split( ';' ) |
---|
[72] | 969 | |
---|
[770] | 970 | jobinfo[ valname ] = value |
---|
[84] | 971 | |
---|
[782] | 972 | self.jobAttrs[ job_id ] = jobinfo |
---|
[84] | 973 | |
---|
[782] | 974 | self.jobs_processed.append( job_id ) |
---|
[770] | 975 | |
---|
| 976 | def endDocument( self ): |
---|
| 977 | """When all metrics have gone, check if any jobs have finished""" |
---|
[72] | 978 | |
---|
[783] | 979 | jobs_finished = [ ] |
---|
| 980 | |
---|
[782] | 981 | debug_msg( 1, "XML: Processed "+str(self.elementct)+ " elements - found "+str(len(self.jobs_processed))+" jobs" ) |
---|
[365] | 982 | |
---|
[782] | 983 | if self.heartbeat == 0: |
---|
| 984 | return None |
---|
[74] | 985 | |
---|
[782] | 986 | for jobid, jobinfo in self.jobAttrs.items(): |
---|
[102] | 987 | |
---|
[782] | 988 | if jobinfo['reported'] != self.heartbeat: |
---|
[74] | 989 | |
---|
[782] | 990 | if (jobinfo['status'] != 'R'): |
---|
| 991 | debug_msg( 1, 'job %s report time %s does not match current heartbeat %s : ignoring job' %(jobid, jobinfo['reported'], self.heartbeat ) ) |
---|
| 992 | del self.jobAttrs[ jobid ] |
---|
[96] | 993 | |
---|
[782] | 994 | if jobid in self.jobs_to_store: |
---|
| 995 | del self.jobs_to_store[ jobid ] |
---|
| 996 | |
---|
| 997 | continue |
---|
| 998 | |
---|
| 999 | elif jobid not in self.jobs_processed: |
---|
[783] | 1000 | |
---|
[782] | 1001 | # Was running previous heartbeat but not anymore: must be finished |
---|
[770] | 1002 | self.jobAttrs[ jobid ]['status'] = 'F' |
---|
| 1003 | self.jobAttrs[ jobid ]['stop_timestamp'] = str( self.heartbeat ) |
---|
[782] | 1004 | debug_msg( 1, 'job %s appears to have finished' %jobid ) |
---|
[96] | 1005 | |
---|
[783] | 1006 | jobs_finished.append( jobid ) |
---|
| 1007 | |
---|
[770] | 1008 | if not jobid in self.jobs_to_store: |
---|
| 1009 | self.jobs_to_store.append( jobid ) |
---|
[74] | 1010 | |
---|
[782] | 1011 | continue |
---|
[87] | 1012 | |
---|
[782] | 1013 | elif self.jobAttrsSaved.has_key( jobid ): |
---|
[84] | 1014 | |
---|
[783] | 1015 | # This should pretty much never happen, but hey let's be careful |
---|
| 1016 | # Perhaps if someone altered their job while in queue with qalter |
---|
| 1017 | |
---|
[782] | 1018 | if self.jobinfoChanged( jobid, jobinfo ): |
---|
[184] | 1019 | |
---|
[782] | 1020 | self.jobAttrs[ jobid ]['stop_timestamp'] = '' |
---|
| 1021 | self.jobAttrs[ jobid ] = self.setJobAttrs( self.jobAttrs[ jobid ], jobinfo ) |
---|
[184] | 1022 | |
---|
[782] | 1023 | if not jobid in self.jobs_to_store: |
---|
[87] | 1024 | |
---|
[782] | 1025 | self.jobs_to_store.append( jobid ) |
---|
[84] | 1026 | |
---|
[782] | 1027 | debug_msg( 10, 'jobinfo for job %s has changed' %jobid ) |
---|
| 1028 | else: |
---|
[928] | 1029 | debug_msg( 10, 'new job %s' %jobid ) |
---|
[782] | 1030 | |
---|
| 1031 | if not jobid in self.jobs_to_store: |
---|
| 1032 | |
---|
| 1033 | self.jobs_to_store.append( jobid ) |
---|
| 1034 | |
---|
| 1035 | debug_msg( 1, 'job_xml_thread(): Found %s updated jobs.' %len(self.jobs_to_store) ) |
---|
| 1036 | |
---|
[792] | 1037 | failed_store = [ ] |
---|
| 1038 | succes_store = [ ] |
---|
| 1039 | |
---|
[782] | 1040 | if len( self.jobs_to_store ) > 0: |
---|
| 1041 | |
---|
| 1042 | debug_msg( 1, 'job_xml_thread(): Storing jobs to database..' ) |
---|
| 1043 | |
---|
[792] | 1044 | for n in range( 0, len(self.jobs_to_store ) ): |
---|
[782] | 1045 | |
---|
[792] | 1046 | if len( self.jobs_to_store ) == 0: |
---|
| 1047 | break |
---|
| 1048 | |
---|
[782] | 1049 | jobid = self.jobs_to_store.pop( 0 ) |
---|
| 1050 | |
---|
[792] | 1051 | db_ok = self.ds.storeJobInfo( jobid, self.jobAttrs[ jobid ] ) |
---|
[782] | 1052 | |
---|
[792] | 1053 | if not db_ok: |
---|
| 1054 | |
---|
| 1055 | self.ds.doRollback() |
---|
| 1056 | failed_store.append( jobid ) |
---|
| 1057 | continue |
---|
| 1058 | |
---|
| 1059 | self.ds.doCommit() |
---|
| 1060 | succes_store.append( jobid ) |
---|
| 1061 | |
---|
[783] | 1062 | if not jobid in jobs_finished: |
---|
[782] | 1063 | |
---|
[783] | 1064 | self.jobAttrsSaved[ jobid ] = self.jobAttrs[ jobid ] |
---|
| 1065 | |
---|
| 1066 | elif self.jobAttrsSaved.has_key( jobid ): |
---|
| 1067 | |
---|
| 1068 | del self.jobAttrsSaved[ jobid ] |
---|
| 1069 | |
---|
[782] | 1070 | if self.jobAttrs[ jobid ]['status'] == 'F': |
---|
| 1071 | |
---|
| 1072 | del self.jobAttrs[ jobid ] |
---|
| 1073 | |
---|
[792] | 1074 | result_str = 'succesfully stored: %s jobs' %str(len(succes_store)) |
---|
[782] | 1075 | |
---|
[792] | 1076 | if len( failed_store ) > 0: |
---|
| 1077 | result_str = result_str + ' - failed to store: %s jobs - deferred to next interval' %str(len(failed_store)) |
---|
| 1078 | |
---|
| 1079 | debug_msg( 1, 'job_xml_thread(): Done storing. %s' %result_str ) |
---|
| 1080 | |
---|
[782] | 1081 | else: |
---|
| 1082 | debug_msg( 1, 'job_xml_thread(): No jobs to store.' ) |
---|
| 1083 | |
---|
| 1084 | self.jobs_processed = [ ] |
---|
| 1085 | |
---|
[783] | 1086 | # TODO: once in while check database AND self.jobAttrsSaved for stale jobs |
---|
| 1087 | |
---|
[770] | 1088 | def setJobAttrs( self, old, new ): |
---|
| 1089 | """ |
---|
| 1090 | Set new job attributes in old, but not lose existing fields |
---|
| 1091 | if old attributes doesn't have those |
---|
| 1092 | """ |
---|
[82] | 1093 | |
---|
[770] | 1094 | for valname, value in new.items(): |
---|
| 1095 | old[ valname ] = value |
---|
[82] | 1096 | |
---|
[770] | 1097 | return old |
---|
| 1098 | |
---|
[82] | 1099 | |
---|
[782] | 1100 | def jobinfoChanged( self, jobid, jobinfo ): |
---|
[770] | 1101 | """ |
---|
| 1102 | Check if jobinfo has changed from jobattrs[jobid] |
---|
| 1103 | if it's report time is bigger than previous one |
---|
| 1104 | and it is report time is recent (equal to heartbeat) |
---|
| 1105 | """ |
---|
[72] | 1106 | |
---|
[770] | 1107 | ignore_changes = [ 'reported' ] |
---|
[87] | 1108 | |
---|
[782] | 1109 | if self.jobAttrsSaved.has_key( jobid ): |
---|
[73] | 1110 | |
---|
[770] | 1111 | for valname, value in jobinfo.items(): |
---|
[73] | 1112 | |
---|
[770] | 1113 | if valname not in ignore_changes: |
---|
[73] | 1114 | |
---|
[782] | 1115 | if self.jobAttrsSaved[ jobid ].has_key( valname ): |
---|
[73] | 1116 | |
---|
[782] | 1117 | if value != self.jobAttrsSaved[ jobid ][ valname ]: |
---|
[73] | 1118 | |
---|
[782] | 1119 | if jobinfo['reported'] > self.jobAttrsSaved[ jobid ][ 'reported' ]: |
---|
| 1120 | |
---|
| 1121 | debug_msg( 1, "job %s field '%s' changed since saved from: %s to: %s" %( jobid, valname, value, self.jobAttrsSaved[ jobid ][ valname ] ) ) |
---|
| 1122 | |
---|
[770] | 1123 | return True |
---|
[73] | 1124 | |
---|
[770] | 1125 | else: |
---|
[782] | 1126 | debug_msg( 1, "job %s did not have field '%s'" %( jobid, valname ) ) |
---|
[770] | 1127 | return True |
---|
[87] | 1128 | |
---|
[770] | 1129 | return False |
---|
[73] | 1130 | |
---|
[71] | 1131 | class GangliaXMLHandler( xml.sax.handler.ContentHandler ): |
---|
[770] | 1132 | """Parse Ganglia's XML""" |
---|
[3] | 1133 | |
---|
[770] | 1134 | def __init__( self, config, datastore ): |
---|
| 1135 | """Setup initial variables and gather info on existing rrd archive""" |
---|
[63] | 1136 | |
---|
[857] | 1137 | self.config = config |
---|
| 1138 | self.clusters = { } |
---|
| 1139 | self.ds = datastore |
---|
[324] | 1140 | |
---|
[857] | 1141 | debug_msg( 1, 'Housekeeping: checking RRD archive (may take a while)..' ) |
---|
[770] | 1142 | self.gatherClusters() |
---|
[857] | 1143 | debug_msg( 1, 'Housekeeping: RRD check complete.' ) |
---|
[33] | 1144 | |
---|
[770] | 1145 | def gatherClusters( self ): |
---|
| 1146 | """Find all existing clusters in archive dir""" |
---|
[44] | 1147 | |
---|
[928] | 1148 | global ARCHIVE_DATASOURCES |
---|
| 1149 | |
---|
[770] | 1150 | archive_dir = check_dir(ARCHIVE_PATH) |
---|
[44] | 1151 | |
---|
[770] | 1152 | hosts = [ ] |
---|
[44] | 1153 | |
---|
[770] | 1154 | if os.path.exists( archive_dir ): |
---|
[44] | 1155 | |
---|
[770] | 1156 | dirlist = os.listdir( archive_dir ) |
---|
[44] | 1157 | |
---|
[770] | 1158 | for cfgcluster in ARCHIVE_DATASOURCES: |
---|
[369] | 1159 | |
---|
[770] | 1160 | if cfgcluster not in dirlist: |
---|
[369] | 1161 | |
---|
[770] | 1162 | # Autocreate a directory for this cluster |
---|
| 1163 | # assume it is new |
---|
| 1164 | # |
---|
| 1165 | cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), cfgcluster ) |
---|
[369] | 1166 | |
---|
[770] | 1167 | os.mkdir( cluster_dir ) |
---|
[369] | 1168 | |
---|
[770] | 1169 | dirlist.append( cfgcluster ) |
---|
[370] | 1170 | |
---|
[770] | 1171 | for item in dirlist: |
---|
[44] | 1172 | |
---|
[770] | 1173 | clustername = item |
---|
[44] | 1174 | |
---|
[770] | 1175 | if not self.clusters.has_key( clustername ) and clustername in ARCHIVE_DATASOURCES: |
---|
[44] | 1176 | |
---|
[770] | 1177 | self.clusters[ clustername ] = RRDHandler( self.config, clustername ) |
---|
[44] | 1178 | |
---|
[928] | 1179 | debug_msg( 9, 'Found cluster dir: %s' %( clustername ) ) |
---|
[365] | 1180 | |
---|
[928] | 1181 | debug_msg( 9, "Found "+str(len(self.clusters.keys()))+" cluster dirs" ) |
---|
| 1182 | |
---|
[770] | 1183 | def startElement( self, name, attrs ): |
---|
| 1184 | """Memorize appropriate data from xml start tags""" |
---|
[3] | 1185 | |
---|
[928] | 1186 | global ARCHIVE_DATASOURCES |
---|
| 1187 | |
---|
[770] | 1188 | if name == 'GANGLIA_XML': |
---|
[32] | 1189 | |
---|
[782] | 1190 | self.XMLSource = str( attrs.get( 'SOURCE', "" ) ) |
---|
| 1191 | self.gangliaVersion = str( attrs.get( 'VERSION', "" ) ) |
---|
[32] | 1192 | |
---|
[770] | 1193 | debug_msg( 10, 'Found XML data: source %s version %s' %( self.XMLSource, self.gangliaVersion ) ) |
---|
[6] | 1194 | |
---|
[770] | 1195 | elif name == 'GRID': |
---|
[32] | 1196 | |
---|
[770] | 1197 | self.gridName = str( attrs.get( 'NAME', "" ) ) |
---|
[858] | 1198 | self.time = str( attrs.get( 'LOCALTIME', "" ) ) |
---|
[32] | 1199 | |
---|
[770] | 1200 | debug_msg( 10, '`-Grid found: %s' %( self.gridName ) ) |
---|
[6] | 1201 | |
---|
[770] | 1202 | elif name == 'CLUSTER': |
---|
[32] | 1203 | |
---|
[782] | 1204 | self.clusterName = str( attrs.get( 'NAME', "" ) ) |
---|
[770] | 1205 | self.time = str( attrs.get( 'LOCALTIME', "" ) ) |
---|
[32] | 1206 | |
---|
[770] | 1207 | if not self.clusters.has_key( self.clusterName ) and self.clusterName in ARCHIVE_DATASOURCES: |
---|
[32] | 1208 | |
---|
[770] | 1209 | self.clusters[ self.clusterName ] = RRDHandler( self.config, self.clusterName ) |
---|
[33] | 1210 | |
---|
[928] | 1211 | debug_msg( 10, ' |-Cluster found: %s' %( self.clusterName ) ) |
---|
[6] | 1212 | |
---|
[770] | 1213 | elif name == 'HOST' and self.clusterName in ARCHIVE_DATASOURCES: |
---|
[32] | 1214 | |
---|
[782] | 1215 | self.hostName = str( attrs.get( 'NAME', "" ) ) |
---|
| 1216 | self.hostIp = str( attrs.get( 'IP', "" ) ) |
---|
| 1217 | self.hostReported = str( attrs.get( 'REPORTED', "" ) ) |
---|
[32] | 1218 | |
---|
[770] | 1219 | debug_msg( 10, ' | |-Host found: %s - ip %s reported %s' %( self.hostName, self.hostIp, self.hostReported ) ) |
---|
[6] | 1220 | |
---|
[770] | 1221 | elif name == 'METRIC' and self.clusterName in ARCHIVE_DATASOURCES: |
---|
[6] | 1222 | |
---|
[770] | 1223 | type = str( attrs.get( 'TYPE', "" ) ) |
---|
| 1224 | |
---|
| 1225 | exclude_metric = False |
---|
| 1226 | |
---|
| 1227 | for ex_metricstr in ARCHIVE_EXCLUDE_METRICS: |
---|
[6] | 1228 | |
---|
[770] | 1229 | orig_name = str( attrs.get( 'NAME', "" ) ) |
---|
[3] | 1230 | |
---|
[770] | 1231 | if string.lower( orig_name ) == string.lower( ex_metricstr ): |
---|
| 1232 | |
---|
| 1233 | exclude_metric = True |
---|
[198] | 1234 | |
---|
[770] | 1235 | elif re.match( ex_metricstr, orig_name ): |
---|
[198] | 1236 | |
---|
[770] | 1237 | exclude_metric = True |
---|
[198] | 1238 | |
---|
[770] | 1239 | if type not in UNSUPPORTED_ARCHIVE_TYPES and not exclude_metric: |
---|
[198] | 1240 | |
---|
[782] | 1241 | myMetric = { } |
---|
| 1242 | myMetric['name'] = str( attrs.get( 'NAME', "" ) ) |
---|
| 1243 | myMetric['val'] = str( attrs.get( 'VAL', "" ) ) |
---|
| 1244 | myMetric['time'] = self.hostReported |
---|
[3] | 1245 | |
---|
[770] | 1246 | self.clusters[ self.clusterName ].memMetric( self.hostName, myMetric ) |
---|
[3] | 1247 | |
---|
[928] | 1248 | debug_msg( 9, 'added metric %s from host %s to cluster %s' %( myMetric['name'], self.hostName, self.clusterName ) ) |
---|
[770] | 1249 | debug_msg( 11, ' | | |-metric: %s:%s' %( myMetric['name'], myMetric['val'] ) ) |
---|
[6] | 1250 | |
---|
[770] | 1251 | def storeMetrics( self ): |
---|
| 1252 | """Store metrics of each cluster rrd handler""" |
---|
[9] | 1253 | |
---|
[770] | 1254 | for clustername, rrdh in self.clusters.items(): |
---|
[16] | 1255 | |
---|
[770] | 1256 | ret = rrdh.storeMetrics() |
---|
[9] | 1257 | |
---|
[770] | 1258 | if ret: |
---|
| 1259 | debug_msg( 9, 'An error occured while storing metrics for cluster %s' %clustername ) |
---|
| 1260 | return 1 |
---|
[38] | 1261 | |
---|
[770] | 1262 | return 0 |
---|
[38] | 1263 | |
---|
[71] | 1264 | class XMLErrorHandler( xml.sax.handler.ErrorHandler ): |
---|
| 1265 | |
---|
[926] | 1266 | def __init__( self ): |
---|
| 1267 | |
---|
| 1268 | self.me_fatal = False |
---|
| 1269 | |
---|
[770] | 1270 | def error( self, exception ): |
---|
| 1271 | """Recoverable error""" |
---|
[71] | 1272 | |
---|
[770] | 1273 | debug_msg( 0, 'Recoverable XML error ' + str( exception ) + ' ignored.' ) |
---|
[71] | 1274 | |
---|
[770] | 1275 | def fatalError( self, exception ): |
---|
| 1276 | """Non-recoverable error""" |
---|
[71] | 1277 | |
---|
[770] | 1278 | exception_str = str( exception ) |
---|
[71] | 1279 | |
---|
[770] | 1280 | # Ignore 'no element found' errors |
---|
| 1281 | if exception_str.find( 'no element found' ) != -1: |
---|
[926] | 1282 | |
---|
[770] | 1283 | debug_msg( 0, 'No XML data found: Socket not (re)connected or datasource not available.' ) |
---|
| 1284 | return 0 |
---|
[71] | 1285 | |
---|
[926] | 1286 | self.me_fatal = True |
---|
| 1287 | |
---|
[770] | 1288 | debug_msg( 0, 'FATAL ERROR: Non-recoverable XML error ' + str( exception ) ) |
---|
[71] | 1289 | |
---|
[926] | 1290 | def isFatal( self ): |
---|
| 1291 | |
---|
| 1292 | return self.me_fatal |
---|
| 1293 | |
---|
[770] | 1294 | def warning( self, exception ): |
---|
| 1295 | """Warning""" |
---|
[71] | 1296 | |
---|
[770] | 1297 | debug_msg( 0, 'Warning ' + str( exception ) ) |
---|
[71] | 1298 | |
---|
[78] | 1299 | class XMLGatherer: |
---|
[770] | 1300 | """Setup a connection and file object to Ganglia's XML""" |
---|
[3] | 1301 | |
---|
[858] | 1302 | s = None |
---|
| 1303 | fd = None |
---|
[770] | 1304 | data = None |
---|
| 1305 | slot = None |
---|
[8] | 1306 | |
---|
[770] | 1307 | # Time since the last update |
---|
| 1308 | # |
---|
| 1309 | LAST_UPDATE = 0 |
---|
[287] | 1310 | |
---|
[770] | 1311 | # Minimum interval between updates |
---|
| 1312 | # |
---|
| 1313 | MIN_UPDATE_INT = 10 |
---|
[287] | 1314 | |
---|
[770] | 1315 | # Is a update occuring now |
---|
| 1316 | # |
---|
| 1317 | update_now = False |
---|
[287] | 1318 | |
---|
[770] | 1319 | def __init__( self, host, port ): |
---|
| 1320 | """Store host and port for connection""" |
---|
[8] | 1321 | |
---|
[770] | 1322 | self.host = host |
---|
| 1323 | self.port = port |
---|
[782] | 1324 | self.slot = threading.Lock() |
---|
[3] | 1325 | |
---|
[770] | 1326 | self.retrieveData() |
---|
[287] | 1327 | |
---|
[770] | 1328 | def retrieveData( self ): |
---|
| 1329 | """Setup connection to XML source""" |
---|
[8] | 1330 | |
---|
[858] | 1331 | self.update_now = True |
---|
[287] | 1332 | |
---|
[770] | 1333 | self.slot.acquire() |
---|
[293] | 1334 | |
---|
[858] | 1335 | self.data = None |
---|
[469] | 1336 | |
---|
[770] | 1337 | for res in socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ): |
---|
[32] | 1338 | |
---|
[770] | 1339 | af, socktype, proto, canonname, sa = res |
---|
[32] | 1340 | |
---|
[770] | 1341 | try: |
---|
[32] | 1342 | |
---|
[770] | 1343 | self.s = socket.socket( af, socktype, proto ) |
---|
[32] | 1344 | |
---|
[770] | 1345 | except ( socket.error, socket.gaierror, socket.herror, socket.timeout ), msg: |
---|
[32] | 1346 | |
---|
[770] | 1347 | self.s = None |
---|
| 1348 | continue |
---|
[32] | 1349 | |
---|
[773] | 1350 | try: |
---|
[32] | 1351 | |
---|
[770] | 1352 | self.s.connect( sa ) |
---|
[32] | 1353 | |
---|
[773] | 1354 | except ( socket.error, socket.gaierror, socket.herror, socket.timeout ), msg: |
---|
[32] | 1355 | |
---|
[770] | 1356 | self.disconnect() |
---|
| 1357 | continue |
---|
[32] | 1358 | |
---|
[773] | 1359 | break |
---|
[3] | 1360 | |
---|
[770] | 1361 | if self.s is None: |
---|
[32] | 1362 | |
---|
[770] | 1363 | debug_msg( 0, 'FATAL ERROR: Could not open socket or unable to connect to datasource!' ) |
---|
| 1364 | self.update_now = False |
---|
| 1365 | #sys.exit( 1 ) |
---|
[5] | 1366 | |
---|
[770] | 1367 | else: |
---|
| 1368 | #self.s.send( '\n' ) |
---|
[287] | 1369 | |
---|
[770] | 1370 | my_fp = self.s.makefile( 'r' ) |
---|
[773] | 1371 | my_data = my_fp.readlines() |
---|
| 1372 | my_data = string.join( my_data, '' ) |
---|
[287] | 1373 | |
---|
[770] | 1374 | self.data = my_data |
---|
[287] | 1375 | |
---|
[773] | 1376 | self.LAST_UPDATE = time.time() |
---|
[287] | 1377 | |
---|
[770] | 1378 | self.slot.release() |
---|
[293] | 1379 | |
---|
[770] | 1380 | self.update_now = False |
---|
[287] | 1381 | |
---|
[770] | 1382 | def disconnect( self ): |
---|
| 1383 | """Close socket""" |
---|
[33] | 1384 | |
---|
[770] | 1385 | if self.s: |
---|
| 1386 | #self.s.shutdown( 2 ) |
---|
| 1387 | self.s.close() |
---|
| 1388 | self.s = None |
---|
[33] | 1389 | |
---|
[770] | 1390 | def __del__( self ): |
---|
| 1391 | """Kill the socket before we leave""" |
---|
[33] | 1392 | |
---|
[770] | 1393 | self.disconnect() |
---|
[33] | 1394 | |
---|
[770] | 1395 | def reGetData( self ): |
---|
| 1396 | """Reconnect""" |
---|
[33] | 1397 | |
---|
[770] | 1398 | while self.update_now: |
---|
[287] | 1399 | |
---|
[770] | 1400 | # Must be another update in progress: |
---|
| 1401 | # Wait until the update is complete |
---|
| 1402 | # |
---|
| 1403 | time.sleep( 1 ) |
---|
[287] | 1404 | |
---|
[770] | 1405 | if self.s: |
---|
| 1406 | self.disconnect() |
---|
[33] | 1407 | |
---|
[770] | 1408 | self.retrieveData() |
---|
[5] | 1409 | |
---|
[770] | 1410 | def getData( self ): |
---|
[287] | 1411 | |
---|
[770] | 1412 | """Return the XML data""" |
---|
[287] | 1413 | |
---|
[770] | 1414 | # If more than MIN_UPDATE_INT seconds passed since last data update |
---|
| 1415 | # update the XML first before returning it |
---|
| 1416 | # |
---|
[287] | 1417 | |
---|
[770] | 1418 | cur_time = time.time() |
---|
[287] | 1419 | |
---|
[770] | 1420 | if ( cur_time - self.LAST_UPDATE ) > self.MIN_UPDATE_INT: |
---|
[287] | 1421 | |
---|
[770] | 1422 | self.reGetData() |
---|
[287] | 1423 | |
---|
[770] | 1424 | while self.update_now: |
---|
[287] | 1425 | |
---|
[770] | 1426 | # Must be another update in progress: |
---|
| 1427 | # Wait until the update is complete |
---|
| 1428 | # |
---|
| 1429 | time.sleep( 1 ) |
---|
| 1430 | |
---|
| 1431 | return self.data |
---|
[287] | 1432 | |
---|
[770] | 1433 | def makeFileDescriptor( self ): |
---|
| 1434 | """Make file descriptor that points to our socket connection""" |
---|
[70] | 1435 | |
---|
[770] | 1436 | self.reconnect() |
---|
[70] | 1437 | |
---|
[770] | 1438 | if self.s: |
---|
| 1439 | self.fd = self.s.makefile( 'r' ) |
---|
[70] | 1440 | |
---|
[770] | 1441 | def getFileObject( self ): |
---|
| 1442 | """Connect, and return a file object""" |
---|
[70] | 1443 | |
---|
[770] | 1444 | self.makeFileDescriptor() |
---|
[78] | 1445 | |
---|
[770] | 1446 | if self.fd: |
---|
| 1447 | return self.fd |
---|
[70] | 1448 | |
---|
[78] | 1449 | class GangliaXMLProcessor( XMLProcessor ): |
---|
[770] | 1450 | """Main class for processing XML and acting with it""" |
---|
[5] | 1451 | |
---|
[770] | 1452 | def __init__( self, XMLSource, DataStore ): |
---|
| 1453 | """Setup initial XML connection and handlers""" |
---|
[33] | 1454 | |
---|
[782] | 1455 | self.config = GangliaConfigParser( GMETAD_CONF ) |
---|
| 1456 | self.myXMLSource = XMLSource |
---|
| 1457 | self.ds = DataStore |
---|
| 1458 | self.myXMLHandler = GangliaXMLHandler( self.config, self.ds ) |
---|
| 1459 | self.myXMLError = XMLErrorHandler() |
---|
[33] | 1460 | |
---|
[770] | 1461 | def run( self ): |
---|
| 1462 | """Main XML processing; start a xml and storethread""" |
---|
[8] | 1463 | |
---|
[782] | 1464 | xml_thread = threading.Thread( None, self.processXML, 'xmlthread' ) |
---|
[770] | 1465 | store_thread = threading.Thread( None, self.storeMetrics, 'storethread' ) |
---|
[22] | 1466 | |
---|
[770] | 1467 | while( 1 ): |
---|
[36] | 1468 | |
---|
[770] | 1469 | if not xml_thread.isAlive(): |
---|
| 1470 | # Gather XML at the same interval as gmetad |
---|
[36] | 1471 | |
---|
[770] | 1472 | # threaded call to: self.processXML() |
---|
| 1473 | # |
---|
| 1474 | try: |
---|
| 1475 | xml_thread = threading.Thread( None, self.processXML, 'xml_thread' ) |
---|
| 1476 | xml_thread.start() |
---|
| 1477 | except thread.error, msg: |
---|
| 1478 | debug_msg( 0, 'ERROR: Unable to start xml_thread!: '+str(msg)) |
---|
| 1479 | #return 1 |
---|
[36] | 1480 | |
---|
[770] | 1481 | if not store_thread.isAlive(): |
---|
| 1482 | # Store metrics every .. sec |
---|
[36] | 1483 | |
---|
[770] | 1484 | # threaded call to: self.storeMetrics() |
---|
| 1485 | # |
---|
| 1486 | try: |
---|
| 1487 | store_thread = threading.Thread( None, self.storeMetrics, 'store_thread' ) |
---|
| 1488 | store_thread.start() |
---|
| 1489 | except thread.error, msg: |
---|
| 1490 | debug_msg( 0, 'ERROR: Unable to start store_thread!: '+str(msg)) |
---|
| 1491 | #return 1 |
---|
| 1492 | |
---|
| 1493 | # Just sleep a sec here, to prevent daemon from going mad. We're all threads here anyway |
---|
| 1494 | time.sleep( 1 ) |
---|
[36] | 1495 | |
---|
[770] | 1496 | def storeMetrics( self ): |
---|
| 1497 | """Store metrics retained in memory to disk""" |
---|
[22] | 1498 | |
---|
[770] | 1499 | global DEBUG_LEVEL |
---|
[365] | 1500 | |
---|
[770] | 1501 | # Store metrics somewhere between every 360 and 640 seconds |
---|
| 1502 | # |
---|
[774] | 1503 | if DEBUG_LEVEL >= 1: |
---|
| 1504 | STORE_INTERVAL = 60 |
---|
[770] | 1505 | else: |
---|
[857] | 1506 | STORE_INTERVAL = random.randint( 300, 600 ) |
---|
[22] | 1507 | |
---|
[770] | 1508 | try: |
---|
| 1509 | store_metric_thread = threading.Thread( None, self.storeThread, 'store_metric_thread' ) |
---|
| 1510 | store_metric_thread.start() |
---|
| 1511 | except thread.error, msg: |
---|
| 1512 | debug_msg( 0, 'ERROR: Unable to start ganglia_store_thread()!: '+str(msg) ) |
---|
| 1513 | return 1 |
---|
[36] | 1514 | |
---|
[770] | 1515 | debug_msg( 1, 'ganglia_store_thread(): started.' ) |
---|
[169] | 1516 | |
---|
[770] | 1517 | debug_msg( 1, 'ganglia_store_thread(): Sleeping.. (%ss)' %STORE_INTERVAL ) |
---|
| 1518 | time.sleep( STORE_INTERVAL ) |
---|
| 1519 | debug_msg( 1, 'ganglia_store_thread(): Done sleeping.' ) |
---|
[36] | 1520 | |
---|
[770] | 1521 | if store_metric_thread.isAlive(): |
---|
[36] | 1522 | |
---|
[782] | 1523 | debug_msg( 1, 'ganglia_store_thread(): storemetricthread() still running, waiting to finish..' ) |
---|
[770] | 1524 | store_metric_thread.join( STORE_TIMEOUT ) # Maximum time is for storing thread to finish |
---|
[36] | 1525 | |
---|
[782] | 1526 | if store_metric_thread.isAlive(): |
---|
| 1527 | |
---|
| 1528 | debug_msg( 1, 'ganglia_store_thread(): Done waiting: storemetricthread() still running :( now what?' ) |
---|
| 1529 | else: |
---|
| 1530 | debug_msg( 1, 'ganglia_store_thread(): Done waiting: storemetricthread() has finished' ) |
---|
| 1531 | |
---|
[770] | 1532 | debug_msg( 1, 'ganglia_store_thread(): finished.' ) |
---|
[36] | 1533 | |
---|
[770] | 1534 | return 0 |
---|
[36] | 1535 | |
---|
[770] | 1536 | def storeThread( self ): |
---|
| 1537 | """Actual metric storing thread""" |
---|
[39] | 1538 | |
---|
[770] | 1539 | debug_msg( 1, 'ganglia_store_metric_thread(): started.' ) |
---|
| 1540 | debug_msg( 1, 'ganglia_store_metric_thread(): Storing data..' ) |
---|
[782] | 1541 | |
---|
[770] | 1542 | ret = self.myXMLHandler.storeMetrics() |
---|
| 1543 | if ret > 0: |
---|
| 1544 | debug_msg( 0, 'ganglia_store_metric_thread(): UNKNOWN ERROR %s while storing Metrics!' %str(ret) ) |
---|
[782] | 1545 | |
---|
[770] | 1546 | debug_msg( 1, 'ganglia_store_metric_thread(): Done storing.' ) |
---|
| 1547 | debug_msg( 1, 'ganglia_store_metric_thread(): finished.' ) |
---|
| 1548 | |
---|
| 1549 | return 0 |
---|
[39] | 1550 | |
---|
[770] | 1551 | def processXML( self ): |
---|
| 1552 | """Process XML""" |
---|
[8] | 1553 | |
---|
[770] | 1554 | try: |
---|
| 1555 | parsethread = threading.Thread( None, self.parseThread, 'parsethread' ) |
---|
| 1556 | parsethread.start() |
---|
| 1557 | except thread.error, msg: |
---|
| 1558 | debug_msg( 0, 'ERROR: Unable to start ganglia_xml_thread()!: ' + str(msg) ) |
---|
| 1559 | return 1 |
---|
[8] | 1560 | |
---|
[770] | 1561 | debug_msg( 1, 'ganglia_xml_thread(): started.' ) |
---|
[36] | 1562 | |
---|
[770] | 1563 | debug_msg( 1, 'ganglia_xml_thread(): Sleeping.. (%ss)' %self.config.getLowestInterval() ) |
---|
| 1564 | time.sleep( float( self.config.getLowestInterval() ) ) |
---|
| 1565 | debug_msg( 1, 'ganglia_xml_thread(): Done sleeping.' ) |
---|
[36] | 1566 | |
---|
[770] | 1567 | if parsethread.isAlive(): |
---|
[36] | 1568 | |
---|
[782] | 1569 | debug_msg( 1, 'ganglia_xml_thread(): parsethread() still running, waiting (%ss) to finish..' %PARSE_TIMEOUT ) |
---|
[770] | 1570 | parsethread.join( PARSE_TIMEOUT ) # Maximum time for XML thread to finish |
---|
[36] | 1571 | |
---|
[782] | 1572 | if parsethread.isAlive(): |
---|
| 1573 | debug_msg( 1, 'ganglia_xml_thread(): Done waiting: parsethread() still running :( now what?' ) |
---|
| 1574 | else: |
---|
| 1575 | debug_msg( 1, 'ganglia_xml_thread(): Done waiting: parsethread() finished' ) |
---|
| 1576 | |
---|
[770] | 1577 | debug_msg( 1, 'ganglia_xml_thread(): finished.' ) |
---|
[36] | 1578 | |
---|
[770] | 1579 | return 0 |
---|
[36] | 1580 | |
---|
[770] | 1581 | def parseThread( self ): |
---|
| 1582 | """Actual parsing thread""" |
---|
[39] | 1583 | |
---|
[770] | 1584 | debug_msg( 1, 'ganglia_parse_thread(): started.' ) |
---|
| 1585 | debug_msg( 1, 'ganglia_parse_thread(): Retrieving XML data..' ) |
---|
| 1586 | |
---|
| 1587 | my_data = self.myXMLSource.getData() |
---|
[176] | 1588 | |
---|
[782] | 1589 | debug_msg( 1, 'ganglia_parse_thread(): Done retrieving: data size %d' %len(my_data) ) |
---|
[293] | 1590 | |
---|
[770] | 1591 | if my_data: |
---|
| 1592 | debug_msg( 1, 'ganglia_parse_thread(): Parsing XML..' ) |
---|
| 1593 | xml.sax.parseString( my_data, self.myXMLHandler, self.myXMLError ) |
---|
| 1594 | debug_msg( 1, 'ganglia_parse_thread(): Done parsing.' ) |
---|
[176] | 1595 | |
---|
[770] | 1596 | debug_msg( 1, 'ganglia_parse_thread(): finished.' ) |
---|
[39] | 1597 | |
---|
[770] | 1598 | return 0 |
---|
[39] | 1599 | |
---|
[9] | 1600 | class GangliaConfigParser: |
---|
| 1601 | |
---|
[770] | 1602 | sources = [ ] |
---|
[9] | 1603 | |
---|
[770] | 1604 | def __init__( self, config ): |
---|
| 1605 | """Parse some stuff from our gmetad's config, such as polling interval""" |
---|
[32] | 1606 | |
---|
[770] | 1607 | self.config = config |
---|
| 1608 | self.parseValues() |
---|
[9] | 1609 | |
---|
[770] | 1610 | def parseValues( self ): |
---|
| 1611 | """Parse certain values from gmetad.conf""" |
---|
[9] | 1612 | |
---|
[770] | 1613 | readcfg = open( self.config, 'r' ) |
---|
[9] | 1614 | |
---|
[770] | 1615 | for line in readcfg.readlines(): |
---|
[9] | 1616 | |
---|
[770] | 1617 | if line.count( '"' ) > 1: |
---|
[9] | 1618 | |
---|
[770] | 1619 | if line.find( 'data_source' ) != -1 and line[0] != '#': |
---|
[9] | 1620 | |
---|
[855] | 1621 | source = { } |
---|
| 1622 | source['name'] = line.split( '"' )[1] |
---|
| 1623 | source_value_words = line.split( '"' )[2].split( ' ' ) |
---|
[9] | 1624 | |
---|
[855] | 1625 | check_interval = source_value_words[0] |
---|
[9] | 1626 | |
---|
[855] | 1627 | try: |
---|
[9] | 1628 | |
---|
[855] | 1629 | source['interval'] = int( check_interval ) |
---|
| 1630 | debug_msg( 9, 'polling interval for %s = %s' %(source['name'], str( source['interval'] ) ) ) |
---|
| 1631 | except ValueError: |
---|
[32] | 1632 | |
---|
[770] | 1633 | source['interval'] = 15 |
---|
| 1634 | debug_msg( 9, 'polling interval for %s defaulted to 15' %(source['name']) ) |
---|
[32] | 1635 | |
---|
[770] | 1636 | self.sources.append( source ) |
---|
[9] | 1637 | |
---|
[855] | 1638 | readcfg.close() |
---|
| 1639 | |
---|
| 1640 | def clusterExists( self, source_name ): |
---|
| 1641 | |
---|
| 1642 | for source in self.sources: |
---|
| 1643 | |
---|
| 1644 | if source['name'] == source_name: |
---|
| 1645 | |
---|
| 1646 | return True |
---|
| 1647 | |
---|
| 1648 | return False |
---|
| 1649 | |
---|
[770] | 1650 | def getInterval( self, source_name ): |
---|
| 1651 | """Return interval for source_name""" |
---|
[32] | 1652 | |
---|
[770] | 1653 | for source in self.sources: |
---|
[32] | 1654 | |
---|
[770] | 1655 | if source['name'] == source_name: |
---|
[32] | 1656 | |
---|
[770] | 1657 | return source['interval'] |
---|
[32] | 1658 | |
---|
[770] | 1659 | return None |
---|
[9] | 1660 | |
---|
[770] | 1661 | def getLowestInterval( self ): |
---|
| 1662 | """Return the lowest interval of all clusters""" |
---|
[34] | 1663 | |
---|
[770] | 1664 | lowest_interval = 0 |
---|
[34] | 1665 | |
---|
[770] | 1666 | for source in self.sources: |
---|
[34] | 1667 | |
---|
[770] | 1668 | if not lowest_interval or source['interval'] <= lowest_interval: |
---|
[34] | 1669 | |
---|
[770] | 1670 | lowest_interval = source['interval'] |
---|
[34] | 1671 | |
---|
[770] | 1672 | # Return 15 when nothing is found, so that the daemon won't go insane with 0 sec delays |
---|
| 1673 | if lowest_interval: |
---|
| 1674 | return lowest_interval |
---|
| 1675 | else: |
---|
| 1676 | return 15 |
---|
[34] | 1677 | |
---|
[9] | 1678 | class RRDHandler: |
---|
[770] | 1679 | """Class for handling RRD activity""" |
---|
[9] | 1680 | |
---|
[32] | 1681 | |
---|
[770] | 1682 | def __init__( self, config, cluster ): |
---|
| 1683 | """Setup initial variables""" |
---|
[78] | 1684 | |
---|
[770] | 1685 | global MODRRDTOOL |
---|
[455] | 1686 | |
---|
[858] | 1687 | self.block = 0 |
---|
| 1688 | self.cluster = cluster |
---|
| 1689 | self.config = config |
---|
[770] | 1690 | self.slot = threading.Lock() |
---|
[928] | 1691 | self.myMetrics = { } |
---|
| 1692 | self.lastStored = { } |
---|
| 1693 | self.timeserials = { } |
---|
[292] | 1694 | |
---|
[770] | 1695 | if MODRRDTOOL: |
---|
[455] | 1696 | |
---|
[770] | 1697 | self.rrdm = RRDMutator() |
---|
| 1698 | else: |
---|
| 1699 | self.rrdm = RRDMutator( RRDTOOL ) |
---|
[455] | 1700 | |
---|
[770] | 1701 | global DEBUG_LEVEL |
---|
[9] | 1702 | |
---|
[770] | 1703 | if DEBUG_LEVEL <= 2: |
---|
| 1704 | self.gatherLastUpdates() |
---|
[365] | 1705 | |
---|
[770] | 1706 | def gatherLastUpdates( self ): |
---|
| 1707 | """Populate the lastStored list, containing timestamps of all last updates""" |
---|
[42] | 1708 | |
---|
[770] | 1709 | cluster_dir = '%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster ) |
---|
[42] | 1710 | |
---|
[770] | 1711 | hosts = [ ] |
---|
[42] | 1712 | |
---|
[770] | 1713 | if os.path.exists( cluster_dir ): |
---|
[42] | 1714 | |
---|
[770] | 1715 | dirlist = os.listdir( cluster_dir ) |
---|
[42] | 1716 | |
---|
[770] | 1717 | for dir in dirlist: |
---|
[42] | 1718 | |
---|
[770] | 1719 | hosts.append( dir ) |
---|
[42] | 1720 | |
---|
[770] | 1721 | for host in hosts: |
---|
[42] | 1722 | |
---|
[770] | 1723 | host_dir = cluster_dir + '/' + host |
---|
[858] | 1724 | dirlist = os.listdir( host_dir ) |
---|
[47] | 1725 | |
---|
[770] | 1726 | for dir in dirlist: |
---|
[47] | 1727 | |
---|
[770] | 1728 | if not self.timeserials.has_key( host ): |
---|
[47] | 1729 | |
---|
[770] | 1730 | self.timeserials[ host ] = [ ] |
---|
[47] | 1731 | |
---|
[770] | 1732 | self.timeserials[ host ].append( dir ) |
---|
[47] | 1733 | |
---|
[770] | 1734 | last_serial = self.getLastRrdTimeSerial( host ) |
---|
[292] | 1735 | |
---|
[770] | 1736 | if last_serial: |
---|
[42] | 1737 | |
---|
[770] | 1738 | metric_dir = cluster_dir + '/' + host + '/' + last_serial |
---|
[292] | 1739 | |
---|
[770] | 1740 | if os.path.exists( metric_dir ): |
---|
[42] | 1741 | |
---|
[770] | 1742 | dirlist = os.listdir( metric_dir ) |
---|
[42] | 1743 | |
---|
[770] | 1744 | for file in dirlist: |
---|
[42] | 1745 | |
---|
[770] | 1746 | metricname = file.split( '.rrd' )[0] |
---|
[42] | 1747 | |
---|
[770] | 1748 | if not self.lastStored.has_key( host ): |
---|
[42] | 1749 | |
---|
[770] | 1750 | self.lastStored[ host ] = { } |
---|
[42] | 1751 | |
---|
[770] | 1752 | self.lastStored[ host ][ metricname ] = self.rrdm.grabLastUpdate( metric_dir + '/' + file ) |
---|
[42] | 1753 | |
---|
[770] | 1754 | def getClusterName( self ): |
---|
| 1755 | """Return clustername""" |
---|
[63] | 1756 | |
---|
[770] | 1757 | return self.cluster |
---|
[32] | 1758 | |
---|
[770] | 1759 | def memMetric( self, host, metric ): |
---|
| 1760 | """Store metric from host in memory""" |
---|
[32] | 1761 | |
---|
[770] | 1762 | # <ATOMIC> |
---|
| 1763 | # |
---|
| 1764 | self.slot.acquire() |
---|
| 1765 | |
---|
| 1766 | if self.myMetrics.has_key( host ): |
---|
[32] | 1767 | |
---|
[770] | 1768 | if self.myMetrics[ host ].has_key( metric['name'] ): |
---|
[32] | 1769 | |
---|
[770] | 1770 | for mymetric in self.myMetrics[ host ][ metric['name'] ]: |
---|
[32] | 1771 | |
---|
[770] | 1772 | if mymetric['time'] == metric['time']: |
---|
[32] | 1773 | |
---|
[770] | 1774 | # Allready have this metric, abort |
---|
| 1775 | self.slot.release() |
---|
| 1776 | return 1 |
---|
| 1777 | else: |
---|
| 1778 | self.myMetrics[ host ][ metric['name'] ] = [ ] |
---|
| 1779 | else: |
---|
[858] | 1780 | self.myMetrics[ host ] = { } |
---|
| 1781 | self.myMetrics[ host ][ metric['name'] ] = [ ] |
---|
[32] | 1782 | |
---|
[770] | 1783 | # Push new metric onto stack |
---|
| 1784 | # atomic code; only 1 thread at a time may access the stack |
---|
[63] | 1785 | |
---|
[770] | 1786 | self.myMetrics[ host ][ metric['name'] ].append( metric ) |
---|
[32] | 1787 | |
---|
[770] | 1788 | self.slot.release() |
---|
| 1789 | # |
---|
| 1790 | # </ATOMIC> |
---|
[40] | 1791 | |
---|
[770] | 1792 | def makeUpdateList( self, host, metriclist ): |
---|
| 1793 | """ |
---|
| 1794 | Make a list of update values for rrdupdate |
---|
| 1795 | but only those that we didn't store before |
---|
| 1796 | """ |
---|
[37] | 1797 | |
---|
[770] | 1798 | update_list = [ ] |
---|
| 1799 | metric = None |
---|
[37] | 1800 | |
---|
[770] | 1801 | while len( metriclist ) > 0: |
---|
[37] | 1802 | |
---|
[770] | 1803 | metric = metriclist.pop( 0 ) |
---|
[37] | 1804 | |
---|
[770] | 1805 | if self.checkStoreMetric( host, metric ): |
---|
[292] | 1806 | |
---|
[770] | 1807 | u_val = str( metric['time'] ) + ':' + str( metric['val'] ) |
---|
| 1808 | #update_list.append( str('%s:%s') %( metric['time'], metric['val'] ) ) |
---|
| 1809 | update_list.append( u_val ) |
---|
[40] | 1810 | |
---|
[770] | 1811 | return update_list |
---|
[37] | 1812 | |
---|
[770] | 1813 | def checkStoreMetric( self, host, metric ): |
---|
| 1814 | """Check if supplied metric if newer than last one stored""" |
---|
[40] | 1815 | |
---|
[770] | 1816 | if self.lastStored.has_key( host ): |
---|
[40] | 1817 | |
---|
[770] | 1818 | if self.lastStored[ host ].has_key( metric['name'] ): |
---|
[40] | 1819 | |
---|
[770] | 1820 | if metric['time'] <= self.lastStored[ host ][ metric['name'] ]: |
---|
[40] | 1821 | |
---|
[770] | 1822 | # This is old |
---|
| 1823 | return 0 |
---|
[40] | 1824 | |
---|
[770] | 1825 | return 1 |
---|
[50] | 1826 | |
---|
[770] | 1827 | def memLastUpdate( self, host, metricname, metriclist ): |
---|
| 1828 | """ |
---|
| 1829 | Memorize the time of the latest metric from metriclist |
---|
| 1830 | but only if it wasn't allready memorized |
---|
| 1831 | """ |
---|
[50] | 1832 | |
---|
[770] | 1833 | if not self.lastStored.has_key( host ): |
---|
| 1834 | self.lastStored[ host ] = { } |
---|
[54] | 1835 | |
---|
[770] | 1836 | last_update_time = 0 |
---|
[50] | 1837 | |
---|
[770] | 1838 | for metric in metriclist: |
---|
[50] | 1839 | |
---|
[770] | 1840 | if metric['name'] == metricname: |
---|
[50] | 1841 | |
---|
[770] | 1842 | if metric['time'] > last_update_time: |
---|
[50] | 1843 | |
---|
[770] | 1844 | last_update_time = metric['time'] |
---|
[40] | 1845 | |
---|
[770] | 1846 | if self.lastStored[ host ].has_key( metricname ): |
---|
| 1847 | |
---|
| 1848 | if last_update_time <= self.lastStored[ host ][ metricname ]: |
---|
| 1849 | return 1 |
---|
[40] | 1850 | |
---|
[770] | 1851 | self.lastStored[ host ][ metricname ] = last_update_time |
---|
[52] | 1852 | |
---|
[770] | 1853 | def storeMetrics( self ): |
---|
| 1854 | """ |
---|
| 1855 | Store all metrics from memory to disk |
---|
| 1856 | and do it to the RRD's in appropriate timeperiod directory |
---|
| 1857 | """ |
---|
[33] | 1858 | |
---|
[770] | 1859 | debug_msg( 5, "Entering storeMetrics()") |
---|
[365] | 1860 | |
---|
[782] | 1861 | count_values = 0 |
---|
| 1862 | count_metrics = 0 |
---|
[770] | 1863 | count_bits = 0 |
---|
[365] | 1864 | |
---|
[770] | 1865 | for hostname, mymetrics in self.myMetrics.items(): |
---|
[33] | 1866 | |
---|
[770] | 1867 | for metricname, mymetric in mymetrics.items(): |
---|
[33] | 1868 | |
---|
[770] | 1869 | count_metrics += 1 |
---|
[365] | 1870 | |
---|
[770] | 1871 | for dmetric in mymetric: |
---|
[365] | 1872 | |
---|
[770] | 1873 | count_values += 1 |
---|
[365] | 1874 | |
---|
[782] | 1875 | count_bits += len( dmetric['time'] ) |
---|
| 1876 | count_bits += len( dmetric['val'] ) |
---|
[365] | 1877 | |
---|
[770] | 1878 | count_bytes = count_bits / 8 |
---|
[365] | 1879 | |
---|
[770] | 1880 | debug_msg( 5, "size of cluster '" + self.cluster + "': " + |
---|
| 1881 | str( len( self.myMetrics.keys() ) ) + " hosts " + |
---|
| 1882 | str( count_metrics ) + " metrics " + str( count_values ) + " values " + |
---|
| 1883 | str( count_bits ) + " bits " + str( count_bytes ) + " bytes " ) |
---|
[365] | 1884 | |
---|
[770] | 1885 | for hostname, mymetrics in self.myMetrics.items(): |
---|
[365] | 1886 | |
---|
[770] | 1887 | for metricname, mymetric in mymetrics.items(): |
---|
[365] | 1888 | |
---|
[770] | 1889 | metrics_to_store = [ ] |
---|
[53] | 1890 | |
---|
[770] | 1891 | # Pop metrics from stack for storing until none is left |
---|
| 1892 | # atomic code: only 1 thread at a time may access myMetrics |
---|
[63] | 1893 | |
---|
[770] | 1894 | # <ATOMIC> |
---|
| 1895 | # |
---|
| 1896 | self.slot.acquire() |
---|
[33] | 1897 | |
---|
[770] | 1898 | while len( self.myMetrics[ hostname ][ metricname ] ) > 0: |
---|
[53] | 1899 | |
---|
[770] | 1900 | if len( self.myMetrics[ hostname ][ metricname ] ) > 0: |
---|
[53] | 1901 | |
---|
[770] | 1902 | try: |
---|
| 1903 | metrics_to_store.append( self.myMetrics[ hostname ][ metricname ].pop( 0 ) ) |
---|
| 1904 | except IndexError, msg: |
---|
[176] | 1905 | |
---|
[770] | 1906 | # Somehow sometimes myMetrics[ hostname ][ metricname ] |
---|
| 1907 | # is still len 0 when the statement is executed. |
---|
| 1908 | # Just ignore indexerror's.. |
---|
| 1909 | pass |
---|
[176] | 1910 | |
---|
[770] | 1911 | self.slot.release() |
---|
| 1912 | # |
---|
| 1913 | # </ATOMIC> |
---|
[53] | 1914 | |
---|
[770] | 1915 | # Create a mapping table, each metric to the period where it should be stored |
---|
| 1916 | # |
---|
| 1917 | metric_serial_table = self.determineSerials( hostname, metricname, metrics_to_store ) |
---|
[33] | 1918 | |
---|
[770] | 1919 | update_rets = [ ] |
---|
[50] | 1920 | |
---|
[770] | 1921 | for period, pmetric in metric_serial_table.items(): |
---|
[47] | 1922 | |
---|
[770] | 1923 | create_ret = self.createCheck( hostname, metricname, period ) |
---|
[47] | 1924 | |
---|
[770] | 1925 | update_ret = self.update( hostname, metricname, period, pmetric ) |
---|
[47] | 1926 | |
---|
[770] | 1927 | if update_ret == 0: |
---|
[47] | 1928 | |
---|
[770] | 1929 | debug_msg( 9, 'stored metric %s for %s' %( hostname, metricname ) ) |
---|
| 1930 | else: |
---|
| 1931 | debug_msg( 9, 'metric update failed' ) |
---|
[47] | 1932 | |
---|
[770] | 1933 | update_rets.append( create_ret ) |
---|
| 1934 | update_rets.append( update_ret ) |
---|
[47] | 1935 | |
---|
[770] | 1936 | # Lets ignore errors here for now, we need to make sure last update time |
---|
| 1937 | # is correct! |
---|
| 1938 | # |
---|
| 1939 | #if not (1) in update_rets: |
---|
[50] | 1940 | |
---|
[770] | 1941 | self.memLastUpdate( hostname, metricname, metrics_to_store ) |
---|
[50] | 1942 | |
---|
[770] | 1943 | debug_msg( 5, "Leaving storeMetrics()") |
---|
[365] | 1944 | |
---|
[770] | 1945 | def makeTimeSerial( self ): |
---|
| 1946 | """Generate a time serial. Seconds since epoch""" |
---|
[17] | 1947 | |
---|
[770] | 1948 | # Seconds since epoch |
---|
| 1949 | mytime = int( time.time() ) |
---|
[17] | 1950 | |
---|
[770] | 1951 | return mytime |
---|
[17] | 1952 | |
---|
[770] | 1953 | def makeRrdPath( self, host, metricname, timeserial ): |
---|
| 1954 | """Make a RRD location/path and filename""" |
---|
[17] | 1955 | |
---|
[858] | 1956 | rrd_dir = '%s/%s/%s/%s' %( check_dir(ARCHIVE_PATH), self.cluster, host, timeserial ) |
---|
| 1957 | rrd_file = '%s/%s.rrd' %( rrd_dir, metricname ) |
---|
[17] | 1958 | |
---|
[770] | 1959 | return rrd_dir, rrd_file |
---|
[17] | 1960 | |
---|
[770] | 1961 | def getLastRrdTimeSerial( self, host ): |
---|
| 1962 | """Find the last timeserial (directory) for this host""" |
---|
[17] | 1963 | |
---|
[770] | 1964 | newest_timeserial = 0 |
---|
[19] | 1965 | |
---|
[770] | 1966 | for dir in self.timeserials[ host ]: |
---|
[32] | 1967 | |
---|
[770] | 1968 | valid_dir = 1 |
---|
[17] | 1969 | |
---|
[770] | 1970 | for letter in dir: |
---|
| 1971 | if letter not in string.digits: |
---|
| 1972 | valid_dir = 0 |
---|
[17] | 1973 | |
---|
[770] | 1974 | if valid_dir: |
---|
| 1975 | timeserial = dir |
---|
| 1976 | if timeserial > newest_timeserial: |
---|
| 1977 | newest_timeserial = timeserial |
---|
[17] | 1978 | |
---|
[770] | 1979 | if newest_timeserial: |
---|
| 1980 | return newest_timeserial |
---|
| 1981 | else: |
---|
| 1982 | return 0 |
---|
[17] | 1983 | |
---|
[770] | 1984 | def determinePeriod( self, host, check_serial ): |
---|
| 1985 | """Determine to which period (directory) this time(serial) belongs""" |
---|
[47] | 1986 | |
---|
[770] | 1987 | period_serial = 0 |
---|
[47] | 1988 | |
---|
[770] | 1989 | if self.timeserials.has_key( host ): |
---|
[47] | 1990 | |
---|
[770] | 1991 | for serial in self.timeserials[ host ]: |
---|
[47] | 1992 | |
---|
[770] | 1993 | if check_serial >= serial and period_serial < serial: |
---|
[47] | 1994 | |
---|
[770] | 1995 | period_serial = serial |
---|
[56] | 1996 | |
---|
[770] | 1997 | return period_serial |
---|
[47] | 1998 | |
---|
[770] | 1999 | def determineSerials( self, host, metricname, metriclist ): |
---|
| 2000 | """ |
---|
| 2001 | Determine the correct serial and corresponding rrd to store |
---|
| 2002 | for a list of metrics |
---|
| 2003 | """ |
---|
[47] | 2004 | |
---|
[770] | 2005 | metric_serial_table = { } |
---|
[47] | 2006 | |
---|
[770] | 2007 | for metric in metriclist: |
---|
[47] | 2008 | |
---|
[770] | 2009 | if metric['name'] == metricname: |
---|
[47] | 2010 | |
---|
[858] | 2011 | period = self.determinePeriod( host, metric['time'] ) |
---|
[47] | 2012 | |
---|
[858] | 2013 | archive_secs = ARCHIVE_HOURS_PER_RRD * (60 * 60) |
---|
[47] | 2014 | |
---|
[770] | 2015 | if (int( metric['time'] ) - int( period ) ) > archive_secs: |
---|
[47] | 2016 | |
---|
[770] | 2017 | # This one should get it's own new period |
---|
| 2018 | period = metric['time'] |
---|
[57] | 2019 | |
---|
[770] | 2020 | if not self.timeserials.has_key( host ): |
---|
| 2021 | self.timeserials[ host ] = [ ] |
---|
[57] | 2022 | |
---|
[770] | 2023 | self.timeserials[ host ].append( period ) |
---|
[47] | 2024 | |
---|
[770] | 2025 | if not metric_serial_table.has_key( period ): |
---|
[47] | 2026 | |
---|
[770] | 2027 | metric_serial_table[ period ] = [ ] |
---|
[47] | 2028 | |
---|
[770] | 2029 | metric_serial_table[ period ].append( metric ) |
---|
[47] | 2030 | |
---|
[770] | 2031 | return metric_serial_table |
---|
[47] | 2032 | |
---|
[770] | 2033 | def createCheck( self, host, metricname, timeserial ): |
---|
| 2034 | """Check if an rrd allready exists for this metric, create if not""" |
---|
[9] | 2035 | |
---|
[770] | 2036 | debug_msg( 9, 'rrdcreate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) ) |
---|
| 2037 | |
---|
| 2038 | rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial ) |
---|
[17] | 2039 | |
---|
[770] | 2040 | if not os.path.exists( rrd_dir ): |
---|
[58] | 2041 | |
---|
[770] | 2042 | try: |
---|
| 2043 | os.makedirs( rrd_dir ) |
---|
[58] | 2044 | |
---|
[770] | 2045 | except os.OSError, msg: |
---|
[58] | 2046 | |
---|
[770] | 2047 | if msg.find( 'File exists' ) != -1: |
---|
[58] | 2048 | |
---|
[770] | 2049 | # Ignore exists errors |
---|
| 2050 | pass |
---|
[58] | 2051 | |
---|
[770] | 2052 | else: |
---|
[58] | 2053 | |
---|
[770] | 2054 | print msg |
---|
| 2055 | return |
---|
[58] | 2056 | |
---|
[770] | 2057 | debug_msg( 9, 'created dir %s' %( str(rrd_dir) ) ) |
---|
[9] | 2058 | |
---|
[770] | 2059 | if not os.path.exists( rrd_file ): |
---|
[9] | 2060 | |
---|
[855] | 2061 | interval = self.config.getInterval( self.cluster ) |
---|
[770] | 2062 | heartbeat = 8 * int( interval ) |
---|
[9] | 2063 | |
---|
[858] | 2064 | params = [ ] |
---|
[12] | 2065 | |
---|
[770] | 2066 | params.append( '--step' ) |
---|
| 2067 | params.append( str( interval ) ) |
---|
[12] | 2068 | |
---|
[770] | 2069 | params.append( '--start' ) |
---|
| 2070 | params.append( str( int( timeserial ) - 1 ) ) |
---|
[12] | 2071 | |
---|
[770] | 2072 | params.append( 'DS:sum:GAUGE:%d:U:U' %heartbeat ) |
---|
| 2073 | params.append( 'RRA:AVERAGE:0.5:1:%s' %(ARCHIVE_HOURS_PER_RRD * 240) ) |
---|
[13] | 2074 | |
---|
[770] | 2075 | self.rrdm.create( str(rrd_file), params ) |
---|
[37] | 2076 | |
---|
[770] | 2077 | debug_msg( 9, 'created rrd %s' %( str(rrd_file) ) ) |
---|
[14] | 2078 | |
---|
[770] | 2079 | def update( self, host, metricname, timeserial, metriclist ): |
---|
| 2080 | """ |
---|
| 2081 | Update rrd file for host with metricname |
---|
| 2082 | in directory timeserial with metriclist |
---|
| 2083 | """ |
---|
[9] | 2084 | |
---|
[770] | 2085 | debug_msg( 9, 'rrdupdate: using timeserial %s for %s/%s' %( timeserial, host, metricname ) ) |
---|
[9] | 2086 | |
---|
[858] | 2087 | rrd_dir, rrd_file = self.makeRrdPath( host, metricname, timeserial ) |
---|
[18] | 2088 | |
---|
[858] | 2089 | update_list = self.makeUpdateList( host, metriclist ) |
---|
[15] | 2090 | |
---|
[770] | 2091 | if len( update_list ) > 0: |
---|
| 2092 | ret = self.rrdm.update( str(rrd_file), update_list ) |
---|
[32] | 2093 | |
---|
[770] | 2094 | if ret: |
---|
| 2095 | return 1 |
---|
| 2096 | |
---|
| 2097 | debug_msg( 9, 'updated rrd %s with %s' %( str(rrd_file), string.join( update_list ) ) ) |
---|
[15] | 2098 | |
---|
[770] | 2099 | return 0 |
---|
[36] | 2100 | |
---|
[169] | 2101 | def daemon(): |
---|
[770] | 2102 | """daemonized threading""" |
---|
[8] | 2103 | |
---|
[770] | 2104 | # Fork the first child |
---|
| 2105 | # |
---|
| 2106 | pid = os.fork() |
---|
[169] | 2107 | |
---|
[770] | 2108 | if pid > 0: |
---|
[169] | 2109 | |
---|
[770] | 2110 | sys.exit(0) # end parent |
---|
[169] | 2111 | |
---|
[770] | 2112 | # creates a session and sets the process group ID |
---|
| 2113 | # |
---|
| 2114 | os.setsid() |
---|
[169] | 2115 | |
---|
[770] | 2116 | # Fork the second child |
---|
| 2117 | # |
---|
| 2118 | pid = os.fork() |
---|
[169] | 2119 | |
---|
[770] | 2120 | if pid > 0: |
---|
[169] | 2121 | |
---|
[770] | 2122 | sys.exit(0) # end parent |
---|
[169] | 2123 | |
---|
[770] | 2124 | write_pidfile() |
---|
[435] | 2125 | |
---|
[770] | 2126 | # Go to the root directory and set the umask |
---|
| 2127 | # |
---|
| 2128 | os.chdir('/') |
---|
| 2129 | os.umask(0) |
---|
[169] | 2130 | |
---|
[770] | 2131 | sys.stdin.close() |
---|
| 2132 | sys.stdout.close() |
---|
| 2133 | sys.stderr.close() |
---|
[169] | 2134 | |
---|
[770] | 2135 | os.open('/dev/null', os.O_RDWR) |
---|
| 2136 | os.dup2(0, 1) |
---|
| 2137 | os.dup2(0, 2) |
---|
[169] | 2138 | |
---|
[770] | 2139 | run() |
---|
[169] | 2140 | |
---|
| 2141 | def run(): |
---|
[770] | 2142 | """Threading start""" |
---|
[169] | 2143 | |
---|
[855] | 2144 | global ARCHIVE_DATASOURCES |
---|
| 2145 | |
---|
[782] | 2146 | config = GangliaConfigParser( GMETAD_CONF ) |
---|
[855] | 2147 | |
---|
| 2148 | for ds in ARCHIVE_DATASOURCES: |
---|
| 2149 | |
---|
| 2150 | if not config.clusterExists( ds ): |
---|
| 2151 | |
---|
| 2152 | print "FATAL ERROR: Data source with name '%s' not found in %s" %( ds, GMETAD_CONF ) |
---|
| 2153 | sys.exit( 1 ) |
---|
| 2154 | |
---|
[782] | 2155 | s_timeout = int( config.getLowestInterval() - 1 ) |
---|
[469] | 2156 | |
---|
[770] | 2157 | socket.setdefaulttimeout( s_timeout ) |
---|
[469] | 2158 | |
---|
[770] | 2159 | myXMLSource = XMLGatherer( ARCHIVE_XMLSOURCE.split( ':' )[0], ARCHIVE_XMLSOURCE.split( ':' )[1] ) |
---|
| 2160 | myDataStore = DataSQLStore( JOB_SQL_DBASE.split( '/' )[0], JOB_SQL_DBASE.split( '/' )[1] ) |
---|
[8] | 2161 | |
---|
[782] | 2162 | myJobProcessor = JobXMLProcessor( myXMLSource, myDataStore ) |
---|
| 2163 | myGangliaProcessor = GangliaXMLProcessor( myXMLSource, myDataStore ) |
---|
[287] | 2164 | |
---|
[770] | 2165 | try: |
---|
[782] | 2166 | job_xml_thread = threading.Thread( None, myJobProcessor.run, 'job_proc_thread' ) |
---|
| 2167 | ganglia_xml_thread = threading.Thread( None, myGangliaProcessor.run, 'ganglia_proc_thread' ) |
---|
[22] | 2168 | |
---|
[782] | 2169 | job_xml_thread.start() |
---|
[770] | 2170 | ganglia_xml_thread.start() |
---|
| 2171 | |
---|
| 2172 | except thread.error, msg: |
---|
| 2173 | debug_msg( 0, 'FATAL ERROR: Unable to start main threads!: '+ str(msg) ) |
---|
| 2174 | syslog.closelog() |
---|
| 2175 | sys.exit(1) |
---|
| 2176 | |
---|
| 2177 | debug_msg( 0, 'main threading started.' ) |
---|
[78] | 2178 | |
---|
[169] | 2179 | def main(): |
---|
[770] | 2180 | """Program startup""" |
---|
[169] | 2181 | |
---|
[770] | 2182 | global DAEMONIZE, USE_SYSLOG |
---|
[375] | 2183 | |
---|
[770] | 2184 | if not processArgs( sys.argv[1:] ): |
---|
| 2185 | sys.exit( 1 ) |
---|
[214] | 2186 | |
---|
[770] | 2187 | if( DAEMONIZE and USE_SYSLOG ): |
---|
| 2188 | syslog.openlog( 'jobarchived', syslog.LOG_NOWAIT, SYSLOG_FACILITY ) |
---|
[169] | 2189 | |
---|
[770] | 2190 | if DAEMONIZE: |
---|
| 2191 | daemon() |
---|
| 2192 | else: |
---|
| 2193 | run() |
---|
[169] | 2194 | |
---|
| 2195 | # |
---|
[81] | 2196 | # Global functions |
---|
[169] | 2197 | # |
---|
[81] | 2198 | |
---|
[9] | 2199 | def check_dir( directory ): |
---|
[770] | 2200 | """Check if directory is a proper directory. I.e.: Does _not_ end with a '/'""" |
---|
[9] | 2201 | |
---|
[770] | 2202 | if directory[-1] == '/': |
---|
| 2203 | directory = directory[:-1] |
---|
[9] | 2204 | |
---|
[770] | 2205 | return directory |
---|
[9] | 2206 | |
---|
[295] | 2207 | def reqtime2epoch( rtime ): |
---|
| 2208 | |
---|
[770] | 2209 | (hours, minutes, seconds ) = rtime.split( ':' ) |
---|
[295] | 2210 | |
---|
[770] | 2211 | etime = int(seconds) |
---|
| 2212 | etime = etime + ( int(minutes) * 60 ) |
---|
| 2213 | etime = etime + ( int(hours) * 60 * 60 ) |
---|
[295] | 2214 | |
---|
[770] | 2215 | return etime |
---|
[295] | 2216 | |
---|
[12] | 2217 | def debug_msg( level, msg ): |
---|
[770] | 2218 | """Only print msg if correct levels""" |
---|
[12] | 2219 | |
---|
[770] | 2220 | if (not DAEMONIZE and DEBUG_LEVEL >= level): |
---|
| 2221 | sys.stderr.write( printTime() + ' - ' + msg + '\n' ) |
---|
| 2222 | |
---|
| 2223 | if (DAEMONIZE and USE_SYSLOG and SYSLOG_LEVEL >= level): |
---|
| 2224 | syslog.syslog( msg ) |
---|
[12] | 2225 | |
---|
[46] | 2226 | def printTime( ): |
---|
[770] | 2227 | """Print current time in human readable format""" |
---|
[46] | 2228 | |
---|
[770] | 2229 | return time.strftime("%a %d %b %Y %H:%M:%S") |
---|
[46] | 2230 | |
---|
[435] | 2231 | def write_pidfile(): |
---|
| 2232 | |
---|
[770] | 2233 | # Write pidfile if PIDFILE exists |
---|
| 2234 | if PIDFILE: |
---|
[435] | 2235 | |
---|
[770] | 2236 | pid = os.getpid() |
---|
[435] | 2237 | |
---|
[770] | 2238 | pidfile = open(PIDFILE, 'w') |
---|
[435] | 2239 | |
---|
[770] | 2240 | pidfile.write( str( pid ) ) |
---|
| 2241 | pidfile.close() |
---|
[435] | 2242 | |
---|
[63] | 2243 | # Ooohh, someone started me! Let's go.. |
---|
[469] | 2244 | # |
---|
[9] | 2245 | if __name__ == '__main__': |
---|
[770] | 2246 | main() |
---|