Search in sources :

Example 31 with Connection

use of com.hazelcast.internal.nio.Connection in project hazelcast by hazelcast.

the class ClientHeartbeatTest method testAddingListenerToNewConnectionFailedBecauseOfHeartbeat.

@Test
public void testAddingListenerToNewConnectionFailedBecauseOfHeartbeat() throws Exception {
    hazelcastFactory.newHazelcastInstance();
    final HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig());
    HazelcastClientInstanceImpl clientInstanceImpl = getHazelcastClientInstanceImpl(client);
    final ClientListenerService clientListenerService = clientInstanceImpl.getListenerService();
    final CountDownLatch blockIncoming = new CountDownLatch(1);
    final CountDownLatch heartbeatStopped = new CountDownLatch(1);
    final CountDownLatch onListenerRegister = new CountDownLatch(2);
    clientInstanceImpl.getConnectionManager().addConnectionListener(new ConnectionListener() {

        @Override
        public void connectionAdded(Connection connection) {
        }

        @Override
        public void connectionRemoved(Connection connection) {
            heartbeatStopped.countDown();
        }
    });
    clientListenerService.registerListener(createPartitionLostListenerCodec(), new EventHandler() {

        AtomicInteger count = new AtomicInteger(0);

        @Override
        public void handle(Object event) {
        }

        @Override
        public void beforeListenerRegister(Connection connection) {
            if (count.incrementAndGet() == 2) {
                try {
                    blockIncoming.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onListenerRegister(Connection connection) {
            onListenerRegister.countDown();
        }
    });
    HazelcastInstance hazelcastInstance2 = hazelcastFactory.newHazelcastInstance();
    assertSizeEventually(2, clientInstanceImpl.getConnectionManager().getActiveConnections());
    blockMessagesFromInstance(hazelcastInstance2, client);
    assertOpenEventually(heartbeatStopped);
    blockIncoming.countDown();
    unblockMessagesFromInstance(hazelcastInstance2, client);
    assertOpenEventually(onListenerRegister);
}
Also used : ClientListenerService(com.hazelcast.client.impl.spi.ClientListenerService) HazelcastInstance(com.hazelcast.core.HazelcastInstance) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Connection(com.hazelcast.internal.nio.Connection) HazelcastClientInstanceImpl(com.hazelcast.client.impl.clientside.HazelcastClientInstanceImpl) EventHandler(com.hazelcast.client.impl.spi.EventHandler) ConnectionListener(com.hazelcast.internal.nio.ConnectionListener) CountDownLatch(java.util.concurrent.CountDownLatch) ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) QuickTest(com.hazelcast.test.annotation.QuickTest) Test(org.junit.Test)

Example 32 with Connection

use of com.hazelcast.internal.nio.Connection in project hazelcast by hazelcast.

the class TcpClientConnectionManagerTranslateTest method testTranslateIsNotUsedOnGettingExistingConnection.

@Test
public void testTranslateIsNotUsedOnGettingExistingConnection() {
    // given
    TestAddressProvider provider = new TestAddressProvider(false);
    HazelcastInstance client = HazelcastClientUtil.newHazelcastClient(provider, new ClientConfig());
    TcpClientConnectionManager clientConnectionManager = new TcpClientConnectionManager(getHazelcastClientInstanceImpl(client));
    clientConnectionManager.start();
    clientConnectionManager.reset();
    clientConnectionManager.getOrConnectToAddress(privateAddress, false);
    provider.shouldTranslate = true;
    // when
    Connection connection = clientConnectionManager.getOrConnectToAddress(privateAddress, false);
    // then
    assertNotNull(connection);
}
Also used : HazelcastInstance(com.hazelcast.core.HazelcastInstance) Connection(com.hazelcast.internal.nio.Connection) ClientConfig(com.hazelcast.client.config.ClientConfig) QuickTest(com.hazelcast.test.annotation.QuickTest) Test(org.junit.Test)

Example 33 with Connection

use of com.hazelcast.internal.nio.Connection in project hazelcast by hazelcast.

the class TcpClientConnectionManagerTranslateTest method testTranslateIsUsedWhenMemberHasPublicClientAddress.

@Test
public void testTranslateIsUsedWhenMemberHasPublicClientAddress() throws UnknownHostException {
    // given
    ClientConfig clientConfig = new ClientConfig();
    clientConfig.setProperty(ClientProperty.DISCOVERY_SPI_PUBLIC_IP_ENABLED.getName(), "true");
    HazelcastInstance client = HazelcastClientUtil.newHazelcastClient(null, clientConfig);
    TcpClientConnectionManager clientConnectionManager = new TcpClientConnectionManager(getHazelcastClientInstanceImpl(client));
    clientConnectionManager.start();
    // private member address is unreachable
    Member member = new MemberImpl(new Address("192.168.0.1", 5701), VERSION, false, UUID.randomUUID());
    // public member address is reachable
    member.getAddressMap().put(EndpointQualifier.resolve(ProtocolType.CLIENT, "public"), new Address("127.0.0.1", 5701));
    // when
    Connection connection = clientConnectionManager.getOrConnectToMember(member, false);
    // then
    assertNotNull(connection);
}
Also used : HazelcastInstance(com.hazelcast.core.HazelcastInstance) Address(com.hazelcast.cluster.Address) MemberImpl(com.hazelcast.cluster.impl.MemberImpl) Connection(com.hazelcast.internal.nio.Connection) ClientConfig(com.hazelcast.client.config.ClientConfig) Member(com.hazelcast.cluster.Member) QuickTest(com.hazelcast.test.annotation.QuickTest) Test(org.junit.Test)

Example 34 with Connection

use of com.hazelcast.internal.nio.Connection in project hazelcast by hazelcast.

the class ClientListenerServiceImpl method deregisterListenerInternal.

private Boolean deregisterListenerInternal(@Nullable UUID userRegistrationId) {
    // This method should only be called from registrationExecutor
    assert (Thread.currentThread().getName().contains("eventRegistration"));
    ClientListenerRegistration listenerRegistration = registrations.remove(userRegistrationId);
    if (listenerRegistration == null) {
        return false;
    }
    Map<Connection, ClientConnectionRegistration> registrations = listenerRegistration.getConnectionRegistrations();
    CompletableFuture[] futures = new CompletableFuture[registrations.size()];
    int i = 0;
    for (Map.Entry<Connection, ClientConnectionRegistration> entry : registrations.entrySet()) {
        ClientConnectionRegistration registration = entry.getValue();
        ClientConnection subscriber = (ClientConnection) entry.getKey();
        // remove local handler
        subscriber.removeEventHandler(registration.getCallId());
        // the rest is for deleting remote registration
        ListenerMessageCodec listenerMessageCodec = listenerRegistration.getCodec();
        UUID serverRegistrationId = registration.getServerRegistrationId();
        ClientMessage request = listenerMessageCodec.encodeRemoveRequest(serverRegistrationId);
        if (request == null) {
            futures[i++] = CompletableFuture.completedFuture(null);
            continue;
        }
        ClientInvocation clientInvocation = new ClientInvocation(client, request, null, subscriber);
        clientInvocation.setInvocationTimeoutMillis(Long.MAX_VALUE);
        futures[i++] = clientInvocation.invokeUrgent().exceptionally(throwable -> {
            if (!(throwable instanceof HazelcastClientNotActiveException || throwable instanceof IOException || throwable instanceof TargetDisconnectedException)) {
                logger.warning("Deregistration of listener with ID " + userRegistrationId + " has failed for address " + subscriber.getRemoteAddress(), throwable);
            }
            return null;
        });
    }
    CompletableFuture.allOf(futures).join();
    return true;
}
Also used : HazelcastClientInstanceImpl(com.hazelcast.client.impl.clientside.HazelcastClientInstanceImpl) ClientConnection(com.hazelcast.client.impl.connection.ClientConnection) MetricsRegistry(com.hazelcast.internal.metrics.MetricsRegistry) MANDATORY(com.hazelcast.internal.metrics.ProbeLevel.MANDATORY) ClientExecutionServiceImpl(com.hazelcast.client.impl.spi.impl.ClientExecutionServiceImpl) CompletableFuture(java.util.concurrent.CompletableFuture) ClientListenerService(com.hazelcast.client.impl.spi.ClientListenerService) EmptyStatement(com.hazelcast.internal.util.EmptyStatement) EventHandler(com.hazelcast.client.impl.spi.EventHandler) SingleExecutorThreadFactory(com.hazelcast.internal.util.executor.SingleExecutorThreadFactory) ListenerMessageCodec(com.hazelcast.client.impl.spi.impl.ListenerMessageCodec) Future(java.util.concurrent.Future) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ClientProperty(com.hazelcast.client.properties.ClientProperty) ILogger(com.hazelcast.logging.ILogger) CLIENT_METRIC_LISTENER_SERVICE_EVENTS_PROCESSED(com.hazelcast.internal.metrics.MetricDescriptorConstants.CLIENT_METRIC_LISTENER_SERVICE_EVENTS_PROCESSED) Map(java.util.Map) HazelcastClientNotActiveException(com.hazelcast.client.HazelcastClientNotActiveException) UuidUtil(com.hazelcast.internal.util.UuidUtil) ThreadFactory(java.util.concurrent.ThreadFactory) ClientInvocation(com.hazelcast.client.impl.spi.impl.ClientInvocation) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) ExecutorService(java.util.concurrent.ExecutorService) ConnectionListener(com.hazelcast.internal.nio.ConnectionListener) HazelcastException(com.hazelcast.core.HazelcastException) Connection(com.hazelcast.internal.nio.Connection) Probe(com.hazelcast.internal.metrics.Probe) StripedRunnable(com.hazelcast.internal.util.executor.StripedRunnable) Collection(java.util.Collection) HazelcastProperties(com.hazelcast.spi.properties.HazelcastProperties) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ExceptionUtil(com.hazelcast.internal.util.ExceptionUtil) CLIENT_METRIC_LISTENER_SERVICE_EVENT_QUEUE_SIZE(com.hazelcast.internal.metrics.MetricDescriptorConstants.CLIENT_METRIC_LISTENER_SERVICE_EVENT_QUEUE_SIZE) CLIENT_PREFIX_LISTENERS(com.hazelcast.internal.metrics.MetricDescriptorConstants.CLIENT_PREFIX_LISTENERS) IOException(java.io.IOException) UUID(java.util.UUID) Preconditions.checkNotNull(com.hazelcast.internal.util.Preconditions.checkNotNull) Executors(java.util.concurrent.Executors) StaticMetricsProvider(com.hazelcast.internal.metrics.StaticMetricsProvider) TargetDisconnectedException(com.hazelcast.spi.exception.TargetDisconnectedException) ClientInvocationFuture(com.hazelcast.client.impl.spi.impl.ClientInvocationFuture) StripedExecutor(com.hazelcast.internal.util.executor.StripedExecutor) Collections(java.util.Collections) ClientConnectionManager(com.hazelcast.client.impl.connection.ClientConnectionManager) ClientMessage(com.hazelcast.client.impl.protocol.ClientMessage) ClientConnection(com.hazelcast.client.impl.connection.ClientConnection) Connection(com.hazelcast.internal.nio.Connection) ClientInvocation(com.hazelcast.client.impl.spi.impl.ClientInvocation) TargetDisconnectedException(com.hazelcast.spi.exception.TargetDisconnectedException) ClientMessage(com.hazelcast.client.impl.protocol.ClientMessage) IOException(java.io.IOException) ListenerMessageCodec(com.hazelcast.client.impl.spi.impl.ListenerMessageCodec) CompletableFuture(java.util.concurrent.CompletableFuture) HazelcastClientNotActiveException(com.hazelcast.client.HazelcastClientNotActiveException) ClientConnection(com.hazelcast.client.impl.connection.ClientConnection) UUID(java.util.UUID) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 35 with Connection

use of com.hazelcast.internal.nio.Connection in project hazelcast by hazelcast.

the class AbstractJoiner method sendSplitBrainJoinMessage.

/**
 * Sends a split brain join request to the target address and returns the response.
 */
private SplitBrainJoinMessage sendSplitBrainJoinMessage(Address target, SplitBrainJoinMessage request) {
    if (logger.isFineEnabled()) {
        logger.fine("Sending SplitBrainJoinMessage to " + target);
    }
    Connection conn = node.getServer().getConnectionManager(MEMBER).getOrConnect(target, true);
    long timeout = SPLIT_BRAIN_CONN_TIMEOUT_MILLIS;
    while (conn == null) {
        timeout -= SPLIT_BRAIN_SLEEP_TIME_MILLIS;
        if (timeout < 0) {
            logger.fine("Returning null timeout<0, " + timeout);
            return null;
        }
        try {
            // noinspection BusyWait
            Thread.sleep(SPLIT_BRAIN_SLEEP_TIME_MILLIS);
        } catch (InterruptedException e) {
            currentThread().interrupt();
            return null;
        }
        conn = node.getServer().getConnectionManager(MEMBER).get(target);
    }
    NodeEngine nodeEngine = node.nodeEngine;
    Future future = nodeEngine.getOperationService().createInvocationBuilder(ClusterServiceImpl.SERVICE_NAME, new SplitBrainMergeValidationOp(request), target).setTryCount(1).invoke();
    try {
        return (SplitBrainJoinMessage) future.get(SPLIT_BRAIN_JOIN_CHECK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        logger.fine("Timeout during join check!", e);
    } catch (Exception e) {
        logger.warning("Error during join check!", e);
    }
    return null;
}
Also used : NodeEngine(com.hazelcast.spi.impl.NodeEngine) Connection(com.hazelcast.internal.nio.Connection) SplitBrainMergeValidationOp(com.hazelcast.internal.cluster.impl.operations.SplitBrainMergeValidationOp) Future(java.util.concurrent.Future) TimeoutException(java.util.concurrent.TimeoutException) MemberLeftException(com.hazelcast.core.MemberLeftException) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

Connection (com.hazelcast.internal.nio.Connection)41 Test (org.junit.Test)14 QuickTest (com.hazelcast.test.annotation.QuickTest)11 ClientMessage (com.hazelcast.client.impl.protocol.ClientMessage)8 ServerConnection (com.hazelcast.internal.server.ServerConnection)7 ParallelJVMTest (com.hazelcast.test.annotation.ParallelJVMTest)7 ClientConnection (com.hazelcast.client.impl.connection.ClientConnection)6 Address (com.hazelcast.cluster.Address)6 HazelcastClientInstanceImpl (com.hazelcast.client.impl.clientside.HazelcastClientInstanceImpl)5 Member (com.hazelcast.cluster.Member)5 HazelcastInstance (com.hazelcast.core.HazelcastInstance)5 ConnectionListener (com.hazelcast.internal.nio.ConnectionListener)5 ClientConnectionManager (com.hazelcast.client.impl.connection.ClientConnectionManager)4 ILogger (com.hazelcast.logging.ILogger)4 QueryId (com.hazelcast.sql.impl.QueryId)4 Map (java.util.Map)4 UUID (java.util.UUID)4 ClientInvocation (com.hazelcast.client.impl.spi.impl.ClientInvocation)3 TargetDisconnectedException (com.hazelcast.spi.exception.TargetDisconnectedException)3 IOException (java.io.IOException)3