def testBatchSizeExceedCapacity(self): """Log handles batch size greater than capacity correctly""" self.assertEqual( True, Log.CENTRALHANDLER.capacity >= Log.CENTRALHANDLER.batchsize) Log.setBatchSize(Log.CENTRALHANDLER.capacity + 2) self.assertEqual(Log.CENTRALHANDLER.capacity, Log.CENTRALHANDLER.batchsize)
def testLoggerNamesRequestedFiltered(self): """SeveralLoggerCheck getLoggerNames returns correct logger names when requested with filtering""" self.assertEquals(True, self.cname in Log.getLoggerNames(self.pname[:-1])) self.assertEquals(True, self.pname in Log.getLoggerNames(self.pname[:-1])) self.assertEquals([self.cname], Log.getLoggerNames(self.cname))
def shutdown(self, action): ''' Shutdown the Container. Normally invoked via CORBA but can also "self terminate" so to speak. Parameters: - action is an encrypted value that tells the container what action to take oneway void shutdown (in unsigned long action) ''' action = (action >> 8) & 0xFF if (action == ACTIVATOR_EXIT) or (action == ACTIVATOR_REBOOT) or (action == ACTIVATOR_RELOAD): self.logger.logTrace("Shutting down container: " + self.name) #Logout from manager ACSCorba.getManager().logout(self.token.h) if (action == ACTIVATOR_REBOOT) or (action == ACTIVATOR_RELOAD): print "Container.shutdown(): Action may not work correctly...-", str(action) self.__init__(self.name) else: #tell the main thread of execution to stop self.running = 0 Log.stopPeriodicFlush() else: self.logger.logWarning("Unable to process 'shutdown' request at this time: " + str(action)) # Close the alarm interface factory Acsalarmpy.AlarmSystemInterfaceFactory.done()
def testSetDefaultLevels(self): """Log sets default handlers levels correctly for valid inputs""" for k in Log.LEVELS: Log.setDefaultLevels( maci.LoggingConfigurable.LogLevels(False, k, k)) self.assertEqual(Log.LEVELS[k], Log.DEFAULTLOCALHANDLER.level) self.assertEqual(Log.LEVELS[k], Log.DEFAULTCENTRALHANDLER.level)
def testLoggerDefault(self): """SeveralLoggerCheck Levels changes on all loggers using default level""" Log.setDefaultLevels(maci.LoggingConfigurable.LogLevels(False,4, 5)) self.assertEquals(True, self.plogger.usingDefault) self.assertEquals(True, self.clogger.usingDefault) self.assertEquals(Log.DEFAULTLOCALHANDLER.level, self.plogger.stdouthandler.level) self.assertEquals(Log.DEFAULTCENTRALHANDLER.level, self.plogger.acshandler.level) self.assertEquals(Log.DEFAULTLOCALHANDLER.level, self.clogger.stdouthandler.level) self.assertEquals(Log.DEFAULTCENTRALHANDLER.level, self.plogger.acshandler.level)
def testCycleStartStop(self): """PeriodicFlushCheck flushing thread start and stops correctly.""" Log.startPeriodicFlush() self.assertEqual(Log.DEFAULT_FLUSH_PERIOD, Log.INTERVAL) self.assertEqual(True, isinstance(Log.SCHEDULER, sched.scheduler)) self.assertEqual(True, isinstance(Log.FLUSHTHREAD, threading.Thread)) self.assertEqual(True, Log.FLUSHTHREAD.isAlive()) self.assertEqual(False, Log.NEXTEVENT is None) Log.stopPeriodicFlush() self.assertEqual(False, Log.FLUSHTHREAD.isAlive())
def set_default_logLevels(self, levels): # pragma: NO COVER ''' Set the default log level for this container. Parameter: levels - maci.LoggingConfigurable.LogLevels instance containing default log level values Raises: Nothing ''' Log.setDefaultLevels(levels)
def testLoggerDefault(self): """SeveralLoggerCheck Levels changes on all loggers using default level""" Log.setDefaultLevels(maci.LoggingConfigurable.LogLevels(False, 4, 5)) self.assertEquals(True, self.plogger.usingDefault) self.assertEquals(True, self.clogger.usingDefault) self.assertEquals(Log.DEFAULTLOCALHANDLER.level, self.plogger.stdouthandler.level) self.assertEquals(Log.DEFAULTCENTRALHANDLER.level, self.plogger.acshandler.level) self.assertEquals(Log.DEFAULTLOCALHANDLER.level, self.clogger.stdouthandler.level) self.assertEquals(Log.DEFAULTCENTRALHANDLER.level, self.plogger.acshandler.level)
def set_logLevels(self, logger_name, levels): """ Set the default log level for this component. Parameter: logger_name - name of the component's logger levels - maci.LoggingConfigurable.LogLevels instance containing default log level values Raises: LoggerDoesNotExistExImpl if the logger is not active. """ if Log.doesLoggerExist(logger_name): Log.getLogger(logger_name).setLevels(levels) else: raise LoggerDoesNotExistExImpl()
def get_logLevels(self, logger_name): """ Retrieve the log levels for a given component. Parameter: logger_name - name of the component's logger Returns: maci.LoggingConfigurable.LogLevels instance containing the logger's log level values Raises: LoggerDoesNotExistExImpl if the logger is not active. """ if Log.doesLoggerExist(logger_name): return Log.getLogger(logger_name).getLevels() else: raise LoggerDoesNotExistExImpl()
def get_logger_names(self): # pragma: NO COVER ''' Retrieve the names of the currently active loggers Returns: list of logger name strings ''' return Log.getLoggerNames()
def testCreation(self): """PeriodicFlushCheck is correct and consistent after import.""" if not Log.isFlushRunning(): self.assertEqual(True, Log.FLUSHTHREAD is None) self.assertEqual(True, Log.SCHEDULER is None) self.assertEqual(True, Log.NEXTEVENT is None) self.assertEqual(True, Log.INTERVAL is None)
def testGetLoggerNames(self): """NoLoggerCheck getLoggerNames when no loggers requested""" # When the entire suite is run together, the name from TestContainer is injected. # This shouldn't happen, but I don't know how to fix it yet. namelist = Log.getLoggerNames() self.assertEquals(True, [] == namelist or ['UnitTestContainer'] == namelist)
def configureComponentLogger(self, name): ''' Configure the logger for the given component name from the values in the CDB. Parameters: name is the name of the component ''' # Each component has an associated logger instance clogger = Log.getLogger(name) # Default levels are used for missing values defaultlevels = Log.getDefaultLevels() try: #Get the global unnamed logging config to retrieve the maxLogsPerSecond attribute logconfigG = self.cdbAccess.getElement("MACI/Containers/" + self.name + "/LoggingConfig", "LoggingConfig") maxLogsPerSec = int(logconfigG[0]['maxLogsPerSecond']) except (Exception): # No value was supplied so default is used maxLogsPerSec = -1 try: # Process all the named logger configurations logconfig = self.cdbAccess.getElement("MACI/Containers/" + self.name + "/LoggingConfig", "LoggingConfig/log:_") for cfg in logconfig: if cfg["Name"] == name: try: centrallevel = int(cfg['minLogLevel']) except KeyError: # No value was supplied so default is used centrallevel = defaultlevels.minLogLevel try: locallevel = int(cfg['minLogLevelLocal']) except KeyError: # No value was supplied so default is used locallevel = defaultlevels.minLogLevelLocal clogger.setLevels(maci.LoggingConfigurable.LogLevels(False, centrallevel, locallevel)) clogger.configureLogging(maxLogsPerSec) # There should only be one entry per logger so we are done break else: # No matching named logger was found so the default values are used clogger.setLevels(maci.LoggingConfigurable.LogLevels(True, 0, 0)) except Exception: # No named loggers were defined so the default values are used clogger.setLevels(maci.LoggingConfigurable.LogLevels(True, 0, 0))
def testNestedOutput(self): """SeveralLoggerCheck messages are logged only once for nested loggers""" nlogger = Log.getLogger("MyLogger1.child") before = len(Log.CENTRALHANDLER.buffer) nlogger.logInfo("Nested Message") after = len(Log.CENTRALHANDLER.buffer) self.assertEqual(1, after - before) Log.CENTRALHANDLER.buffer = []
def setUp(self): self.mylogger = Log.Logger("mylogger") self.mylogger.acshandler = mock.Mock(spec=Log.ACSHandler) self.mylogger.stdouthandler = mock.Mock() self.mylogger.handlers[0] = self.mylogger.stdouthandler self.mylogger.handlers[1] = self.mylogger.acshandler self.mylogger.acshandler.level = 0 self.mylogger.stdouthandler.level = 0
def testSetFlushInterval(self): """PeriodicFlushCheck updates flush interval correctly""" Log.startPeriodicFlush() now = time.time() next = Log.NEXTEVENT Log.setFlushInterval(5) self.assertNotEqual(next, Log.NEXTEVENT) self.assertAlmostEqual(now + Log.INTERVAL, Log.NEXTEVENT[0], 1) Log.stopPeriodicFlush() Log.setFlushInterval(Log.DEFAULT_FLUSH_PERIOD)
def testSetFlushInterval(self): """PeriodicFlushCheck updates flush interval correctly""" Log.startPeriodicFlush() now = time.time() next = Log.NEXTEVENT Log.setFlushInterval(5) self.assertNotEqual(next, Log.NEXTEVENT) self.assertAlmostEqual(now + Log.INTERVAL, Log.NEXTEVENT[0],1) Log.stopPeriodicFlush() Log.setFlushInterval(Log.DEFAULT_FLUSH_PERIOD)
def get_default_logLevels(self): # pragma: NO COVER ''' Retrieve the default log levels used in this container. Returns: maci.LoggingConfigurable.LogLevels instance containing default log level values Raises: Nothing ''' return Log.getDefaultLevels()
def __init__(self, sourceName=None, hostName=None): """ Create an instance of the AlarmSystemInterface. Parameters: sourceName is the name of this source hostName is the name of the computer where the source is running. """ self.logger = Log.getLogger() self.sourceName = sourceName self.hostName = hostName self.configuration = ASI.ASIConfiguration()
def __init__(self, sourceName = None, hostName = None): """ Create an instance of the AlarmSystemInterface. Parameters: sourceName is the name of this source hostName is the name of the computer where the source is running. """ self.logger = Log.getLogger() self.sourceName = sourceName self.hostName = hostName self.configuration = ASI.ASIConfiguration()
def testDoubleStart(self): """PeriodicFlushCheck only one thread is created if start is called twice.""" Log.startPeriodicFlush() ft = Log.FLUSHTHREAD sc = Log.SCHEDULER ne = Log.NEXTEVENT Log.startPeriodicFlush() self.assertEqual(ft, Log.FLUSHTHREAD) self.assertEqual(sc, Log.SCHEDULER) self.assertEqual(ne, Log.NEXTEVENT) Log.stopPeriodicFlush()
def tearDown(self): Log.setDefaultLevels(maci.LoggingConfigurable.LogLevels(False, 3, 3)) self.plogger.setLevels(maci.LoggingConfigurable.LogLevels(True, 0, 0)) self.clogger.setLevels(maci.LoggingConfigurable.LogLevels(True, 0, 0))
def testExists(self): """SeveralLoggerCheck search with parent key""" self.assertEqual(True, Log.doesLoggerExist(self.pname))
def testSetImmediateDispatchLevel(self): """Log sets immediate dispatch level correctly""" self.assertEqual(Log.LEVELS[10], Log.CENTRALHANDLER.dispatchlevel) Log.setImmediateDispatchLevel(3) self.assertEqual(Log.LEVELS[3], Log.CENTRALHANDLER.dispatchlevel)
def testLoggerNamesRequested(self): """SeveralLoggerCheck getLoggerNames returns all known loggers""" self.assertEquals(Log.logging.Logger.manager.loggerDict.keys(), Log.getLoggerNames())
def setUp(self): self.pname = "MyLogger1" self.plogger = Log.getLogger(self.pname) self.cname = "MyLogger2" self.clogger = Log.getLogger(self.cname)
def testUnnamedLoggerNamesList(self): """OneLoggerCheck names list has unnamed logger when filtered by unnamed logger""" self.assertEquals([self.mylogger.name], Log.getLoggerNames(self.mylogger.name))
def testBoundaryDispatchLevel(self): """Log handles lowest and highest immediate dispatch level correctly""" Log.setImmediateDispatchLevel(0) self.assertEqual(Log.LEVELS[0], Log.CENTRALHANDLER.dispatchlevel) Log.setImmediateDispatchLevel(99) self.assertEqual(Log.LEVELS[99], Log.CENTRALHANDLER.dispatchlevel)
def testNone(self): """NoLoggerCheck logger search with no key""" self.assertEqual(False, Log.doesLoggerExist(None))
def setUp(self): self.mylogger = Log.getLogger()
def testExistsNested(self): """SeveralLoggerCheck search with the nested child's name as key""" self.assertEqual(True, Log.doesLoggerExist(self.cname))
def testExistsPartial(self): """SeveralLoggerCheck search with part of an exising key""" self.assertEqual(False, Log.doesLoggerExist("child"))
def testSetFlushIntervalInvalid(self): """PeriodicFlushCheck flush thread stopped when invalid interval is set""" Log.startPeriodicFlush() Log.setFlushInterval(-5) self.assertEqual(False, Log.FLUSHTHREAD.isAlive())
def testUnnamedLoggerExists(self): """OneLoggerCheck unnamed logger found by search""" self.assertEqual(True, Log.doesLoggerExist(self.mylogger.name))
def tearDown(self): Log.setDefaultLevels(maci.LoggingConfigurable.LogLevels(False,3, 3)) self.plogger.setLevels(maci.LoggingConfigurable.LogLevels(True,0, 0)) self.clogger.setLevels(maci.LoggingConfigurable.LogLevels(True,0, 0))
def setUp(self): self.logger = Log.getLogger("dispatchcheck") self.logger.stdouthandler = mock.Mock() self.logger.handlers[0] = self.logger.stdouthandler Log.CENTRALHANDLER.buffer = []
def testWrong(self): """SeveralLoggerCheck Search with non-existing key""" self.assertEqual(False, Log.doesLoggerExist("blah"))
def testInvalidBatchSize(self): """Log handles invalid batch size correctly""" self.assertEqual(10, Log.CENTRALHANDLER.batchsize) Log.setBatchSize(-2) self.assertEqual(0, Log.CENTRALHANDLER.batchsize)
class AlarmSystemInterfaceFactory(object): """ Base class for creating sources and fault states. """ logger = Log.getLogger("AlarmSystemInterfaceFactory") manager = None systemtype = None initialized = False registry = {} @classmethod def init(cls, man=None): """ Initializes the factory. This method must be called before using the other methods of this class. Returns: None """ cls.logger.logTrace("AlarmSystemInterfaceFactory::init() entering.") cls.manager = man cls.initialized = True try: import ACSAlarmSystemInterfaceProxy as ACSProxy cls.registry['ACS'] = ACSProxy.ACSAlarmSystemInterfaceProxy except: pass try: import CERNAlarmSystemInterfaceProxy as CERNProxy cls.registry['CERN'] = CERNProxy.CERNAlarmSystemInterfaceProxy except: pass # Parse the CDB to get the system type cdb = CDBAccess.CDBaccess() try: ln = cdb.getField( 'Alarms/Administrative/AlarmSystemConfiguration', 'AlarmSystemConfiguration/configuration-property') doc = AcsAlarmSystem_xsd.minidom.parseString(ln) rootNode = doc.documentElement rootObj = AcsAlarmSystem_xsd.alarm_system_configurationListType.factory( ) rootObj.build(rootNode) cls.systemtype = rootObj.get_configuration_property()[0].valueOf_ except: cls.systemtype = 'ACS' cls.logger.logDebug("Using %s alarm system" % cls.systemtype) cls.logger.logTrace("AlarmSystemInterfaceFactory::init() exiting.") @classmethod def done(cls): """ Release the resources held by the factory. This method must be called when the client is finished using the factory. Returns: None """ cls.logger.logTrace("AlarmSystemInterfaceFactory::done() entering.") cls.manager = None cls.initialized = False cls.systemtype = None cls.registry = {} cls.logger.logTrace("AlarmSystemInterfaceFactory::done() exiting.") @classmethod def createSource(cls, sourceName=None): """ Create a new instance of an alarm system interface. Parameters: sourceName is the name of the alarm source Returns: an instance of the appropriate interface Raises: exception if factory has not been initialized """ cls.logger.logTrace( "AlarmSystemInterfaceFactory::createSource() entering.") if not cls.initialized: raise ErrFactory.ACSASFactoryNotInitedExImpl() cls.logger.logTrace( "AlarmSystemInterfaceFactory::createSource() exiting.") return cls.registry[cls.systemtype](sourceName) @classmethod def createFaultState(cls, family=None, member=None, code=None): """ Create a new instance of a fault state. Parameters: family is the name of the alarm family for this fault member is the name of the member of the alarm family for this fault code is the error code for this fault Returns: an instance of FaultState Raises: exception if factory has not been initialized """ cls.logger.logTrace( "AlarmSystemInterfaceFactory::createFaultState() entering.") if not cls.initialized: raise ErrFactory.ACSASFactoryNotInitedExImpl() cls.logger.logTrace( "AlarmSystemInterfaceFactory::createFaultState() exiting.") return FaultState.FaultState(family, member, code)
def testBatchSize(self): """Log changes log batch size correctly""" self.assertEqual(10, Log.CENTRALHANDLER.batchsize) self.assertEqual(1000, Log.CENTRALHANDLER.capacity) Log.setBatchSize(15) self.assertEqual(15, Log.CENTRALHANDLER.batchsize)
def testSetDefaultLevels(self): """Log sets default handlers levels correctly for valid inputs""" for k in Log.LEVELS: Log.setDefaultLevels(maci.LoggingConfigurable.LogLevels(False, k, k)) self.assertEqual(Log.LEVELS[k], Log.DEFAULTLOCALHANDLER.level) self.assertEqual(Log.LEVELS[k], Log.DEFAULTCENTRALHANDLER.level)
def testSetFlushIntervalInvalid(self): """PeriodicFlushCheck flush thread stopped when invalid interval is set""" Log.startPeriodicFlush() Log.setFlushInterval(-5) self.assertEqual(False, Log.FLUSHTHREAD.isAlive()) Log.stopPeriodicFlush()
def setUp(self): self.logger = Log.getLogger("dispatchcheck") self.logger.stdouthandler = mock.Mock() self.logger.handlers[0] = self.logger.stdouthandler