Search in sources :

Example 11 with GridCommunicationClient

use of org.apache.ignite.internal.util.nio.GridCommunicationClient in project ignite by apache.

the class TcpCommunicationSpi method sendMessage0.

/**
     * @param node Destination node.
     * @param msg Message to send.
     * @param ackC Ack closure.
     * @throws org.apache.ignite.spi.IgniteSpiException Thrown in case of any error during sending the message.
     *      Note that this is not guaranteed that failed communication will result
     *      in thrown exception as this is dependant on SPI implementation.
     */
private void sendMessage0(ClusterNode node, Message msg, IgniteInClosure<IgniteException> ackC) throws IgniteSpiException {
    assert node != null;
    assert msg != null;
    if (log.isTraceEnabled())
        log.trace("Sending message with ack to node [node=" + node + ", msg=" + msg + ']');
    ClusterNode locNode = getLocalNode();
    if (locNode == null)
        throw new IgniteSpiException("Local node has not been started or fully initialized " + "[isStopping=" + getSpiContext().isStopping() + ']');
    if (node.id().equals(locNode.id()))
        notifyListener(node.id(), msg, NOOP);
    else {
        GridCommunicationClient client = null;
        int connIdx = connPlc.connectionIndex();
        try {
            boolean retry;
            do {
                client = reserveClient(node, connIdx);
                UUID nodeId = null;
                if (!client.async())
                    nodeId = node.id();
                retry = client.sendMessage(nodeId, msg, ackC);
                client.release();
                if (!retry)
                    sentMsgsCnt.increment();
                else {
                    removeNodeClient(node.id(), client);
                    ClusterNode node0 = getSpiContext().node(node.id());
                    if (node0 == null)
                        throw new IgniteCheckedException("Failed to send message to remote node " + "(node has left the grid): " + node.id());
                }
                client = null;
            } while (retry);
        } catch (IgniteCheckedException e) {
            throw new IgniteSpiException("Failed to send message to remote node: " + node, e);
        } finally {
            if (client != null && removeNodeClient(node.id(), client))
                client.forceClose();
        }
    }
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) GridCommunicationClient(org.apache.ignite.internal.util.nio.GridCommunicationClient) UUID(java.util.UUID) IpcEndpoint(org.apache.ignite.internal.util.ipc.IpcEndpoint) IpcSharedMemoryServerEndpoint(org.apache.ignite.internal.util.ipc.shmem.IpcSharedMemoryServerEndpoint)

Example 12 with GridCommunicationClient

use of org.apache.ignite.internal.util.nio.GridCommunicationClient in project ignite by apache.

the class TcpCommunicationSpi method createShmemClient.

/**
     * @param node Node.
     * @param port Port.
     * @param connIdx Connection index.
     * @return Client.
     * @throws IgniteCheckedException If failed.
     */
@Nullable
private GridCommunicationClient createShmemClient(ClusterNode node, int connIdx, Integer port) throws IgniteCheckedException {
    int attempt = 1;
    int connectAttempts = 1;
    long connTimeout0 = connTimeout;
    IgniteSpiOperationTimeoutHelper timeoutHelper = new IgniteSpiOperationTimeoutHelper(this, !node.isClient());
    while (true) {
        GridCommunicationClient client;
        try {
            client = new GridShmemCommunicationClient(connIdx, metricsLsnr, port, timeoutHelper.nextTimeoutChunk(connTimeout), log, getSpiContext().messageFormatter());
        } catch (IgniteCheckedException e) {
            if (timeoutHelper.checkFailureTimeoutReached(e))
                throw e;
            // Reconnect for the second time, if connection is not established.
            if (connectAttempts < 2 && X.hasCause(e, ConnectException.class)) {
                connectAttempts++;
                continue;
            }
            throw e;
        }
        try {
            safeHandshake(client, null, node.id(), timeoutHelper.nextTimeoutChunk(connTimeout0), null, null);
        } catch (HandshakeTimeoutException | IgniteSpiOperationTimeoutException e) {
            client.forceClose();
            if (failureDetectionTimeoutEnabled() && (e instanceof HandshakeTimeoutException || timeoutHelper.checkFailureTimeoutReached(e))) {
                if (log.isDebugEnabled())
                    log.debug("Handshake timed out (failure threshold reached) [failureDetectionTimeout=" + failureDetectionTimeout() + ", err=" + e.getMessage() + ", client=" + client + ']');
                throw e;
            }
            assert !failureDetectionTimeoutEnabled();
            if (log.isDebugEnabled())
                log.debug("Handshake timed out (will retry with increased timeout) [timeout=" + connTimeout0 + ", err=" + e.getMessage() + ", client=" + client + ']');
            if (attempt == reconCnt || connTimeout0 > maxConnTimeout) {
                if (log.isDebugEnabled())
                    log.debug("Handshake timedout (will stop attempts to perform the handshake) " + "[timeout=" + connTimeout0 + ", maxConnTimeout=" + maxConnTimeout + ", attempt=" + attempt + ", reconCnt=" + reconCnt + ", err=" + e.getMessage() + ", client=" + client + ']');
                throw e;
            } else {
                attempt++;
                connTimeout0 *= 2;
                continue;
            }
        } catch (IgniteCheckedException | RuntimeException | Error e) {
            if (log.isDebugEnabled())
                log.debug("Caught exception (will close client) [err=" + e.getMessage() + ", client=" + client + ']');
            client.forceClose();
            throw e;
        }
        return client;
    }
}
Also used : IgniteSpiOperationTimeoutHelper(org.apache.ignite.spi.IgniteSpiOperationTimeoutHelper) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridShmemCommunicationClient(org.apache.ignite.internal.util.nio.GridShmemCommunicationClient) IgniteSpiOperationTimeoutException(org.apache.ignite.spi.IgniteSpiOperationTimeoutException) GridCommunicationClient(org.apache.ignite.internal.util.nio.GridCommunicationClient) IpcEndpoint(org.apache.ignite.internal.util.ipc.IpcEndpoint) IpcSharedMemoryServerEndpoint(org.apache.ignite.internal.util.ipc.shmem.IpcSharedMemoryServerEndpoint) Nullable(org.jetbrains.annotations.Nullable)

Example 13 with GridCommunicationClient

use of org.apache.ignite.internal.util.nio.GridCommunicationClient in project ignite by apache.

the class TcpCommunicationSpi method createTcpClient.

/**
     * Establish TCP connection to remote node and returns client.
     *
     * @param node Remote node.
     * @param connIdx Connection index.
     * @return Client.
     * @throws IgniteCheckedException If failed.
     */
protected GridCommunicationClient createTcpClient(ClusterNode node, int connIdx) throws IgniteCheckedException {
    Collection<String> rmtAddrs0 = node.attribute(createSpiAttributeName(ATTR_ADDRS));
    Collection<String> rmtHostNames0 = node.attribute(createSpiAttributeName(ATTR_HOST_NAMES));
    Integer boundPort = node.attribute(createSpiAttributeName(ATTR_PORT));
    Collection<InetSocketAddress> extAddrs = node.attribute(createSpiAttributeName(ATTR_EXT_ADDRS));
    boolean isRmtAddrsExist = (!F.isEmpty(rmtAddrs0) && boundPort != null);
    boolean isExtAddrsExist = !F.isEmpty(extAddrs);
    if (!isRmtAddrsExist && !isExtAddrsExist)
        throw new IgniteCheckedException("Failed to send message to the destination node. Node doesn't have any " + "TCP communication addresses or mapped external addresses. Check configuration and make sure " + "that you use the same communication SPI on all nodes. Remote node id: " + node.id());
    LinkedHashSet<InetSocketAddress> addrs;
    // Try to connect first on bound addresses.
    if (isRmtAddrsExist) {
        List<InetSocketAddress> addrs0 = new ArrayList<>(U.toSocketAddresses(rmtAddrs0, rmtHostNames0, boundPort));
        boolean sameHost = U.sameMacs(getSpiContext().localNode(), node);
        Collections.sort(addrs0, U.inetAddressesComparator(sameHost));
        addrs = new LinkedHashSet<>(addrs0);
    } else
        addrs = new LinkedHashSet<>();
    // Then on mapped external addresses.
    if (isExtAddrsExist)
        addrs.addAll(extAddrs);
    Set<InetAddress> allInetAddrs = U.newHashSet(addrs.size());
    for (InetSocketAddress addr : addrs) {
        // Skip unresolved as addr.getAddress() can return null.
        if (!addr.isUnresolved())
            allInetAddrs.add(addr.getAddress());
    }
    List<InetAddress> reachableInetAddrs = U.filterReachable(allInetAddrs);
    if (reachableInetAddrs.size() < allInetAddrs.size()) {
        LinkedHashSet<InetSocketAddress> addrs0 = U.newLinkedHashSet(addrs.size());
        List<InetSocketAddress> unreachableInetAddr = new ArrayList<>(allInetAddrs.size() - reachableInetAddrs.size());
        for (InetSocketAddress addr : addrs) {
            if (reachableInetAddrs.contains(addr.getAddress()))
                addrs0.add(addr);
            else
                unreachableInetAddr.add(addr);
        }
        addrs0.addAll(unreachableInetAddr);
        addrs = addrs0;
    }
    if (log.isDebugEnabled())
        log.debug("Addresses to connect for node [rmtNode=" + node.id() + ", addrs=" + addrs.toString() + ']');
    boolean conn = false;
    GridCommunicationClient client = null;
    IgniteCheckedException errs = null;
    int connectAttempts = 1;
    for (InetSocketAddress addr : addrs) {
        long connTimeout0 = connTimeout;
        int attempt = 1;
        IgniteSpiOperationTimeoutHelper timeoutHelper = new IgniteSpiOperationTimeoutHelper(this, !node.isClient());
        while (!conn) {
            // Reconnection on handshake timeout.
            try {
                SocketChannel ch = SocketChannel.open();
                ch.configureBlocking(true);
                ch.socket().setTcpNoDelay(tcpNoDelay);
                ch.socket().setKeepAlive(true);
                if (sockRcvBuf > 0)
                    ch.socket().setReceiveBufferSize(sockRcvBuf);
                if (sockSndBuf > 0)
                    ch.socket().setSendBufferSize(sockSndBuf);
                if (getSpiContext().node(node.id()) == null) {
                    U.closeQuiet(ch);
                    throw new ClusterTopologyCheckedException("Failed to send message " + "(node left topology): " + node);
                }
                ConnectionKey connKey = new ConnectionKey(node.id(), connIdx, -1);
                GridNioRecoveryDescriptor recoveryDesc = outRecoveryDescriptor(node, connKey);
                if (!recoveryDesc.reserve()) {
                    U.closeQuiet(ch);
                    return null;
                }
                long rcvCnt = -1;
                Map<Integer, Object> meta = new HashMap<>();
                GridSslMeta sslMeta = null;
                try {
                    ch.socket().connect(addr, (int) timeoutHelper.nextTimeoutChunk(connTimeout));
                    if (isSslEnabled()) {
                        meta.put(SSL_META.ordinal(), sslMeta = new GridSslMeta());
                        SSLEngine sslEngine = ignite.configuration().getSslContextFactory().create().createSSLEngine();
                        sslEngine.setUseClientMode(true);
                        sslMeta.sslEngine(sslEngine);
                    }
                    Integer handshakeConnIdx = connIdx;
                    rcvCnt = safeHandshake(ch, recoveryDesc, node.id(), timeoutHelper.nextTimeoutChunk(connTimeout0), sslMeta, handshakeConnIdx);
                    if (rcvCnt == -1)
                        return null;
                } finally {
                    if (recoveryDesc != null && rcvCnt == -1)
                        recoveryDesc.release();
                }
                try {
                    meta.put(CONN_IDX_META, connKey);
                    if (recoveryDesc != null) {
                        recoveryDesc.onHandshake(rcvCnt);
                        meta.put(-1, recoveryDesc);
                    }
                    GridNioSession ses = nioSrvr.createSession(ch, meta).get();
                    client = new GridTcpNioCommunicationClient(connIdx, ses, log);
                    conn = true;
                } finally {
                    if (!conn) {
                        if (recoveryDesc != null)
                            recoveryDesc.release();
                    }
                }
            } catch (HandshakeTimeoutException | IgniteSpiOperationTimeoutException e) {
                if (client != null) {
                    client.forceClose();
                    client = null;
                }
                if (failureDetectionTimeoutEnabled() && (e instanceof HandshakeTimeoutException || timeoutHelper.checkFailureTimeoutReached(e))) {
                    String msg = "Handshake timed out (failure detection timeout is reached) " + "[failureDetectionTimeout=" + failureDetectionTimeout() + ", addr=" + addr + ']';
                    onException(msg, e);
                    if (log.isDebugEnabled())
                        log.debug(msg);
                    if (errs == null)
                        errs = new IgniteCheckedException("Failed to connect to node (is node still alive?). " + "Make sure that each ComputeTask and cache Transaction has a timeout set " + "in order to prevent parties from waiting forever in case of network issues " + "[nodeId=" + node.id() + ", addrs=" + addrs + ']');
                    errs.addSuppressed(new IgniteCheckedException("Failed to connect to address: " + addr, e));
                    break;
                }
                assert !failureDetectionTimeoutEnabled();
                onException("Handshake timed out (will retry with increased timeout) [timeout=" + connTimeout0 + ", addr=" + addr + ']', e);
                if (log.isDebugEnabled())
                    log.debug("Handshake timed out (will retry with increased timeout) [timeout=" + connTimeout0 + ", addr=" + addr + ", err=" + e + ']');
                if (attempt == reconCnt || connTimeout0 > maxConnTimeout) {
                    if (log.isDebugEnabled())
                        log.debug("Handshake timedout (will stop attempts to perform the handshake) " + "[timeout=" + connTimeout0 + ", maxConnTimeout=" + maxConnTimeout + ", attempt=" + attempt + ", reconCnt=" + reconCnt + ", err=" + e.getMessage() + ", addr=" + addr + ']');
                    if (errs == null)
                        errs = new IgniteCheckedException("Failed to connect to node (is node still alive?). " + "Make sure that each ComputeTask and cache Transaction has a timeout set " + "in order to prevent parties from waiting forever in case of network issues " + "[nodeId=" + node.id() + ", addrs=" + addrs + ']');
                    errs.addSuppressed(new IgniteCheckedException("Failed to connect to address: " + addr, e));
                    break;
                } else {
                    attempt++;
                    connTimeout0 *= 2;
                // Continue loop.
                }
            } catch (Exception e) {
                if (client != null) {
                    client.forceClose();
                    client = null;
                }
                onException("Client creation failed [addr=" + addr + ", err=" + e + ']', e);
                if (log.isDebugEnabled())
                    log.debug("Client creation failed [addr=" + addr + ", err=" + e + ']');
                boolean failureDetThrReached = timeoutHelper.checkFailureTimeoutReached(e);
                if (failureDetThrReached)
                    LT.warn(log, "Connect timed out (consider increasing 'failureDetectionTimeout' " + "configuration property) [addr=" + addr + ", failureDetectionTimeout=" + failureDetectionTimeout() + ']');
                else if (X.hasCause(e, SocketTimeoutException.class))
                    LT.warn(log, "Connect timed out (consider increasing 'connTimeout' " + "configuration property) [addr=" + addr + ", connTimeout=" + connTimeout + ']');
                if (errs == null)
                    errs = new IgniteCheckedException("Failed to connect to node (is node still alive?). " + "Make sure that each ComputeTask and cache Transaction has a timeout set " + "in order to prevent parties from waiting forever in case of network issues " + "[nodeId=" + node.id() + ", addrs=" + addrs + ']');
                errs.addSuppressed(new IgniteCheckedException("Failed to connect to address: " + addr, e));
                // Reconnect for the second time, if connection is not established.
                if (!failureDetThrReached && connectAttempts < 2 && (e instanceof ConnectException || X.hasCause(e, ConnectException.class))) {
                    connectAttempts++;
                    continue;
                }
                break;
            }
        }
        if (conn)
            break;
    }
    if (client == null) {
        assert errs != null;
        if (X.hasCause(errs, ConnectException.class))
            LT.warn(log, "Failed to connect to a remote node " + "(make sure that destination node is alive and " + "operating system firewall is disabled on local and remote hosts) " + "[addrs=" + addrs + ']');
        if (getSpiContext().node(node.id()) != null && (CU.clientNode(node) || !CU.clientNode(getLocalNode())) && X.hasCause(errs, ConnectException.class, SocketTimeoutException.class, HandshakeTimeoutException.class, IgniteSpiOperationTimeoutException.class)) {
            LT.warn(log, "TcpCommunicationSpi failed to establish connection to node, node will be dropped from " + "cluster [" + "rmtNode=" + node + ", err=" + errs + ", connectErrs=" + Arrays.toString(errs.getSuppressed()) + ']');
            getSpiContext().failNode(node.id(), "TcpCommunicationSpi failed to establish connection to node [" + "rmtNode=" + node + ", errs=" + errs + ", connectErrs=" + Arrays.toString(errs.getSuppressed()) + ']');
        }
        throw errs;
    }
    return client;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) SocketChannel(java.nio.channels.SocketChannel) GridNioSession(org.apache.ignite.internal.util.nio.GridNioSession) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) SSLEngine(javax.net.ssl.SSLEngine) ArrayList(java.util.ArrayList) GridSslMeta(org.apache.ignite.internal.util.nio.ssl.GridSslMeta) GridTcpNioCommunicationClient(org.apache.ignite.internal.util.nio.GridTcpNioCommunicationClient) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteSpiOperationTimeoutException(org.apache.ignite.spi.IgniteSpiOperationTimeoutException) ConnectException(java.net.ConnectException) GridCommunicationClient(org.apache.ignite.internal.util.nio.GridCommunicationClient) IpcEndpoint(org.apache.ignite.internal.util.ipc.IpcEndpoint) IpcSharedMemoryServerEndpoint(org.apache.ignite.internal.util.ipc.shmem.IpcSharedMemoryServerEndpoint) IgniteClientDisconnectedException(org.apache.ignite.IgniteClientDisconnectedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) SSLException(javax.net.ssl.SSLException) IgniteSpiOperationTimeoutException(org.apache.ignite.spi.IgniteSpiOperationTimeoutException) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) SocketTimeoutException(java.net.SocketTimeoutException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) ConnectException(java.net.ConnectException) IpcOutOfSystemResourcesException(org.apache.ignite.internal.util.ipc.shmem.IpcOutOfSystemResourcesException) IOException(java.io.IOException) IgniteClientDisconnectedCheckedException(org.apache.ignite.internal.IgniteClientDisconnectedCheckedException) IgniteException(org.apache.ignite.IgniteException) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IgniteSpiOperationTimeoutHelper(org.apache.ignite.spi.IgniteSpiOperationTimeoutHelper) SocketTimeoutException(java.net.SocketTimeoutException) GridNioRecoveryDescriptor(org.apache.ignite.internal.util.nio.GridNioRecoveryDescriptor) IgniteSpiTimeoutObject(org.apache.ignite.spi.IgniteSpiTimeoutObject) InetAddress(java.net.InetAddress) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)

Example 14 with GridCommunicationClient

use of org.apache.ignite.internal.util.nio.GridCommunicationClient in project ignite by apache.

the class TcpCommunicationSpi method spiStop.

/** {@inheritDoc} */
@Override
public void spiStop() throws IgniteSpiException {
    assert stopping;
    unregisterMBean();
    // Stop TCP server.
    if (nioSrvr != null)
        nioSrvr.stop();
    U.interrupt(commWorker);
    U.join(commWorker, log);
    U.cancel(shmemAcceptWorker);
    U.join(shmemAcceptWorker, log);
    U.cancel(shmemWorkers);
    U.join(shmemWorkers, log);
    shmemWorkers.clear();
    // Force closing on stop (safety).
    for (GridCommunicationClient[] clients0 : clients.values()) {
        for (GridCommunicationClient client : clients0) {
            if (client != null)
                client.forceClose();
        }
    }
    // Clear resources.
    nioSrvr = null;
    commWorker = null;
    boundTcpPort = -1;
    // Ack stop.
    if (log.isDebugEnabled())
        log.debug(stopInfo());
}
Also used : GridCommunicationClient(org.apache.ignite.internal.util.nio.GridCommunicationClient)

Example 15 with GridCommunicationClient

use of org.apache.ignite.internal.util.nio.GridCommunicationClient in project ignite by apache.

the class TcpCommunicationSpi method simulateNodeFailure.

/**
     * Stops service threads to simulate node failure.
     *
     * FOR TEST PURPOSES ONLY!!!
     */
public void simulateNodeFailure() {
    if (nioSrvr != null)
        nioSrvr.stop();
    U.interrupt(commWorker);
    U.join(commWorker, log);
    for (GridCommunicationClient[] clients0 : clients.values()) {
        for (GridCommunicationClient client : clients0) {
            if (client != null)
                client.forceClose();
        }
    }
}
Also used : GridCommunicationClient(org.apache.ignite.internal.util.nio.GridCommunicationClient)

Aggregations

GridCommunicationClient (org.apache.ignite.internal.util.nio.GridCommunicationClient)16 UUID (java.util.UUID)9 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)5 ClusterNode (org.apache.ignite.cluster.ClusterNode)4 IpcEndpoint (org.apache.ignite.internal.util.ipc.IpcEndpoint)4 IpcSharedMemoryServerEndpoint (org.apache.ignite.internal.util.ipc.shmem.IpcSharedMemoryServerEndpoint)4 CommunicationSpi (org.apache.ignite.spi.communication.CommunicationSpi)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 GridTcpNioCommunicationClient (org.apache.ignite.internal.util.nio.GridTcpNioCommunicationClient)3 IgniteSpiException (org.apache.ignite.spi.IgniteSpiException)3 IOException (java.io.IOException)2 SocketChannel (java.nio.channels.SocketChannel)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 IgniteClientDisconnectedCheckedException (org.apache.ignite.internal.IgniteClientDisconnectedCheckedException)2 IpcOutOfSystemResourcesException (org.apache.ignite.internal.util.ipc.shmem.IpcOutOfSystemResourcesException)2 GridNioRecoveryDescriptor (org.apache.ignite.internal.util.nio.GridNioRecoveryDescriptor)2 GridNioSession (org.apache.ignite.internal.util.nio.GridNioSession)2 IgniteSpiOperationTimeoutException (org.apache.ignite.spi.IgniteSpiOperationTimeoutException)2 IgniteSpiOperationTimeoutHelper (org.apache.ignite.spi.IgniteSpiOperationTimeoutHelper)2