Search in sources :

Example 1 with ChannelAddress

use of joynr.system.RoutingTypes.ChannelAddress in project joynr by bmwcarit.

the class CcMessageRouterTest method testFailedTransmitDoesNotLeadToThreadStarvation.

@Test(timeout = 3000)
public void testFailedTransmitDoesNotLeadToThreadStarvation() throws Exception {
    final int MESSAGE_LOAD = 10;
    ImmutableMessage failingMessage = mock(ImmutableMessage.class);
    when(failingMessage.isTtlAbsolute()).thenReturn(true);
    when(failingMessage.getTtlMs()).thenReturn(ExpiryDate.fromRelativeTtl(1000L).getValue());
    when(failingMessage.getRecipient()).thenReturn("to");
    when(routingTable.get("to")).thenReturn(channelAddress);
    Set<Address> addressSet = new HashSet<>();
    addressSet.add(channelAddress);
    Mockito.doReturn(addressSet).when(addressManager).getAddresses(failingMessage);
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            assertEquals(invocation.getArguments().length, 3);
            FailureAction failureAction = (FailureAction) invocation.getArguments()[2];
            failureAction.execute(new Exception("Some error"));
            return null;
        }
    }).when(messagingStubMock).transmit(eq(failingMessage), any(SuccessAction.class), any(FailureAction.class));
    for (int i = 0; i < MESSAGE_LOAD; i++) {
        messageRouter.route(failingMessage);
    }
    Thread.sleep(2000);
    verify(messagingStubMock, atLeast(MESSAGE_LOAD * 3)).transmit(eq(failingMessage), any(SuccessAction.class), any(FailureAction.class));
    ImmutableMessage anotherMessage = mock(ImmutableMessage.class);
    when(anotherMessage.isTtlAbsolute()).thenReturn(true);
    when(anotherMessage.getTtlMs()).thenReturn(ExpiryDate.fromRelativeTtl(1000L).getValue());
    when(anotherMessage.getRecipient()).thenReturn("to");
    Mockito.doReturn(addressSet).when(addressManager).getAddresses(anotherMessage);
    final Semaphore semaphore = new Semaphore(0);
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            assertEquals(invocation.getArguments().length, 3);
            SuccessAction successAction = (SuccessAction) invocation.getArguments()[1];
            successAction.execute();
            semaphore.release();
            return null;
        }
    }).when(messagingStubMock).transmit(eq(anotherMessage), any(SuccessAction.class), any(FailureAction.class));
    messageRouter.route(anotherMessage);
    assertTrue(semaphore.tryAcquire(100, TimeUnit.MILLISECONDS));
}
Also used : FailureAction(io.joynr.messaging.FailureAction) Address(joynr.system.RoutingTypes.Address) ChannelAddress(joynr.system.RoutingTypes.ChannelAddress) Semaphore(java.util.concurrent.Semaphore) JoynrRuntimeException(io.joynr.exceptions.JoynrRuntimeException) JoynrMessageNotSentException(io.joynr.exceptions.JoynrMessageNotSentException) JoynrDelayMessageException(io.joynr.exceptions.JoynrDelayMessageException) SuccessAction(io.joynr.messaging.SuccessAction) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ImmutableMessage(joynr.ImmutableMessage) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Test(org.junit.Test)

Example 2 with ChannelAddress

use of joynr.system.RoutingTypes.ChannelAddress in project joynr by bmwcarit.

the class CcMessageRouterTest method setUp.

@Before
public void setUp() throws Exception {
    when(middlewareMessagingStubFactoryMock.create(any(ChannelAddress.class))).thenReturn(messagingStubMock);
    AbstractModule mockModule = new AbstractModule() {

        private Long msgRetryIntervalMs = 10L;

        // message runnables + cleanup thread
        private int numberOfThreads = maximumParallelSends + 1;

        private long routingTableGracePeriodMs = 30000;

        private long routingTableCleanupIntervalMs = 60000;

        @Override
        protected void configure() {
            bind(MessageRouter.class).to(CcMessageRouter.class);
            bind(RoutingTable.class).toInstance(routingTable);
            bind(AddressManager.class).toInstance(addressManager);
            bind(MulticastReceiverRegistry.class).toInstance(multicastReceiverRegistry);
            bind(ShutdownNotifier.class).toInstance(shutdownNotifier);
            bind(Long.class).annotatedWith(Names.named(ConfigurableMessagingSettings.PROPERTY_SEND_MSG_RETRY_INTERVAL_MS)).toInstance(msgRetryIntervalMs);
            bind(Integer.class).annotatedWith(Names.named(ConfigurableMessagingSettings.PROPERTY_MESSAGING_MAXIMUM_PARALLEL_SENDS)).toInstance(maximumParallelSends);
            bind(Long.class).annotatedWith(Names.named(ConfigurableMessagingSettings.PROPERTY_ROUTING_TABLE_GRACE_PERIOD_MS)).toInstance(routingTableGracePeriodMs);
            bind(Long.class).annotatedWith(Names.named(ConfigurableMessagingSettings.PROPERTY_ROUTING_TABLE_CLEANUP_INTERVAL_MS)).toInstance(routingTableCleanupIntervalMs);
            bindConstant().annotatedWith(Names.named(ClusterControllerRuntimeModule.PROPERTY_ACCESSCONTROL_ENABLE)).to(false);
            bind(AccessController.class).toInstance(Mockito.mock(AccessController.class));
            bind(StatusReceiver.class).toInstance(statusReceiver);
            MapBinder<Class<? extends Address>, AbstractMiddlewareMessagingStubFactory<? extends IMessagingStub, ? extends Address>> messagingStubFactory;
            messagingStubFactory = MapBinder.newMapBinder(binder(), new TypeLiteral<Class<? extends Address>>() {
            }, new TypeLiteral<AbstractMiddlewareMessagingStubFactory<? extends IMessagingStub, ? extends Address>>() {
            }, Names.named(MessagingStubFactory.MIDDLEWARE_MESSAGING_STUB_FACTORIES));
            messagingStubFactory.addBinding(ChannelAddress.class).toInstance(middlewareMessagingStubFactoryMock);
            MapBinder<Class<? extends Address>, IMessagingSkeleton> messagingSkeletonFactory;
            messagingSkeletonFactory = MapBinder.newMapBinder(binder(), new TypeLiteral<Class<? extends Address>>() {
            }, new TypeLiteral<IMessagingSkeleton>() {
            }, Names.named(MessagingSkeletonFactory.MIDDLEWARE_MESSAGING_SKELETONS));
            messagingSkeletonFactory.addBinding(ChannelAddress.class).toInstance(messagingSkeletonMock);
            Multibinder.newSetBinder(binder(), new TypeLiteral<MulticastAddressCalculator>() {
            });
        }

        @Provides
        @Named(MessageRouter.SCHEDULEDTHREADPOOL)
        ScheduledExecutorService provideMessageSchedulerThreadPoolExecutor() {
            ThreadFactory schedulerNamedThreadFactory = new ThreadFactoryBuilder().setNameFormat("joynr.MessageScheduler-scheduler-%d").build();
            ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(numberOfThreads, schedulerNamedThreadFactory);
            scheduler.setKeepAliveTime(100, TimeUnit.SECONDS);
            scheduler.allowCoreThreadTimeOut(true);
            return scheduler;
        }
    };
    testModule = Modules.override(mockModule).with(new TestGlobalAddressModule());
    Injector injector = Guice.createInjector(testModule);
    messageRouter = injector.getInstance(MessageRouter.class);
    ObjectMapper objectMapper = new ObjectMapper();
    messageFactory = new MutableMessageFactory(objectMapper, new HashSet<JoynrMessageProcessor>());
    // toParticipantId is globally visible
    final boolean isGloballyVisible = true;
    final long expiryDateMs = Long.MAX_VALUE;
    final boolean isSticky = true;
    final boolean allowUpdate = false;
    routingTable.put(toParticipantId, channelAddress, isGloballyVisible, expiryDateMs, isSticky, allowUpdate);
    Request request = new Request("noMethod", new Object[] {}, new String[] {}, "requestReplyId");
    joynrMessage = messageFactory.createRequest(fromParticipantId, toParticipantId, request, new MessagingQos());
    joynrMessage.setLocalMessage(true);
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) TestGlobalAddressModule(io.joynr.messaging.routing.TestGlobalAddressModule) IMessagingSkeleton(io.joynr.messaging.IMessagingSkeleton) Address(joynr.system.RoutingTypes.Address) ChannelAddress(joynr.system.RoutingTypes.ChannelAddress) CcMessageRouter(io.joynr.messaging.routing.CcMessageRouter) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) StatusReceiver(io.joynr.statusmetrics.StatusReceiver) MessagingQos(io.joynr.messaging.MessagingQos) TypeLiteral(com.google.inject.TypeLiteral) Injector(com.google.inject.Injector) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) ShutdownNotifier(io.joynr.runtime.ShutdownNotifier) Request(joynr.Request) ChannelAddress(joynr.system.RoutingTypes.ChannelAddress) AbstractModule(com.google.inject.AbstractModule) AbstractMiddlewareMessagingStubFactory(io.joynr.messaging.AbstractMiddlewareMessagingStubFactory) AccessController(io.joynr.accesscontrol.AccessController) MutableMessageFactory(io.joynr.dispatching.MutableMessageFactory) IMessagingStub(io.joynr.messaging.IMessagingStub) Before(org.junit.Before)

Example 3 with ChannelAddress

use of joynr.system.RoutingTypes.ChannelAddress in project joynr by bmwcarit.

the class LocalCapabilitiesDirectoryTest method setUp.

@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
    channelAddress = new ChannelAddress(TEST_URL, "testChannelId");
    ObjectMapper objectMapper = new ObjectMapper();
    channelAddressSerialized = objectMapper.writeValueAsString(channelAddress);
    Field objectMapperField = CapabilityUtils.class.getDeclaredField("objectMapper");
    objectMapperField.setAccessible(true);
    objectMapperField.set(CapabilityUtils.class, objectMapper);
    Answer<Void> answer = new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            ((Callback<Void>) args[0]).onSuccess(null);
            return null;
        }
    };
    doAnswer(answer).when(globalCapabilitiesClient).add(any(Callback.class), any(GlobalDiscoveryEntry.class));
    String discoveryDirectoriesDomain = "io.joynr";
    String capabilitiesDirectoryParticipantId = "capDir_participantId";
    String capabiltitiesDirectoryChannelId = "dirchannelId";
    String domainAccessControllerParticipantId = "domainAccessControllerParticipantId";
    String domainAccessControllerChannelId = "domainAccessControllerChannelId";
    DiscoveryEntry globalCapabilitiesDirectoryDiscoveryEntry = CapabilityUtils.newGlobalDiscoveryEntry(new Version(0, 1), discoveryDirectoriesDomain, GlobalCapabilitiesDirectory.INTERFACE_NAME, capabilitiesDirectoryParticipantId, new ProviderQos(), System.currentTimeMillis(), expiryDateMs, domainAccessControllerChannelId, new ChannelAddress(TEST_URL, capabiltitiesDirectoryChannelId));
    DiscoveryEntry domainAccessControllerDiscoveryEntry = CapabilityUtils.newGlobalDiscoveryEntry(new Version(0, 1), discoveryDirectoriesDomain, GlobalDomainAccessController.INTERFACE_NAME, domainAccessControllerParticipantId, new ProviderQos(), System.currentTimeMillis(), expiryDateMs, domainAccessControllerChannelId, new ChannelAddress(TEST_URL, domainAccessControllerChannelId));
    when(capabilitiesProvisioning.getDiscoveryEntries()).thenReturn(Sets.newHashSet(globalCapabilitiesDirectoryDiscoveryEntry, domainAccessControllerDiscoveryEntry));
    // use default freshnessUpdateIntervalMs: 3600000ms (1h)
    localCapabilitiesDirectory = new LocalCapabilitiesDirectoryImpl(capabilitiesProvisioning, globalAddressProvider, localDiscoveryEntryStoreMock, globalDiscoveryEntryCacheMock, messageRouter, globalCapabilitiesClient, expiredDiscoveryEntryCacheCleaner, 3600000, capabilitiesFreshnessUpdateExecutor, defaultDiscoveryRetryIntervalMs, shutdownNotifier);
    verify(expiredDiscoveryEntryCacheCleaner).scheduleCleanUpForCaches(Mockito.<ExpiredDiscoveryEntryCacheCleaner.CleanupAction>any(), argThat(new DiscoveryEntryStoreVarargMatcher(globalDiscoveryEntryCacheMock, localDiscoveryEntryStoreMock)));
    verify(capabilitiesFreshnessUpdateExecutor).scheduleAtFixedRate(runnableCaptor.capture(), anyLong(), anyLong(), eq(TimeUnit.MILLISECONDS));
    ProviderQos providerQos = new ProviderQos();
    CustomParameter[] parameterList = { new CustomParameter("key1", "value1"), new CustomParameter("key2", "value2") };
    providerQos.setCustomParameters(parameterList);
    String participantId = "testParticipantId";
    String domain = "domain";
    discoveryEntry = new DiscoveryEntry(new Version(47, 11), domain, TestInterface.INTERFACE_NAME, participantId, providerQos, System.currentTimeMillis(), expiryDateMs, publicKeyId);
    globalDiscoveryEntry = new GlobalDiscoveryEntry(new Version(47, 11), domain, TestInterface.INTERFACE_NAME, participantId, providerQos, System.currentTimeMillis(), expiryDateMs, publicKeyId, channelAddressSerialized);
}
Also used : DiscoveryEntry(joynr.types.DiscoveryEntry) GlobalDiscoveryEntry(joynr.types.GlobalDiscoveryEntry) GlobalDiscoveryEntry(joynr.types.GlobalDiscoveryEntry) ChannelAddress(joynr.system.RoutingTypes.ChannelAddress) Matchers.anyString(org.mockito.Matchers.anyString) Field(java.lang.reflect.Field) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(org.mockito.stubbing.Answer) Callback(io.joynr.proxy.Callback) Version(joynr.types.Version) InvocationOnMock(org.mockito.invocation.InvocationOnMock) DeferredVoid(io.joynr.provider.DeferredVoid) CustomParameter(joynr.types.CustomParameter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ProviderQos(joynr.types.ProviderQos) Before(org.junit.Before)

Example 4 with ChannelAddress

use of joynr.system.RoutingTypes.ChannelAddress in project joynr by bmwcarit.

the class CapabilitiesDirectoryImpl method add.

@Override
public Promise<DeferredVoid> add(GlobalDiscoveryEntry globalDiscoveryEntry) {
    DeferredVoid deferred = new DeferredVoid();
    Promise<DeferredVoid> promise = new Promise<DeferredVoid>(deferred);
    Address address = CapabilityUtils.getAddressFromGlobalDiscoveryEntry(globalDiscoveryEntry);
    String clusterControllerId;
    if (address instanceof MqttAddress) {
        clusterControllerId = ((MqttAddress) address).getTopic();
    } else if (address instanceof ChannelAddress) {
        clusterControllerId = ((ChannelAddress) address).getChannelId();
    } else {
        deferred.reject(new ProviderRuntimeException(""));
        return promise;
    }
    GlobalDiscoveryEntryPersisted discoveryEntry = new GlobalDiscoveryEntryPersisted(globalDiscoveryEntry, clusterControllerId);
    logger.debug("registered discovery entry: {}", discoveryEntry);
    discoveryEntryStore.add(discoveryEntry);
    deferred.resolve();
    return promise;
}
Also used : Promise(io.joynr.provider.Promise) ChannelAddress(joynr.system.RoutingTypes.ChannelAddress) MqttAddress(joynr.system.RoutingTypes.MqttAddress) Address(joynr.system.RoutingTypes.Address) ChannelAddress(joynr.system.RoutingTypes.ChannelAddress) DeferredVoid(io.joynr.provider.DeferredVoid) ProviderRuntimeException(joynr.exceptions.ProviderRuntimeException) GlobalDiscoveryEntryPersisted(io.joynr.capabilities.GlobalDiscoveryEntryPersisted) MqttAddress(joynr.system.RoutingTypes.MqttAddress)

Example 5 with ChannelAddress

use of joynr.system.RoutingTypes.ChannelAddress in project joynr by bmwcarit.

the class ArbitrationTest method keywordArbitratorOnChangeSubscriptionsTest.

// Check that the keyword arbitrator will only consider providers that support onChange subscriptions
// when this is requested by the DiscoveryQos
@Test
public void keywordArbitratorOnChangeSubscriptionsTest() throws InterruptedException {
    ProviderQos providerQos = new ProviderQos();
    CustomParameter[] qosParameters = { new CustomParameter(ArbitrationConstants.KEYWORD_PARAMETER, testKeyword) };
    // Create a capability entry for a provider with the correct keyword but that does not support onChange subscriptions
    providerQos.setCustomParameters(qosParameters);
    providerQos.setSupportsOnChangeSubscriptions(false);
    capabilitiesList.add(new DiscoveryEntryWithMetaInfo(new Version(47, 11), domain, TestInterface.INTERFACE_NAME, "wrongParticipantId", providerQos, System.currentTimeMillis(), NO_EXPIRY, publicKeyId, true));
    // Create a capability entry for a provider with the correct keyword and that also supports onChange subscriptions
    ProviderQos providerQos2 = new ProviderQos();
    CustomParameter[] qosParameters2 = { new CustomParameter(ArbitrationConstants.KEYWORD_PARAMETER, testKeyword) };
    providerQos2.setCustomParameters(qosParameters2);
    providerQos2.setSupportsOnChangeSubscriptions(true);
    expectedEndpointAddress = new ChannelAddress("http://testUrl", "testChannelId");
    DiscoveryEntryWithMetaInfo expectedDiscoveryEntry = new DiscoveryEntryWithMetaInfo(new Version(47, 11), domain, TestInterface.INTERFACE_NAME, "expectedParticipantId", providerQos2, System.currentTimeMillis(), NO_EXPIRY, publicKeyId, true);
    capabilitiesList.add(expectedDiscoveryEntry);
    discoveryQos = new DiscoveryQos(ARBITRATION_TIMEOUT, ArbitrationStrategy.Keyword, Long.MAX_VALUE);
    discoveryQos.addCustomParameter(ArbitrationConstants.KEYWORD_PARAMETER, testKeyword);
    discoveryQos.setProviderMustSupportOnChange(true);
    try {
        Arbitrator arbitrator = ArbitratorFactory.create(Sets.newHashSet(domain), interfaceName, interfaceVersion, discoveryQos, localDiscoveryAggregator);
        arbitrator.setArbitrationListener(arbitrationCallback);
        arbitrator.scheduleArbitration();
        assertTrue(localDiscoveryAggregatorSemaphore.tryAcquire(1000, TimeUnit.MILLISECONDS));
        ArbitrationResult expectedArbitrationResult = new ArbitrationResult(expectedDiscoveryEntry);
        verify(arbitrationCallback, times(1)).onSuccess(eq(expectedArbitrationResult));
    } catch (DiscoveryException e) {
        fail("A Joyn Arbitration Exception has been thrown");
    }
}
Also used : Version(joynr.types.Version) ChannelAddress(joynr.system.RoutingTypes.ChannelAddress) CustomParameter(joynr.types.CustomParameter) DiscoveryEntryWithMetaInfo(joynr.types.DiscoveryEntryWithMetaInfo) DiscoveryException(io.joynr.exceptions.DiscoveryException) ProviderQos(joynr.types.ProviderQos) Test(org.junit.Test)

Aggregations

ChannelAddress (joynr.system.RoutingTypes.ChannelAddress)22 ProviderQos (joynr.types.ProviderQos)12 Version (joynr.types.Version)12 Test (org.junit.Test)12 Address (joynr.system.RoutingTypes.Address)10 DiscoveryEntryWithMetaInfo (joynr.types.DiscoveryEntryWithMetaInfo)9 DiscoveryException (io.joynr.exceptions.DiscoveryException)6 MqttAddress (joynr.system.RoutingTypes.MqttAddress)6 HashSet (java.util.HashSet)5 InvocationOnMock (org.mockito.invocation.InvocationOnMock)5 CustomParameter (joynr.types.CustomParameter)4 DiscoveryEntry (joynr.types.DiscoveryEntry)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 FailureAction (io.joynr.messaging.FailureAction)3 SuccessAction (io.joynr.messaging.SuccessAction)3 InProcessAddress (io.joynr.messaging.inprocess.InProcessAddress)3 ArrayList (java.util.ArrayList)3 Collection (java.util.Collection)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3