def doHandling(HandlerClass): global expect expect = HandlerClass.__name__ #'MyExcHandler' excHandler = HandlerClass() pub.setListenerExcHandler(excHandler) pub.sendMessage(testTopic) assert expect is None
def main(): #setup_logging() #logger = logging.getLogger() #logger.info("XBGW App Version: {}".format(version)) # Make sure we're the only instance of the app on this system prevent_duplicate(PID_FILE) # Catch and log exceptions unhandled by listeners pub.setListenerExcHandler(PubsubExceptionHandler()) # Create the settings file if it does not exist already. # TODO: Consider moving into load_from_json as managing the # settings file should arguably be done by the SettingsRegistry if not os.path.exists(SETTINGS_FILE): with open(SETTINGS_FILE, "w") as f: f.write("{}") settings = SettingsRegistry() settings.load_from_json(SETTINGS_FILE) # Create PubSub participants #manager = XBeeEventManager() print("Data ready for input.") DDOEventManager() dcrep = AWSPush(settings, "devicecloud") for topic in manager.data_topics: dcrep.start_reporting(topic) # timeout is 30 seconds by default, but that is far too slow for our # purposes. Set the timeout to 100 ms. (Value may be fine tuned later) asyncore.loop(timeout=0.1)
def testNoExceptionHandling1(): pub.setListenerExcHandler(None) def raises(): raise RuntimeError('test') topicMgr.getOrCreateTopic('testNoExceptionTrapping') pub.subscribe(raises, 'testNoExceptionTrapping') pytest.raises( RuntimeError, pub.sendMessage, 'testNoExceptionTrapping')
def testNoExceptionHandling1(): pub.setListenerExcHandler(None) def raises(): raise RuntimeError('test') topicMgr.getOrCreateTopic('testNoExceptionTrapping') pub.subscribe(raises, 'testNoExceptionTrapping') pytest.raises(RuntimeError, pub.sendMessage, 'testNoExceptionTrapping')
def testHandleExcept1a(): from pubsub.utils.exchandling import ExcPublisher excPublisher = ExcPublisher( pub.getDefaultTopicMgr() ) pub.setListenerExcHandler(excPublisher) # create a listener that raises an exception: from raisinglistener import getRaisingListener raisingListener = getRaisingListener() pub.setNotificationFlags(all=False) pub.subscribe(raisingListener, 'testHandleExcept1a') # first test when a listener raises an exception and exception listener also raises! class BadUncaughtExcListener: def __call__(self, listenerStr=None, excTraceback=None): raise RuntimeError('bad exception listener!') handler = BadUncaughtExcListener() pub.subscribe(handler, ExcPublisher.topicUncaughtExc) pytest.raises(pub.ExcHandlerError, pub.sendMessage, 'testHandleExcept1a') pub.unsubscribe(handler, ExcPublisher.topicUncaughtExc)
def testHandleExcept1a(): from pubsub.utils.exchandling import ExcPublisher excPublisher = ExcPublisher(pub.getDefaultTopicMgr()) pub.setListenerExcHandler(excPublisher) # create a listener that raises an exception: from raisinglistener import getRaisingListener raisingListener = getRaisingListener() pub.setNotificationFlags(all=False) pub.subscribe(raisingListener, 'testHandleExcept1a') # first test when a listener raises an exception and exception listener also raises! class BadUncaughtExcListener: def __call__(self, listenerStr=None, excTraceback=None): raise RuntimeError('bad exception listener!') handler = BadUncaughtExcListener() pub.subscribe(handler, ExcPublisher.topicUncaughtExc) pytest.raises(pub.ExcHandlerError, pub.sendMessage, 'testHandleExcept1a') pub.unsubscribe(handler, ExcPublisher.topicUncaughtExc)
def testHandleExcept2(): #Test sendMessage when one handler, then change handler and verify changed testTopic = 'testTopics.testHandleExcept2' pub.subscribe(throws, testTopic) pub.setListenerExcHandler(None) #pubsub.utils.notification.useNotifyByWriteFile() #assert_equal( topicMgr.getTopic(testTopic).getNumListeners(), 1 ) expect = None def validate(className): global expect assert expect == className expect = None class MyExcHandler: def __call__(self, listener, topicObj): validate(self.__class__.__name__) class MyExcHandler2: def __call__(self, listener, topicObj): validate(self.__class__.__name__) def doHandling(HandlerClass): global expect expect = HandlerClass.__name__ #'MyExcHandler' excHandler = HandlerClass() pub.setListenerExcHandler(excHandler) pub.sendMessage(testTopic) assert expect is None doHandling(MyExcHandler) doHandling(MyExcHandler2) # restore to no handling and verify: pub.setListenerExcHandler(None) pytest.raises(RuntimeError, pub.sendMessage, testTopic)
def testHandleExcept2(): #Test sendMessage when one handler, then change handler and verify changed testTopic = 'testTopics.testHandleExcept2' pub.subscribe(throws, testTopic) pub.setListenerExcHandler(None) #pubsub.utils.notification.useNotifyByWriteFile() #assert_equal( topicMgr.getTopic(testTopic).getNumListeners(), 1 ) expect = None def validate(className): global expect assert expect == className expect = None class MyExcHandler: def __call__(self, listener, topicObj): validate(self.__class__.__name__) class MyExcHandler2: def __call__(self, listener, topicObj): validate(self.__class__.__name__) def doHandling(HandlerClass): global expect expect = HandlerClass.__name__ #'MyExcHandler' excHandler = HandlerClass() pub.setListenerExcHandler(excHandler) pub.sendMessage(testTopic) assert expect is None doHandling(MyExcHandler) doHandling(MyExcHandler2) # restore to no handling and verify: pub.setListenerExcHandler(None) pytest.raises( RuntimeError, pub.sendMessage, testTopic)
def main(): setup_logging() logger = logging.getLogger() logger.info("XBGW App Version: {}".format(version)) # Make sure we're the only instance of the app on this system prevent_duplicate(PID_FILE) # Catch and log exceptions unhandled by listeners pub.setListenerExcHandler(PubsubExceptionHandler()) # Create the settings file if it does not exist already. # TODO: Consider moving into load_from_json as managing the # settings file should arguably be done by the SettingsRegistry if not os.path.exists(SETTINGS_FILE): with open(SETTINGS_FILE, "w") as f: f.write("{}") settings = SettingsRegistry() settings.load_from_json(SETTINGS_FILE) # Create PubSub participants XBeeEventManager(settings, "xbee_manager") DDOEventManager() shcrep = SelfHostedCloudReporter(settings, "selfhostedcloud") rciproc = RCICommandProcessor() echo_cmd = EchoCommand() # Subscribe to all topics that XBeeEventManager publishes for topic in XBeeEventManager.data_topics: shcrep.start_reporting(topic) # timeout is 30 seconds by default, but that is far too slow for our # purposes. Set the timeout to 100 ms. (Value may be fine tuned later) asyncore.loop(timeout=0.1)
def main(): setup_logging() logger = logging.getLogger() logger.info("XBGW App Version: {}".format(version)) # Make sure we're the only instance of the app on this system prevent_duplicate(PID_FILE) # Catch and log exceptions unhandled by listeners pub.setListenerExcHandler(PubsubExceptionHandler()) # Create the settings file if it does not exist already. # TODO: Consider moving into load_from_json as managing the # settings file should arguably be done by the SettingsRegistry if not os.path.exists(SETTINGS_FILE): with open(SETTINGS_FILE, "w") as f: f.write("{}") settings = SettingsRegistry() settings.load_from_json(SETTINGS_FILE) # Create PubSub participants XBeeEventManager(settings, "xbee_manager") DDOEventManager() dcrep = DeviceCloudReporter(settings, "devicecloud") rciproc = RCICommandProcessor() echo_cmd = EchoCommand() # Subscribe to all topics that XBeeEventManager publishes for topic in XBeeEventManager.data_topics: dcrep.start_reporting(topic) # timeout is 30 seconds by default, but that is far too slow for our # purposes. Set the timeout to 100 ms. (Value may be fine tuned later) asyncore.loop(timeout=0.1)
# Internal imports. import paasmaker # Logging setup. import logging logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO) # Setup pubsub exception handling. # Just log the exception, and continue on to the next handler. class PaasmakerPubSubExceptionHandler(IExcHandler): def __call__(self, listenerID, topicObj): logging.error("Exception in pub/sub handler:", exc_info=True) logging.error("Listener ID: %s", listenerID) pub.setListenerExcHandler(PaasmakerPubSubExceptionHandler()) # Parse command line options. options.parse_command_line() # Load configuration logging.info("Loading configuration...") configuration = paasmaker.common.configuration.Configuration() configuration.load_from_file(['paasmaker.yml', '/etc/paasmaker/paasmaker.yml']) # Reset the log level. logging.info("Resetting server log level to %s.", configuration['server_log_level']) logger = logging.getLogger() logger.setLevel(getattr(logging, configuration['server_log_level'])) configuration.dump()
''' :copyright: Copyright 2006-2009 by Oliver Schoenborn, all rights reserved. :license: BSD, see LICENSE.txt for details. ''' from pubsub import pub from pubsub.utils.exchandling import IExcHandler, TracebackInfo # create one special notification handler that ignores all except # one type of notification class MyPubsubExcHandler(IExcHandler): def __call__(self, listenerID): print 'Exception raised in listener %s during sendMessage()' % listenerID print TracebackInfo() pub.setListenerExcHandler(MyPubsubExcHandler())
def __init__(self): # Register PubSubEnv exception handler. if not self._singleton_init: self._singleton_init = True pub.setListenerExcHandler(PubSubEnv.PubSubEnvExceptionHandler())
def __init__(self, import_name): """Creates the Chalice GitHubApp Blueprint.""" super().__init__(import_name) pub.setListenerExcHandler(ExcPublisher(pub.getDefaultTopicMgr()))
def set_exception_handler(): """Set the pubsub exception handler. This should only be run for debugging purposes. """ pub.setListenerExcHandler(ListenerExceptionHandler())
""" :copyright: Copyright since 2006 by Oliver Schoenborn, all rights reserved. :license: BSD, see LICENSE.txt for details. """ from pubsub import pub from pubsub.py2and3 import print_ # create one special notification handler that ignores all except # one type of notification class MyPubsubExcHandler(pub.IListenerExcHandler): def __call__(self, listenerID): print_('Exception raised in listener %s during sendMessage()' % listenerID) print_(TracebackInfo()) pub.setListenerExcHandler( MyPubsubExcHandler() )
raise Exception("Test Exception") logging.info("Listener [{}] - Message: {}".format(self._id, msg)) return def do_timer_event(self, msg: str): logging.info("Timer Message: {}".format(msg)) self.__timer_reset() return class ListenerExceptionHandler(pub.IListenerExcHandler): def __call__(self, listener_id, topic_obj): logging.info("Listener [{}] raised an exception".format(listener_id)) pub.setListenerExcHandler(ListenerExceptionHandler()) if __name__ == "__main__": LoggingSetup() topic1 = "Topic1" topic2 = "Topic2" listeners = [ Listener("1"), Listener("2"), Listener("3"), Listener("4"), Listener("5") ]