def test_match(self): e1 = rsb.Event(method='foo') e2 = rsb.Event() f = rsb.filter.MethodFilter(method='foo') assert f.match(e1) assert not f.match(e2) f = rsb.filter.MethodFilter(method='foo', invert=True) assert not f.match(e1) assert f.match(e2)
def testMatch(self): e1 = rsb.Event(method='foo') e2 = rsb.Event() f = rsb.filter.MethodFilter(method='foo') self.assertTrue(f.match(e1)) self.assertFalse(f.match(e2)) f = rsb.filter.MethodFilter(method='foo', invert=True) self.assertFalse(f.match(e1)) self.assertTrue(f.match(e2))
def testMatch(self): id1 = rsb.EventId(participantId=uuid.uuid1(), sequenceNumber=0) e1 = rsb.Event(causes=[ id1 ]) id2 = rsb.EventId(participantId=uuid.uuid1(), sequenceNumber=1) e2 = rsb.Event(causes=[ id2 ]) f = rsb.filter.CauseFilter(cause=id1) self.assertTrue(f.match(e1)) self.assertFalse(f.match(e2)) f = rsb.filter.CauseFilter(cause=id1, invert=True) self.assertFalse(f.match(e1)) self.assertTrue(f.match(e2))
def test_match(self): id1 = rsb.EventId(participant_id=uuid.uuid1(), sequence_number=0) e1 = rsb.Event(causes=[id1]) id2 = rsb.EventId(participant_id=uuid.uuid1(), sequence_number=1) e2 = rsb.Event(causes=[id2]) f = rsb.filter.CauseFilter(cause=id1) assert f.match(e1) assert not f.match(e2) f = rsb.filter.CauseFilter(cause=id1, invert=True) assert not f.match(e1) assert f.match(e2)
def testMatch(self): senderId1 = uuid.uuid1() e1 = rsb.Event(id=rsb.EventId(participantId=senderId1, sequenceNumber=0)) senderId2 = uuid.uuid1() e2 = rsb.Event(id=rsb.EventId(participantId=senderId2, sequenceNumber=1)) f = rsb.filter.OriginFilter(origin=senderId1) self.assertTrue(f.match(e1)) self.assertFalse(f.match(e2)) f = rsb.filter.OriginFilter(origin=senderId1, invert=True) self.assertFalse(f.match(e1)) self.assertTrue(f.match(e2))
def test_match(self): sender_id1 = uuid.uuid1() e1 = rsb.Event( event_id=rsb.EventId(participant_id=sender_id1, sequence_number=0)) sender_id2 = uuid.uuid1() e2 = rsb.Event( event_id=rsb.EventId(participant_id=sender_id2, sequence_number=1)) f = rsb.filter.OriginFilter(origin=sender_id1) assert f.match(e1) assert not f.match(e2) f = rsb.filter.OriginFilter(origin=sender_id1, invert=True) assert not f.match(e1) assert f.match(e2)
def notification_to_event(notification, wire_data, wire_schema, converter): """Build an event from a notification.""" event = rsb.Event( rsb.EventId(uuid.UUID(bytes=notification.event_id.sender_id), notification.event_id.sequence_number)) event.scope = rsb.Scope(notification.scope.decode('ASCII')) if notification.HasField("method"): event.method = notification.method.decode('ASCII') event.data_type = converter.data_type event.data = converter.deserialize(wire_data, wire_schema) # Meta data event.meta_data.create_time = unix_microseconds_to_time( notification.meta_data.create_time) event.meta_data.send_time = unix_microseconds_to_time( notification.meta_data.send_time) event.meta_data.set_receive_time() for info in notification.meta_data.user_infos: event.meta_data.set_user_info(info.key.decode('ASCII'), info.value.decode('ASCII')) for time in notification.meta_data.user_times: event.meta_data.set_user_time( time.key.decode('ASCII'), unix_microseconds_to_time(time.timestamp)) # Causes for cause in notification.causes: event_id = rsb.EventId(uuid.UUID(bytes=cause.sender_id), cause.sequence_number) event.add_cause(event_id) return event
def notificationToEvent(notification, wireData, wireSchema, converter): """ Build event from notification. """ event = rsb.Event( rsb.EventId(uuid.UUID(bytes=notification.event_id.sender_id), notification.event_id.sequence_number)) event.scope = rsb.Scope(notification.scope) if notification.HasField("method"): event.method = notification.method event.type = converter.getDataType() event.data = converter.deserialize(wireData, wireSchema) # Meta data event.metaData.createTime = unixMicrosecondsToTime( notification.meta_data.create_time) event.metaData.sendTime = unixMicrosecondsToTime( notification.meta_data.send_time) event.metaData.setReceiveTime() for info in notification.meta_data.user_infos: event.metaData.setUserInfo(info.key, info.value) for time in notification.meta_data.user_times: event.metaData.setUserTime(time.key, unixMicrosecondsToTime(time.timestamp)) # Causes for cause in notification.causes: id = rsb.EventId(uuid.UUID(bytes=cause.sender_id), cause.sequence_number) event.addCause(id) return event
def send_pong(self, participant, query=None): scope = participant_scope(participant.participant_id, self._informer.scope) pong_event = rsb.Event(scope=scope, data='pong', data_type=str) if query: pong_event.add_cause(query.event_id) self._informer.publish_event(pong_event)
def send_bye(self, participant): bye = Bye() bye.id = participant.participant_id.bytes scope = participant_scope(participant.participant_id, self._informer.scope) bye_event = rsb.Event(scope=scope, data=bye, data_type=type(bye)) self._informer.publish_event(bye_event)
def sendPong(self, participant, query=None): scope = participantScope(participant.id, self.__informer.scope) pongEvent = rsb.Event(scope=scope, data='pong', type=str) if query: pongEvent.addCause(query.id) self.__informer.publishEvent(pongEvent)
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
def sendBye(self, participant): bye = Bye() bye.id = participant.id.get_bytes() scope = participantScope(participant.id, self.__informer.scope) byeEvent = rsb.Event(scope=scope, data=bye, type=type(bye)) self.__informer.publishEvent(byeEvent)
def echo(request): reply = rsb.Event(scope=request.scope, data=request.data, type=type(request.data)) reply.metaData.setUserTime('request.send', request.metaData.sendTime) reply.metaData.setUserTime('request.receive', request.metaData.receiveTime) return reply
def test_match(self): scope = Scope("/bla") f = rsb.filter.ScopeFilter(scope) assert scope == f.scope e = rsb.Event() e.scope = scope assert f.match(e) e.scope = scope.concat(Scope("/sub/scope")) assert f.match(e) e.scope = Scope("/blubbbbbb") assert not f.match(e)
def testMatch(self): scope = Scope("/bla") f = rsb.filter.ScopeFilter(scope) self.assertEqual(scope, f.getScope()) e = rsb.Event() e.scope = scope self.assertTrue(f.match(e)) e.scope = scope.concat(Scope("/sub/scope")) self.assertTrue(f.match(e)) e.scope = Scope("/blubbbbbb") self.assertFalse(f.match(e))
def publish_persons(self, persons, cause_uuid): # Gather the information of every head rsb_person_list = HeadObjects() for a_person in persons: rsb_person_list.head_objects.extend([a_person.to_rsb_msg()]) # Create the event and add the cause. Maybe some day someone will use # this reference to the cause :) event = rsb.Event(scope=self.person_publisher.getScope(), data=rsb_person_list, type=type(rsb_person_list), causes=[cause_uuid]) # Publish the data self.person_publisher.publishEvent(event)
def _handle_request(self, request): # Call the callable implementing the behavior of this # method. If it does not take an argument # (i.e. self.request_type is type(None)), call it without # argument. Otherwise pass the payload of the request event to # it. user_infos = {} causes = [request.event_id] is_error = False try: if self.request_type is type(None): # noqa: E721 assert (request.data is None) result = self._func() elif self.request_type is rsb.Event: result = self._func(request) else: result = self._func(request.data) result_type = type(result) except Exception as e: is_error = True user_infos['rsb:error?'] = '1' result = str(e) result_type = str # If the returned result is an event, use it as reply event # (after adding the request as cause). Otherwise add all # necessary meta-data. if isinstance(result, rsb.Event): reply = result reply.method = 'REPLY' reply.causes += causes else: # This check is required because the reply informer is # created with type 'object' to enable throwing exceptions if not is_error and not isinstance(result, self.reply_type): raise ValueError( "The result '{}' (of type {}) of method {} does not match " "the method's declared return type {}.".format( result, result_type, self.name, self.reply_type)) reply = rsb.Event(scope=self.informer.scope, method='REPLY', data=result, data_type=result_type, user_infos=user_infos, causes=causes) # Publish the reply event. self.informer.publish_event(reply)
def sendHello(self, participant, query=None): hello = Hello() hello.kind = participant.kind hello.id = participant.id.get_bytes() hello.scope = participant.scope.toString() if participant.parentId: hello.parent = participant.parentId.get_bytes() for url in participant.transportURLs: hello.transport.append(url) host = hello.host if self.host.id is None: host.id = self.host.hostname else: host.id = self.host.id host.hostname = self.host.hostname host.machine_type = self.host.machineType if self.host.machineVersion is not None: host.machine_version = self.host.machineVersion host.software_type = self.host.softwareType host.software_version = self.host.softwareVersion process = hello.process process.id = str(self.process.id) process.program_name = self.process.programName for argument in self.process.arguments: process.commandline_arguments.append(argument) process.start_time = int(self.process.startTime * 1000000.0) if self.process.executingUser: process.executing_user = self.process.executingUser process.rsb_version = self.process.rsbVersion if _displayName: process.display_name = _displayName scope = participantScope(participant.id, self.__informer.scope) helloEvent = rsb.Event(scope=scope, data=hello, type=type(hello)) if query: helloEvent.addCause(query.id) self.__informer.publishEvent(helloEvent)
def send_hello(self, participant, query=None): hello = Hello() hello.kind = participant.kind hello.id = participant.participant_id.bytes hello.scope = participant.scope.to_string() if participant.parent_id: hello.parent = participant.parent_id.bytes for url in participant.transport_urls: hello.transport.append(url) host = hello.host if self.host.host_id is None: host.id = self.host.hostname else: host.id = self.host.host_id host.hostname = self.host.hostname host.machine_type = self.host.machine_type if self.host.machine_version is not None: host.machine_version = self.host.machine_version host.software_type = self.host.software_type host.software_version = self.host.software_version process = hello.process process.id = str(self.process.process_id) process.program_name = self.process.program_name for argument in self.process.arguments: process.commandline_arguments.append(argument) process.start_time = int(self.process.start_time * 1000000.0) if self.process.executing_user: process.executing_user = self.process.executing_user process.rsb_version = self.process.rsb_version if _display_name: process.display_name = _display_name scope = participant_scope(participant.participant_id, self._informer.scope) hello_event = rsb.Event(scope=scope, data=hello, data_type=type(hello)) if query: hello_event.add_cause(query.event_id) self._informer.publish_event(hello_event)
class LocalMethod(Method): """ Objects of this class implement and make available methods of a local server. The actual behavior of methods is implemented by invoking arbitrary user-supplied callables. .. codeauthor:: jmoringe """ def __init__(self, scope, config, server, name, func, requestType, replyType, allowParallelExecution): super(LocalMethod, self).__init__(scope, config, server, name, requestType, replyType) self._allowParallelExecution = allowParallelExecution self._func = func self.listener # force listener creation def makeListener(self): receivingStrategy = None if self._allowParallelExecution: receivingStrategy = FullyParallelEventReceivingStrategy() listener = rsb.createListener(self.scope, self.config, parent=self, receivingStrategy=receivingStrategy) listener.addFilter(rsb.filter.MethodFilter(method='REQUEST')) listener.addHandler(self._handleRequest) return listener def makeInformer(self): return rsb.createInformer(self.scope, self.config, parent=self, dataType=object) def _handleRequest(self, request): # Call the callable implementing the behavior of this # method. If it does not take an argument # (i.e. self.requestType is type(None)), call it without # argument. Otherwise pass the payload of the request event to # it. userInfos = {} causes = [request.id] isError = False try: if self.requestType is type(None): assert (request.data is None) result = self._func() elif self.requestType is rsb.Event: result = self._func(request) else: result = self._func(request.data) resultType = type(result) except Exception, e: isError = True userInfos['rsb:error?'] = '1' result = str(e) resultType = str # If the returned result is an event, use it as reply event # (after adding the request as cause). Otherwise add all # necessary meta-data. if isinstance(result, rsb.Event): reply = result reply.method = 'REPLY' reply.causes += causes else: # This check is required because the reply informer is # created with type 'object' to enable throwing exceptions if not isError and not isinstance(result, self.replyType): raise ValueError( "The result '%s' (of type %s) " "of method %s does not match " "the method's declared return type %s." % (result, resultType, self.name, self.replyType)) reply = rsb.Event(scope=self.informer.scope, method='REPLY', data=result, type=resultType, userInfos=userInfos, causes=causes) # Publish the reply event. self.informer.publishEvent(reply)
def setUp(self): self.e = rsb.Event()
def asynchronous(self, arg=None): """ Call the method asynchronously and returns a :obj:`Future`. Calls the represented method with argument ``arg``, returning a :obj:`Future` instance that can be used to retrieve the result. If ``arg`` is an instance of :obj:`Event`, the result of the method call is an :obj:`Event` containing the object returned by the remote method as payload. If ``arg`` is of any other type, the result is the payload of the method call is the object that was returned by the remote method. The call to this method returns immediately, even if the remote method did produce a result yet. The returned :obj:`Future` instance has to be used to retrieve the result. Args: arg: The argument object that should be passed to the remote method. A converter has to be available for the type of ``arg``. Returns: Future or DataFuture: A :obj:`Future` or :obj:`DataFuture` instance that can be used to check the success of the method call, wait for the result and retrieve the result. Raises: RemoteCallError: If an error occurs before the remote was invoked. See Also: :obj:`__call__` Examples: >>> my_server.echo.asynchronous('bla') <Future running at 3054cd0> >>> my_server.echo.asynchronous('bla').get() 'bla' >>> my_server.echo.asynchronous(Event(scope=my_server.scope, ... data='bla', type=str)).get() Event[id = ..., data = 'bla', ...] """ self.listener # Force listener creation # When the caller supplied an event, adjust the meta-data and # create a future that will return an event. if isinstance(arg, rsb.Event): event = arg event.scope = self.informer.scope event.method = 'REQUEST' result = Future() # Otherwise, create a new event with suitable meta-data and a # future that will return the payload of the reply event. else: event = rsb.Event(scope=self.informer.scope, method='REQUEST', data=arg, data_type=type(arg)) result = DataFuture() # Publish the constructed request event and record the call as # in-progress, waiting for a reply. try: with self._lock: event = self.informer.publish_event(event) self._calls[event.event_id] = result except Exception as e: raise RemoteCallError(self.server.scope, self, e) from e return result
# Public License as published by the Free Software Foundation; # either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # ============================================================ import logging import uuid import sys import rsb if __name__ == "__main__": logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s\n%(message)s', stream=sys.stderr) with open('data/event-id-cases.txt') as input: for line in input.readlines(): origin, seqnum, expected = list(map(str.strip, line.split(' '))) originId, seqnum, expectedId = \ (uuid.UUID(hex=origin), int(seqnum, 16), uuid.UUID(hex=expected)) event = rsb.Event(event_id=rsb.EventId(participant_id=originId, sequence_number=seqnum)) assert event.event_id.get_as_uuid() == expectedId
level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s\n%(message)s', stream=sys.stderr) listener_pid = int(sys.argv[2]) for size in [4, 256, 400000]: scope = "/size-%d/sub_1/sub_2" % size print("[Python Informer] Processing scope %s" % scope) informer = rsb.create_informer(scope, data_type=str) for i in range(120): event = rsb.Event( scope=scope, data='c' * size, data_type=str, user_infos={ "informer-lang": "Python", "index": str(listener_pid + i) }, user_times={"informer-start": time.time()}, causes=set([ rsb.EventId( uuid.UUID('00000000-0000-0000-0000-000000000000'), 0) ])) informer.publish_event(event) informer.deactivate() print("[Python Informer] Done")