def json2Obj(msg): """ """ obj = None try: obj = json.loads(msg) except ValueError: raise AgentException("load string to dic error, {0} not a json format".format(msg)) except Exception, e: raise AgentException("unknown error: {0}".format(e))
def __init__(self, configFileName): """ 配置文件解析类初始化函数,configFileName为配置文件全路径,cmdDict为配置参数字典 """ if not os.path.isfile(configFileName): raise AgentException( "config file {0} not exists".format(configFileName)) try: self.cfgParser = ConfigParser() self.cfgParser.read(configFileName) except Exception, e: raise AgentException(e)
def __start__(self): try: if os.fork() > 0: sys.exit(0) except OSError, e: raise AgentException("fork #1 failed: %d (%s)" % (e.errno, e.strerror))
def __init__(self): """ 命令行解析类,命令行参数优先于配置文件:如果相同一个参数,既在配置文件中配置了, 又在命令行参数中进行了设置,则命令行参数的设置将覆盖配置文件中的配置 """ usage = "usage: %prog [-option]" parser = OptionParser(usage) parser.add_option("-c", "--console", action="store_true", dest="console", help="前台运行") parser.add_option("-f", "--defaults-file", dest="configFile", help="指定agent的配置文件") self.configFile = "/etc/IMAgent/agent.cnf" self.console = False try: (options, args) = parser.parse_args() if options.console: self.console = options.console if options.configFile: self.configFile = options.configFile except SystemExit, e: raise AgentException(e)
def initConfig(path, config): cfgParser = AgentConfigParser(path) sections = cfgParser.getSections() for section in sections: if config.check(section) == None: raise AgentException( "AgentConfigManager.initConfig unknown section {0}".format( section)) items = cfgParser.getItems(section) for item in items: f = 'set_' + section + '_' + item[0].split('_')[0] try: getattr(config, f)(item[0], item[1]) except AttributeError: raise AgentException( "AgentConfigManager.initConfig unknown item {0}". format(item))
def createDataBase(name, attr): try: url = 'from imagent.' + name + '.' + name + ' import ' + name exec url return eval(name)(attr) except KeyError, e: raise AgentException('DataBaseManager.createDataBase KeyError:%s' % e)
def set_monitors_attr(self, key, val): keys = key.split('_') if len(keys) < 2: raise AgentException('setMonitorsInterval unknown attr') if keys[1] not in self.monitors['attr'].keys(): self.monitors['attr'][keys[1]] = {keys[2]: val} else: self.monitors['attr'][keys[1]][keys[2]] = val
def execSql(self, sql, db=None): try: conn = self.getConnection(db=db) conn.autocommit(True) cursor = conn.cursor() try: cursor.execute(sql) rows = cursor.fetchall() cursor.close() conn.close() return rows except Exception, e: cursor.close() raise AgentException("execute sql '%s' error:%s" % (sql, e)) except Exception, e: raise AgentException("connect execute sql '%s' error:%s" % (sql, e))
def stop(self): """ 程序退出时调用,在进程退出时,删除pid文件 """ AgentLog.info("RDS Agent start to exit") try: os.remove(self.__pidFile__) except: AgentLog.warning("remove pid file {0} error".format( self.__pidFile__)) raise AgentException("remove pid file {0} error".format( self.__pidFile__))
def start(self): """ 把进程pid写入到对应的pid文件 """ AgentLog.info("RDS Agent start to run") try: file = open(self.__pidFile__, 'wt') file.write(str(os.getpid())) file.close() except: AgentLog.error("open pid file {0} error, start failed".format( self.__pidFile__)) raise AgentException("open pid file {0} failed".format( self.__pidFile__))
class DataBaseManager(object): @staticmethod def createDataBase(name, attr): try: url = 'from imagent.' + name + '.' + name + ' import ' + name exec url return eval(name)(attr) except KeyError, e: raise AgentException('DataBaseManager.createDataBase KeyError:%s' % e) except AttributeError, e: # AgentLog.error('DataBaseManager.createDataBase config name is error value: %s'%dbConfig['name']) raise AgentException( 'DataBaseManager.createDataBase config name is error value: %s' % name)
class Daemon: def __init__(self): self.__start__() def __start__(self): try: if os.fork() > 0: sys.exit(0) except OSError, e: raise AgentException("fork #1 failed: %d (%s)" % (e.errno, e.strerror)) os.chdir("/") os.setsid() os.umask(0) try: if os.fork() > 0: sys.exit(0) except OSError, e: raise AgentException("fork #2 failed: %d (%s)" % (e.errno, e.strerror))
#coding=utf-8 from imagent.core.common.AgentException import AgentException from imagent.core.common.AgentFileException import AgentFileException class DataBaseManager(object): @staticmethod def createDataBase(name, attr): try: url = 'from imagent.' + name + '.' + name + ' import ' + name exec url return eval(name)(attr) except KeyError, e: raise AgentException('DataBaseManager.createDataBase KeyError:%s' % e) except AttributeError, e: # AgentLog.error('DataBaseManager.createDataBase config name is error value: %s'%dbConfig['name']) raise AgentException( 'DataBaseManager.createDataBase config name is error value: %s' % name) except TypeError, e: # AgentLog.error('DataBaseManager.createDataBase config attar is error value: %s'%dbConfig['attr']) raise AgentException( 'DataBaseManager.createDataBase config attar is error value: %s' % attr) except AgentFileException, e: raise AgentException('DataBaseManager.createDataBase error: %s' % e)
def info(msg): try: AgentLog.logger.info(msg) except AttributeError: raise AgentException('AgentLog has not inited')
def critical(msg): try: AgentLog.logger.critical(msg + 'stack:%s' % traceback.format_exc()) except AttributeError: raise AgentException('AgentLog has not inited')
def init(config_file='log.cnf', section="normal"): try: logging.config.fileConfig(config_file) AgentLog.logger = logging.getLogger(section) except Exception, e: raise AgentException('Agent init Error:%s' % e)
def set_monitors_interval(self, key, interval): keys = key.split('_') if len(keys) != 2: raise AgentException('setMonitorsInterval unknown attr') self.monitors['interval'][keys[1]] = interval
def set_database_attr(self, key, attr): keys = key.split('_') if len(keys) != 2: raise AgentException('setDBAttr unknown attr') self.database['attr'][keys[1]] = attr