示例#1
0
    def test_introspection_events(self):
        # The listener must be able to deserialize introspection events. But
        # since it is created without introspection enabled, it does not force
        # the initialization of the introspection module.
        rsb.introspection.rsb_initialize()

        # Collect events in a thread-safe way and make sure the number is
        # right: one event is expected for the creation of the participant,
        # followed by one event for its destruction.
        events = []
        events_cv = threading.Condition()
        expected_events = 2

        def add_event(event):
            with events_cv:
                events.append(event)
                if len(events) == expected_events:
                    events_cv.notify()

        with rsb.create_listener(rsb.introspection.BASE_SCOPE) as listener:
            listener.add_handler(add_event)
            # Create and destroy a participant with enabled introspection. This
            # generates two introspection events.
            rsb.get_default_participant_config().introspection = True
            with rsb.create_informer('/foo'):
                pass
            with events_cv:
                events_cv.wait_for(lambda: len(events) >= expected_events,
                                   timeout=10)
        assert len(events) == expected_events
示例#2
0
    def test_user_roundtrip(self):
        scope = Scope("/test/it")
        in_connector = self._get_in_connector(scope, activate=False)
        out_connector = self._get_out_connector(scope, activate=False)

        in_configurator = rsb.eventprocessing.InRouteConfigurator(
            connectors=[in_connector])
        out_configurator = rsb.eventprocessing.OutRouteConfigurator(
            connectors=[out_connector])

        listener = create_listener(scope, configurator=in_configurator)
        publisher = create_informer(scope,
                                    data_type=str,
                                    configurator=out_configurator)

        receiver = SettingReceiver(scope)
        listener.add_handler(receiver)

        data1 = "a string to test"
        sent_event = Event(EventId(uuid.uuid4(), 0))
        sent_event.data = data1
        sent_event.data_type = str
        sent_event.scope = scope
        sent_event.meta_data.set_user_info("test", "it")
        sent_event.meta_data.set_user_info("test again", "it works?")
        sent_event.meta_data.set_user_time("blubb", 234234.0)
        sent_event.meta_data.set_user_time("bla", 3434343.45)
        sent_event.add_cause(EventId(uuid.uuid4(), 1323))
        sent_event.add_cause(EventId(uuid.uuid4(), 42))

        publisher.publish_event(sent_event)

        with receiver.result_condition:
            while receiver.result_event is None:
                receiver.result_condition.wait(10)
            if receiver.result_event is None:
                self.fail("Listener did not receive an event")
            assert receiver.result_event.meta_data.create_time <= \
                receiver.result_event.meta_data.send_time
            assert receiver.result_event.meta_data.send_time <= \
                receiver.result_event.meta_data.receive_time
            assert receiver.result_event.meta_data.receive_time <= \
                receiver.result_event.meta_data.deliver_time
            sent_event.meta_data.receive_time = \
                receiver.result_event.meta_data.receive_time
            sent_event.meta_data.deliver_time = \
                receiver.result_event.meta_data.deliver_time
            # HACK: floating point precision leads to an imprecision here,
            # avoid this.
            sent_event.meta_data.send_time = \
                receiver.result_event.meta_data.send_time
            sent_event.meta_data.create_time = \
                receiver.result_event.meta_data.create_time
            assert sent_event == receiver.result_event

        publisher.deactivate()
        listener.deactivate()
示例#3
0
 def make_listener(self):
     receiving_strategy = None
     if self._allow_parallel_execution:
         receiving_strategy = FullyParallelEventReceivingStrategy()
     listener = rsb.create_listener(self.scope,
                                    self.config,
                                    parent=self,
                                    receiving_strategy=receiving_strategy)
     listener.add_filter(rsb.filter.MethodFilter(method='REQUEST'))
     listener.add_handler(self._handle_request)
     return listener
示例#4
0
    def activate(self):
        with self._mutex:
            if self._active:
                raise RuntimeError('Activate called even though reader '
                                   'was already active')

            self._logger.info('Activating reader')

            self._listener = rsb.create_listener(self.scope,
                                                 self.config,
                                                 parent=self)
            self._listener.add_handler(self._handle_event)

            self._active = True

        super().activate()
示例#5
0
    def test_hierarchy_sending(self):

        send_scope = Scope("/this/is/a/test")
        super_scopes = send_scope.super_scopes(True)

        out_connector = self._get_out_connector(send_scope, activate=False)
        out_configurator = rsb.eventprocessing.OutRouteConfigurator(
            connectors=[out_connector])
        informer = create_informer(send_scope,
                                   data_type=str,
                                   configurator=out_configurator)

        # set up listeners on the complete hierarchy
        listeners = []
        receivers = []
        for scope in super_scopes:

            in_connector = self._get_in_connector(scope, activate=False)
            in_configurator = rsb.eventprocessing.InRouteConfigurator(
                connectors=[in_connector])

            listener = create_listener(scope, configurator=in_configurator)
            listeners.append(listener)

            receiver = SettingReceiver(scope)

            listener.add_handler(receiver)

            receivers.append(receiver)

        data = "a string to test"
        informer.publish_data(data)

        for receiver in receivers:
            with receiver.result_condition:
                while receiver.result_event is None:
                    receiver.result_condition.wait(10)
                if receiver.result_event is None:
                    pytest.fail(
                        "Listener on scope {} did not receive an event".format(
                            receiver.scope))
                assert receiver.result_event.data == data

        for listener in listeners:
            listener.deactivate()
        informer.deactivate()
示例#6
0
    def test_informer_listener_roundtrip(self):

        with rsb.create_informer(self.scope, data_type=str) as informer, \
                rsb.create_listener(self.scope) as listener:

            def set_received(event):
                with self.received_condition:
                    self.received_data = event.data
                    self.received_condition.notifyAll()

            listener.add_handler(set_received)
            data = 'our little test'
            informer.publish_data(data)
            start = time.time()
            with self.received_condition:
                while self.received_data is None:
                    self.received_condition.wait(1)
                    if time.time() > start + 10:
                        break
                assert data == self.received_data
示例#7
0
        def is_done(self):
            return self.counter == self.expectedCount

    listeners = []
    receivers = []
    try:
        for size in [4, 256, 400000]:
            # Create listeners for all scopes below the /sizeSIZE scope:
            # * /size-SIZE
            # * /size-SIZE/sub_1
            # * /size-SIZE/sub_1/sub_2
            scope = rsb.Scope("/size-%d/sub_1/sub_2" % size)
            scopes = scope.super_scopes(True)
            for superscope in scopes[1:]:
                listener = rsb.create_listener(superscope)
                listeners.append(listener)

                receiver = Receiver(
                    scope, size,
                    rsb.EventId(
                        uuid.UUID('00000000-0000-0000-0000-000000000000'), 0),
                    120)
                receivers.append(receiver)
                listener.add_handler(receiver)

        open('ready', 'w').close()
        print("[Python Listener] Ready")

        for receiver in receivers:
            with receiver.condition:
示例#8
0
    def __init__(self):
        self._logger = get_logger_by_class(self.__class__)

        self._participants = []

        self._process = ProcessInfo()
        self._host = HostInfo()

        self._informer = rsb.create_informer(PARTICIPANTS_SCOPE)
        self._listener = rsb.create_listener(PARTICIPANTS_SCOPE)

        def handle(event):
            # TODO use filter when we get conjunction filter
            if event.method not in ['REQUEST', 'SURVEY']:
                return

            participant_id = None
            participant = None
            if len(event.scope.components) > \
                    len(PARTICIPANTS_SCOPE.components):
                try:
                    participant_id = uuid.UUID(event.scope.components[-1])
                    if participant_id is not None:
                        participant = next(
                            (p for p in self._participants
                             if p.participant_id == participant_id), None)
                except Exception:
                    self._logger.warn(
                        'Query event %s does not '
                        'properly address a participant',
                        event,
                        exc_info=True)

            def process(thunk):
                if participant is not None and event.method == 'REQUEST':
                    thunk(query=event, participant=participant)
                elif participant is None and event.method == 'SURVEY':
                    for p in self._participants:
                        thunk(query=event, participant=p)
                else:
                    self._logger.warn('Query event %s not understood', event)

            if event.data is None:
                process(self.send_hello)
            elif event.data == 'ping':
                process(self.send_pong)
            else:
                self._logger.warn('Query event %s not understood', event)

        self._listener.add_handler(handle)

        self._server = rsb.create_local_server(
            process_scope(self._host.host_id or self._host.hostname,
                          str(self._process.process_id)))

        def echo(request):
            reply = rsb.Event(scope=request.scope,
                              data=request.data,
                              data_type=type(request.data))
            reply.meta_data.set_user_time('request.send',
                                          request.meta_data.send_time)
            reply.meta_data.set_user_time('request.receive',
                                          request.meta_data.receive_time)
            return reply

        self._server.add_method('echo',
                                echo,
                                request_type=rsb.Event,
                                reply_type=rsb.Event)
示例#9
0
# See ./registration.py.
sys.path.append('.')
from SimpleImage_pb2 import SimpleImage  # noqa: I100 path required before

if __name__ == '__main__':
    # Pacify logger.
    logging.basicConfig()

    # See ./registration.py
    converter = rsb.converter.ProtocolBufferConverter(
        message_class=SimpleImage)
    rsb.converter.register_global_converter(converter)

    rsb.set_default_participant_config(
        rsb.ParticipantConfig.from_default_sources())

    # Create a listener that will receive the events carrying protocol
    # buffer payloads. See the listener.py example for a more detailed
    # explanation of listener creation.
    with rsb.create_listener(rsb.Scope("/example/converter")) as listener:

        def print_data(event):
            print("Received {} object with fields:\n{}".format(
                type(event.data).__name__, str(event.data)))

        listener.add_handler(print_data)

        # wait endlessly for received events
        while True:
            time.sleep(100)
示例#10
0
 def test_listener(self):
     participant = None
     with rsb.create_listener('/') as listener:
         participant = listener
         assert self.creation_calls == [(participant, None)]
     assert self.destruction_calls == [participant]
示例#11
0
 def test_create_listener(self):
     assert rsb.create_listener("/") is not None
示例#12
0
import time

import rsb

_received_event = threading.Event()


def handle(event):
    print("Received event: {}".format(event))
    _received_event.set()


if __name__ == '__main__':
    # Pacify logger.
    logging.basicConfig()

    # Create a listener on the specified scope. The listener will
    # dispatch all received events asynchronously to all registered
    # handlers.
    with rsb.create_listener("/example/informer") as listener:

        # Add a handler to handle received events. Handlers are callable
        # objects with the received event as the single argument.
        listener.add_handler(handle)

        # Wait for an event to arrive and terminate afterwards
        _received_event.wait()
        # Give the informer some more time to finish for the socket transport
        time.sleep(1)
# mark-end::body
示例#13
0
 def make_listener(self):
     listener = rsb.create_listener(self.scope, self.config, parent=self)
     listener.add_filter(rsb.filter.MethodFilter(method='REPLY'))
     listener.add_handler(self._handle_reply)
     return listener