Пример #1
0
    def __init__(self, channelname, component=None, domain=None):
        '''
        Constructor.

        Params:
        - channelName is the channel name
        - component is the component this supplier has been instantiated from
        (if applicable). This parameter is likely to become mandatory in future
        version of ACS
        - domain is the name of the domain of notification channels the channel
        belongs to


        Returns: Nothing

        Raises: ACSErrTypeCommonImpl.CORBAProblemExImpl on critical failures
        '''

        #Logger for this supplier
        self.logger = getLogger(str(channelname) + "-Supplier")

        #Call the super's constructor
        CommonNC.__init__(self, channelname, component, domain)

        #CORBA ref to the channels supplier admin
        self.supplierAdmin = None
        #CORBA ref to this suppliers structured proxy push consumer
        self.sppc = None
        #number of events sent so far
        self.count = 0

        #Handle all of the CORBA stuff now
        CommonNC.initCORBA(self)
        self.initCORBA()
Пример #2
0
    def __init__ (self, channelname, component=None, domain=None):
        '''
        Constructor.

        Params:
        - channelName is the channel name
        - component is the component this supplier has been instantiated from
        (if applicable). This parameter is likely to become mandatory in future
        version of ACS
        - domain is the name of the domain of notification channels the channel
        belongs to


        Returns: Nothing

        Raises: ACSErrTypeCommonImpl.CORBAProblemExImpl on critical failures
        '''
        
        #Logger for this supplier
        self.logger = getLogger(str(channelname) + "-Supplier")

        #Call the super's constructor
        CommonNC.__init__(self, channelname, component, domain)
        
        #CORBA ref to the channels supplier admin
        self.supplierAdmin = None  
        #CORBA ref to this suppliers structured proxy push consumer
        self.sppc = None
        #number of events sent so far
        self.count = 0

        #Handle all of the CORBA stuff now
        CommonNC.initCORBA(self)
        self.initCORBA()
Пример #3
0
    def __init__ (self, name, component=None, domain=None):
        '''
        Constructor.

        Params:
        - name is the channel name in string format
        - component is the component this supplier has been instantiated from
        (if applicable). This parameter is likely to become mandatory in future
        version of ACS
        - domain is the name of the domain of notification channels the channel
        belongs to

        Returns: Nothing

        Raises: ACSErrTypeCommonImpl.CORBAProblemExImpl on critical failures
        '''
        self.logger = getLogger(str(name) + "-Consumer")

        #Call the super's constructor
        CommonNC.__init__(self, name, component, domain)
        
        #CORBA ref to the channels consumer admin
        self.consumerAdmin = None  
        #CORBA ref to this consumers structured proxy push supplier
        self.spps = None
        #Dictionary containing handler functions for different object types
        self.handlers = {}
        #dictionary mapping events to the total amount of time they have
        #to finish
        self.handlerTimeoutDict = getEventHandlerTimeoutDict(name)
        #profiler to time how long it takes events to be processed
        self.profiler = Profiler()
        #Is the consumer suspended?
        self.suspended = False
        #Lock used to read & write suspended attribute
        self.lockAction = threading.Lock()
       
        #Handle all of the CORBA stuff now
        CommonNC.initCORBA(self)
        self.initCORBA()
        self.__buffer_max_size = 100
        self.__buffer = Queue.Queue(self.__buffer_max_size);
        self.__stop_thread = False
        self.__thread = Thread(target=self.__process_event)
        self.__thread.setDaemon(True)
        self.__thread.start()
Пример #4
0
 def test_object_initialization_domain(self):
     """CommonNC initialization with domain"""
     nc = CommonNC("Channel", mock.Mock(), "Domain")
     self.assertEqual(0, nc.connected)
     self.assertEqual('Channel', nc.channelName)
     self.assertEqual(True, isinstance(nc.component, mock.Mock))
     self.assertEqual('Domain', nc.domainName)
     self.assertEqual(True, nc.evtChan is None)
     self.assertEqual(True, nc.nt is None)
Пример #5
0
 def test_object_initialization_no_domain(self):
     """CommonNC initialization with default domain"""
     nc = CommonNC("Channel", mock.Mock())
     self.assertEqual(0, nc.connected)
     self.assertEqual('Channel', nc.channelName)
     self.assertEqual(True, isinstance(nc.component, mock.Mock))
     self.assertEqual(NAMESERVICE_BINDING_NC_DOMAIN_DEFAULT, nc.domainName)
     self.assertEqual(True, nc.evtChan is None)
     self.assertEqual(True, nc.nt is None)
Пример #6
0
 def test_object_initialization_default(self):
     """CommonNC default initialization"""
     nc = CommonNC(None, None)
     self.assertEqual(0, nc.connected)
     self.assertEqual('None', nc.channelName)
     self.assertEqual(True, nc.component is None)
     self.assertEqual(NAMESERVICE_BINDING_NC_DOMAIN_DEFAULT, nc.domainName)
     self.assertEqual(True, nc.evtChan is None)
     self.assertEqual(True, nc.nt is None)
Пример #7
0
    def reinitConnection(self):
        '''
        Consumer reinitializes the connection to the Channel.

        Parameters: None
        
        Returns: Nothing

        Raises: ACSErrTypeCommonImpl.CORBAProblemExImpl on critical failures
        '''
        oldChannelTimestamp = self.channelTimestamp
        try:
            CommonNC.initCORBA(self)
            self.initCORBA()
            self.spps.connect_structured_push_consumer(self._this())
        except:
            self.channelTimestamp = oldChannelTimestamp
            raise
        self.logger.logInfo("Consumer reconnected to the channel '%s'"%(self.channelName))
Пример #8
0
class TestCommonNC(unittest.TestCase):
    def setUp(self):
        Acspy.Util.ACSCorba.SINGLETON_CLIENT = mock.Mock(spec=Acspy.Util.ACSCorba._Client)
        self.nc = CommonNC("Channel", mock.Mock())
        self.original = sys.stderr
        sys.stderr = mock.Mock(spec=sys.stderr)

    def tearDown(self):
        sys.stderr = self.original
        Acspy.Util.ACSCorba.SINGLETON_CLIENT = None

    @mock.patch_object(Acspy.Nc.CommonNC, "cdb_channel_config_exists", mockNotExists)
    def test_configAdminProps_noconfig(self):
        """CommonNC configAdminProps returns expected value when no CDB configuration defined"""
        self.assertEqual([], self.nc.configAdminProps())

    @mock.patch_object(Acspy.Nc.CommonNC, "cdb_channel_config_exists", mockExists)
    @mock.patch_object(Acspy.Nc.CommonNC, "get_channel_admin_props", mockProps)
    def test_configAdminProps_propsExist(self):
        """CommonNC configAdminProps returns correct values when CDB configuration defined"""
        self.nc.logger = mock.Mock(spec=Acspy.Common.Log.Logger)
        self.assertEqual(["a", "b", "c"], self.nc.configAdminProps())
        self.assertEqual([("logDebug", ("Found admin properties in the CDB",), {})], self.nc.logger.method_calls)

    @mock.patch_object(Acspy.Nc.CommonNC, "cdb_channel_config_exists", mockNotExists)
    def test_configQofS_noconfig(self):
        """CommonNC configQofS returns expected value when no CDB configuration defined"""
        self.assertEqual([], self.nc.configQofS())

    @mock.patch_object(Acspy.Nc.CommonNC, "cdb_channel_config_exists", mockExists)
    @mock.patch_object(Acspy.Nc.CommonNC, "get_channel_qofs_props", mockProps)
    def test_configQofS_propsExist(self):
        """CommonNC configQofS returns correct values when CDB configuration defined"""
        self.nc.logger = mock.Mock(spec=Acspy.Common.Log.Logger)
        self.assertEqual(["a", "b", "c"], self.nc.configQofS())
        self.assertEqual([("logDebug", ("Found Q of S properties in the CDB",), {})], self.nc.logger.method_calls)

    def test_createNotificationChannel_missingFactory(self):
        """CommonNC createNotificationChannel throws correct exception when no EventChannelFactory defined"""
        self.nc.nt = mock.Mock(spec=NameTree.nameTree)

        def side_effect(*args):
            raise CosNaming.NamingContext.NotFound(None, None)

        self.nc.nt.getObject.side_effect = side_effect
        self.nc.getNotificationFactoryNameForChannel = mock.Mock()
        self.nc.getNotificationFactoryNameForChannel.return_value = "NotifyFactory"
        try:
            self.nc.createNotificationChannel()
            self.fail("No Exception thrown")
        except CORBAProblemExImpl, e:
            self.assertEqual(["Unable to get Notification Service"], e.getData("reason"))
            self.assertEqual(["CosNaming.NamingContext.NotFound(why=None, rest_of_name=None)"], e.getData("exception"))
Пример #9
0
    def publishEvent (self,
                      simple_data=None,
                      event_callback=None,
                      type_name=None,
                      event_name="",
                      se=None,
                      supplier_name=None):
        '''
        publishEvent is the one method developers have to use.

        publishEvent() is designed so Supplier does not have to be subclassed.  

        Params:
        - simple_data is a user-defined IDL struct. If this parameter is not
        specified by the developer, se MUST be used.  99% of the time developers
        should specify the simple_data parameter and NOTHING ELSE!
        - event_callback is a reference to the user implemented eventProcessCallback
        the user must implements: eventSent(self, simple_data), 
        eventDropped(self, simple_data) and eventStoredInQueue(self, simple_data)
        methods.
        - type_name is literally the type_name field of a structured event. This
        is an optional parameter and should not be specified under normal
        circumstances. If unspecified, the name of the simple_data object is used.
        - event_name is the event_name field of the structured event. Not really
        useful.
        - se is a fully-defined structured event. If this parameter is specified,
        all other parameters will be completely ignored. A check is made to ensure
        that this object is really what it claims to be. This parameter is
        reserved for ACS internal usage.
        - suppier_name is the name of the supplier publishing the event. This
        parameter is reserved for ACS internal usage.

        Returns: Nothing

        Raises:
        - ACSErrTypeCommonImpl.CORBAProblemExImpl
        - ACSErrTypeCommonImpl.CouldntPerformActionExImpl
        - ACSErrTypeCommonImpl.TypeNotSupportedExImpl
        '''
        #Whoah, user passed in the entire structured event...I'm impressed.
        if se != None:
            #check to make sure it's a structured event first.
            if isinstance(se, CosNotification.StructuredEvent):
                #publish it
                try:
                    self.sppc.push_structured_event(se)
                    return
                except CORBA.OBJECT_NOT_EXIST, e:
                    if self.autoreconnect:
                        # Recreate the channel
	                CommonNC.initCORBA(self)
                        self.initCORBA()
                    raise CORBAProblemExImpl(nvSeq=[NameValue("channelname",
                                                              self.channelName),
                                                    NameValue("exception",
                                                              str(e))])
                except Exception, e:
                    print_exc()
                    raise CORBAProblemExImpl(nvSeq=[NameValue("channelname",
                                                              self.channelName),
                                                    NameValue("exception",
                                                              str(e))])
Пример #10
0
                self.logger.logNotice("Publisher:" + comp_name +
                                      ", Event Type:" + type_name)
            
            self.count = self.count + 1
        except (CORBA.COMM_FAILURE, CORBA.TRANSIENT):
            #Notify Service is down
            if event_callback != None:
                event_callback.eventDropped(simple_data)

        except (CORBA.OBJECT_NOT_EXIST, CORBA.BAD_OPERATION) as e:
            #Notify Service is down
            if self.autoreconnect:
                # Recreate the channel
                channel_recreated = False
                try:
                    CommonNC.initCORBA(self)
                    self.initCORBA()
                    channel_recreated = True
                except Exception, e:
                    channel_recreated = False

                if channel_recreated:
                    # Try to publish again the event
                    try:
                        self.sppc.push_structured_event(se)
                        if event_callback != None:
                            event_callback.eventSent(simple_data)
                    # Event cannot be sent
                    except Exception, e:
                        if event_callback != None:
                            event_callback.eventDropped(simple_data)
Пример #11
0
class TestCommonNC(unittest.TestCase):
    def setUp(self):
        Acspy.Util.ACSCorba.SINGLETON_CLIENT = mock.Mock(
            spec=Acspy.Util.ACSCorba._Client)
        self.nc = CommonNC("Channel", mock.Mock())
        self.original = sys.stderr
        sys.stderr = mock.Mock(spec=sys.stderr)

    def tearDown(self):
        sys.stderr = self.original
        Acspy.Util.ACSCorba.SINGLETON_CLIENT = None

    @mock.patch_object(Acspy.Nc.CommonNC, 'cdb_channel_config_exists',
                       mockNotExists)
    def test_configAdminProps_noconfig(self):
        """CommonNC configAdminProps returns expected value when no CDB configuration defined"""
        self.assertEqual([], self.nc.configAdminProps())

    @mock.patch_object(Acspy.Nc.CommonNC, 'cdb_channel_config_exists',
                       mockExists)
    @mock.patch_object(Acspy.Nc.CommonNC, 'get_channel_admin_props', mockProps)
    def test_configAdminProps_propsExist(self):
        """CommonNC configAdminProps returns correct values when CDB configuration defined"""
        self.nc.logger = mock.Mock(spec=Acspy.Common.Log.Logger)
        self.assertEqual(['a', 'b', 'c'], self.nc.configAdminProps())
        self.assertEqual([('logDebug',
                           ('Found admin properties in the CDB', ), {})],
                         self.nc.logger.method_calls)

    @mock.patch_object(Acspy.Nc.CommonNC, 'cdb_channel_config_exists',
                       mockNotExists)
    def test_configQofS_noconfig(self):
        """CommonNC configQofS returns expected value when no CDB configuration defined"""
        self.assertEqual([], self.nc.configQofS())

    @mock.patch_object(Acspy.Nc.CommonNC, 'cdb_channel_config_exists',
                       mockExists)
    @mock.patch_object(Acspy.Nc.CommonNC, 'get_channel_qofs_props', mockProps)
    def test_configQofS_propsExist(self):
        """CommonNC configQofS returns correct values when CDB configuration defined"""
        self.nc.logger = mock.Mock(spec=Acspy.Common.Log.Logger)
        self.assertEqual(['a', 'b', 'c'], self.nc.configQofS())
        self.assertEqual([('logDebug',
                           ('Found Q of S properties in the CDB', ), {})],
                         self.nc.logger.method_calls)

    def test_createNotificationChannel_missingFactory(self):
        """CommonNC createNotificationChannel throws correct exception when no EventChannelFactory defined"""
        self.nc.nt = mock.Mock(spec=NameTree.nameTree)

        def side_effect(*args):
            raise CosNaming.NamingContext.NotFound(None, None)

        self.nc.nt.getObject.side_effect = side_effect
        self.nc.getNotificationFactoryNameForChannel = mock.Mock()
        self.nc.getNotificationFactoryNameForChannel.return_value = "NotifyFactory"
        try:
            self.nc.createNotificationChannel()
            self.fail("No Exception thrown")
        except CORBAProblemExImpl, e:
            self.assertEqual(['Unable to get Notification Service'],
                             e.getData('reason'))
            self.assertEqual([
                'CosNaming.NamingContext.NotFound(why=None, rest_of_name=None)'
            ], e.getData('exception'))
Пример #12
0
 def setUp(self):
     Acspy.Util.ACSCorba.SINGLETON_CLIENT = mock.Mock(
         spec=Acspy.Util.ACSCorba._Client)
     self.nc = CommonNC("Channel", mock.Mock())
     self.original = sys.stderr
     sys.stderr = mock.Mock(spec=sys.stderr)
Пример #13
0
 def setUp(self):
     Acspy.Util.ACSCorba.SINGLETON_CLIENT = mock.Mock(spec=Acspy.Util.ACSCorba._Client)
     self.nc = CommonNC("Channel", mock.Mock())
     self.original = sys.stderr
     sys.stderr = mock.Mock(spec=sys.stderr)
Пример #14
0
    def publishEvent(self,
                     simple_data=None,
                     event_callback=None,
                     type_name=None,
                     event_name="",
                     se=None,
                     supplier_name=None):
        '''
        publishEvent is the one method developers have to use.

        publishEvent() is designed so Supplier does not have to be subclassed.  

        Params:
        - simple_data is a user-defined IDL struct. If this parameter is not
        specified by the developer, se MUST be used.  99% of the time developers
        should specify the simple_data parameter and NOTHING ELSE!
        - event_callback is a reference to the user implemented eventProcessCallback
        the user must implements: eventSent(self, simple_data), 
        eventDropped(self, simple_data) and eventStoredInQueue(self, simple_data)
        methods.
        - type_name is literally the type_name field of a structured event. This
        is an optional parameter and should not be specified under normal
        circumstances. If unspecified, the name of the simple_data object is used.
        - event_name is the event_name field of the structured event. Not really
        useful.
        - se is a fully-defined structured event. If this parameter is specified,
        all other parameters will be completely ignored. A check is made to ensure
        that this object is really what it claims to be. This parameter is
        reserved for ACS internal usage.
        - suppier_name is the name of the supplier publishing the event. This
        parameter is reserved for ACS internal usage.

        Returns: Nothing

        Raises:
        - ACSErrTypeCommonImpl.CORBAProblemExImpl
        - ACSErrTypeCommonImpl.CouldntPerformActionExImpl
        - ACSErrTypeCommonImpl.TypeNotSupportedExImpl
        '''
        #Whoah, user passed in the entire structured event...I'm impressed.
        if se != None:
            #check to make sure it's a structured event first.
            if isinstance(se, CosNotification.StructuredEvent):
                #publish it
                try:
                    self.sppc.push_structured_event(se)
                    return
                except CORBA.OBJECT_NOT_EXIST, e:
                    if self.autoreconnect:
                        # Recreate the channel
                        CommonNC.initCORBA(self)
                        self.initCORBA()
                    raise CORBAProblemExImpl(nvSeq=[
                        NameValue("channelname", self.channelName),
                        NameValue("exception", str(e))
                    ])
                except Exception, e:
                    print_exc()
                    raise CORBAProblemExImpl(nvSeq=[
                        NameValue("channelname", self.channelName),
                        NameValue("exception", str(e))
                    ])
Пример #15
0
                self.logger.logNotice("Publisher:" + comp_name +
                                      ", Event Type:" + type_name)

            self.count = self.count + 1
        except (CORBA.COMM_FAILURE, CORBA.TRANSIENT):
            #Notify Service is down
            if event_callback != None:
                event_callback.eventDropped(simple_data)

        except (CORBA.OBJECT_NOT_EXIST, CORBA.BAD_OPERATION) as e:
            #Notify Service is down
            if self.autoreconnect:
                # Recreate the channel
                channel_recreated = False
                try:
                    CommonNC.initCORBA(self)
                    self.initCORBA()
                    channel_recreated = True
                except Exception, e:
                    channel_recreated = False

                if channel_recreated:
                    # Try to publish again the event
                    try:
                        self.sppc.push_structured_event(se)
                        if event_callback != None:
                            event_callback.eventSent(simple_data)
                    # Event cannot be sent
                    except Exception, e:
                        if event_callback != None:
                            event_callback.eventDropped(simple_data)