Search in sources :

Example 91 with IgniteSpiException

use of org.apache.ignite.spi.IgniteSpiException in project ignite by apache.

the class ClientImpl method sendJoinRequest.

/**
 * @param recon {@code True} if reconnects.
 * @param addr Address.
 * @return Socket, connect response and client acknowledge support flag.
 */
@Nullable
private T3<SocketStream, Integer, Boolean> sendJoinRequest(boolean recon, InetSocketAddress addr) {
    assert addr != null;
    if (log.isDebugEnabled())
        log.debug("Send join request [addr=" + addr + ", reconnect=" + recon + ", locNodeId=" + getLocalNodeId() + ']');
    Collection<Throwable> errs = null;
    long ackTimeout0 = spi.getAckTimeout();
    int reconCnt = 0;
    int connectAttempts = 1;
    int sslConnectAttempts = 3;
    UUID locNodeId = getLocalNodeId();
    IgniteSpiOperationTimeoutHelper timeoutHelper = new IgniteSpiOperationTimeoutHelper(spi, true);
    DiscoveryDataPacket discoveryData = null;
    while (true) {
        boolean openSock = false;
        Socket sock = null;
        try {
            long tsNanos = System.nanoTime();
            sock = spi.openSocket(addr, timeoutHelper);
            openSock = true;
            TcpDiscoveryHandshakeRequest req = new TcpDiscoveryHandshakeRequest(locNodeId);
            req.client(true);
            spi.writeToSocket(sock, req, timeoutHelper.nextTimeoutChunk(spi.getSocketTimeout()));
            TcpDiscoveryHandshakeResponse res = spi.readMessage(sock, null, ackTimeout0);
            UUID rmtNodeId = res.creatorNodeId();
            assert rmtNodeId != null;
            assert !getLocalNodeId().equals(rmtNodeId);
            locNode.clientRouterNodeId(rmtNodeId);
            tsNanos = System.nanoTime();
            TcpDiscoveryAbstractMessage msg;
            if (!recon) {
                TcpDiscoveryNode node = locNode;
                if (locNode.order() > 0) {
                    node = locNode.clientReconnectNode(spi.locNodeAttrs);
                    marshalCredentials(node);
                }
                if (discoveryData == null) {
                    DiscoveryDataPacket dataPacket = new DiscoveryDataPacket(getLocalNodeId());
                    dataPacket.joiningNodeClient(true);
                    discoveryData = spi.collectExchangeData(dataPacket);
                }
                TcpDiscoveryJoinRequestMessage joinReqMsg = new TcpDiscoveryJoinRequestMessage(node, discoveryData);
                TcpDiscoveryNode nodef = node;
                joinReqMsg.spanContainer().span(tracing.create(TraceableMessagesTable.traceName(joinReqMsg.getClass())).addTag(SpanTags.tag(SpanTags.EVENT_NODE, SpanTags.ID), () -> nodef.id().toString()).addTag(SpanTags.tag(SpanTags.EVENT_NODE, SpanTags.CONSISTENT_ID), () -> nodef.consistentId().toString()).addLog(() -> "Created").end());
                msg = joinReqMsg;
                // The only way to know is passing flag directly with handshake response.
                if (!res.isDiscoveryDataPacketCompression())
                    ((TcpDiscoveryJoinRequestMessage) msg).gridDiscoveryData().unzipData(log);
            } else
                msg = new TcpDiscoveryClientReconnectMessage(getLocalNodeId(), rmtNodeId, lastMsgId);
            msg.client(true);
            if (msg instanceof TraceableMessage)
                tracing.messages().beforeSend((TraceableMessage) msg);
            spi.writeToSocket(sock, msg, timeoutHelper.nextTimeoutChunk(spi.getSocketTimeout()));
            spi.stats.onMessageSent(msg, U.millisSinceNanos(tsNanos));
            if (log.isDebugEnabled())
                log.debug("Message has been sent to address [msg=" + msg + ", addr=" + addr + ", rmtNodeId=" + rmtNodeId + ']');
            return new T3<>(new SocketStream(sock), spi.readReceipt(sock, timeoutHelper.nextTimeoutChunk(ackTimeout0)), res.clientAck());
        } catch (IOException | IgniteCheckedException e) {
            U.closeQuiet(sock);
            if (log.isDebugEnabled())
                log.error("Exception on joining: " + e.getMessage(), e);
            onException("Exception on joining: " + e.getMessage(), e);
            if (errs == null)
                errs = new ArrayList<>();
            errs.add(e);
            if (X.hasCause(e, SSLException.class)) {
                if (--sslConnectAttempts == 0)
                    throw new IgniteSpiException("Unable to establish secure connection. " + "Was remote cluster configured with SSL? [rmtAddr=" + addr + ", errMsg=\"" + e.getMessage() + "\"]", e);
                continue;
            }
            if (X.hasCause(e, StreamCorruptedException.class)) {
                // StreamCorruptedException could be caused by remote node failover
                if (connectAttempts < 2) {
                    connectAttempts++;
                    continue;
                }
                if (log.isDebugEnabled())
                    log.debug("Connect failed with StreamCorruptedException, skip address: " + addr);
                break;
            }
            if (timeoutHelper.checkFailureTimeoutReached(e))
                break;
            if (!spi.failureDetectionTimeoutEnabled() && ++reconCnt == spi.getReconnectCount())
                break;
            if (!openSock) {
                // Reconnect for the second time, if connection is not established.
                if (connectAttempts < 2) {
                    connectAttempts++;
                    continue;
                }
                // Don't retry if we can not establish connection.
                break;
            }
            if (!spi.failureDetectionTimeoutEnabled() && (e instanceof SocketTimeoutException || X.hasCause(e, SocketTimeoutException.class))) {
                ackTimeout0 *= 2;
                if (!checkAckTimeout(ackTimeout0))
                    break;
            }
        }
    }
    if (log.isDebugEnabled())
        log.debug("Failed to join to address [addr=" + addr + ", recon=" + recon + ", errs=" + errs + ']');
    return null;
}
Also used : SSLException(javax.net.ssl.SSLException) TcpDiscoveryClientReconnectMessage(org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryClientReconnectMessage) DiscoveryDataPacket(org.apache.ignite.spi.discovery.tcp.internal.DiscoveryDataPacket) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) StreamCorruptedException(java.io.StreamCorruptedException) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) UUID(java.util.UUID) TcpDiscoveryJoinRequestMessage(org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryJoinRequestMessage) T3(org.apache.ignite.internal.util.typedef.T3) TcpDiscoveryHandshakeRequest(org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryHandshakeRequest) TcpDiscoveryHandshakeResponse(org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryHandshakeResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) IgniteSpiOperationTimeoutHelper(org.apache.ignite.spi.IgniteSpiOperationTimeoutHelper) TraceableMessage(org.apache.ignite.internal.processors.tracing.messages.TraceableMessage) SocketTimeoutException(java.net.SocketTimeoutException) TcpDiscoveryAbstractMessage(org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryAbstractMessage) Socket(java.net.Socket) TcpDiscoveryNode(org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoveryNode) Nullable(org.jetbrains.annotations.Nullable)

Example 92 with IgniteSpiException

use of org.apache.ignite.spi.IgniteSpiException in project ignite by apache.

the class ClientImpl method pingNode.

/**
 * {@inheritDoc}
 */
@Override
public boolean pingNode(@NotNull final UUID nodeId) {
    if (nodeId.equals(getLocalNodeId()))
        return true;
    TcpDiscoveryNode node = rmtNodes.get(nodeId);
    if (node == null || !node.visible())
        return false;
    GridFutureAdapter<Boolean> fut = pingFuts.get(nodeId);
    if (fut == null) {
        fut = new GridFutureAdapter<>();
        GridFutureAdapter<Boolean> oldFut = pingFuts.putIfAbsent(nodeId, fut);
        if (oldFut != null)
            fut = oldFut;
        else {
            State state = this.state;
            if (spi.getSpiContext().isStopping() || state == STOPPED || state == SEGMENTED) {
                if (pingFuts.remove(nodeId, fut))
                    fut.onDone(false);
                return false;
            } else if (state == DISCONNECTED) {
                if (pingFuts.remove(nodeId, fut))
                    fut.onDone(new IgniteClientDisconnectedCheckedException(null, "Failed to ping node, client node disconnected."));
            } else {
                final GridFutureAdapter<Boolean> finalFut = fut;
                executorService.schedule(() -> {
                    if (pingFuts.remove(nodeId, finalFut)) {
                        if (ClientImpl.this.state == DISCONNECTED)
                            finalFut.onDone(new IgniteClientDisconnectedCheckedException(null, "Failed to ping node, client node disconnected."));
                        else
                            finalFut.onDone(false);
                    }
                }, spi.netTimeout, MILLISECONDS);
                sockWriter.sendMessage(new TcpDiscoveryClientPingRequest(getLocalNodeId(), nodeId));
            }
        }
    }
    try {
        return fut.get();
    } catch (IgniteInterruptedCheckedException ignored) {
        return false;
    } catch (IgniteCheckedException e) {
        throw new IgniteSpiException(e);
    }
}
Also used : TcpDiscoveryClientPingRequest(org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryClientPingRequest) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) IgniteClientDisconnectedCheckedException(org.apache.ignite.internal.IgniteClientDisconnectedCheckedException) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) TcpDiscoveryNode(org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoveryNode)

Example 93 with IgniteSpiException

use of org.apache.ignite.spi.IgniteSpiException in project ignite by apache.

the class TcpDiscoveryJdbcIpFinder method getRegisteredAddresses.

/**
 * {@inheritDoc}
 */
@Override
public Collection<InetSocketAddress> getRegisteredAddresses() throws IgniteSpiException {
    init();
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        conn = dataSrc.getConnection();
        conn.setTransactionIsolation(TRANSACTION_READ_COMMITTED);
        stmt = conn.prepareStatement(getAddrsQry);
        rs = stmt.executeQuery();
        Collection<InetSocketAddress> addrs = new LinkedList<>();
        while (rs.next()) addrs.add(new InetSocketAddress(rs.getString(1), rs.getInt(2)));
        return addrs;
    } catch (SQLException e) {
        throw new IgniteSpiException("Failed to get registered addresses version.", e);
    } finally {
        U.closeQuiet(rs);
        U.closeQuiet(stmt);
        U.closeQuiet(conn);
    }
}
Also used : SQLException(java.sql.SQLException) InetSocketAddress(java.net.InetSocketAddress) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) LinkedList(java.util.LinkedList)

Example 94 with IgniteSpiException

use of org.apache.ignite.spi.IgniteSpiException in project ignite by apache.

the class TcpDiscoveryJdbcIpFinder method unregisterAddresses.

/**
 * {@inheritDoc}
 */
@Override
public void unregisterAddresses(Collection<InetSocketAddress> addrs) throws IgniteSpiException {
    assert !F.isEmpty(addrs);
    init();
    Connection conn = null;
    PreparedStatement stmt = null;
    boolean committed = false;
    try {
        conn = dataSrc.getConnection();
        conn.setAutoCommit(false);
        conn.setTransactionIsolation(TRANSACTION_READ_COMMITTED);
        stmt = conn.prepareStatement(unregAddrQry);
        for (InetSocketAddress addr : addrs) {
            stmt.setString(1, addr.getAddress().getHostAddress());
            stmt.setInt(2, addr.getPort());
            stmt.addBatch();
        }
        stmt.executeBatch();
        conn.commit();
        committed = true;
    } catch (SQLException e) {
        U.rollbackConnectionQuiet(conn);
        throw new IgniteSpiException("Failed to unregister addresses: " + addrs, e);
    } finally {
        if (!committed)
            U.rollbackConnectionQuiet(conn);
        U.closeQuiet(stmt);
        U.closeQuiet(conn);
    }
}
Also used : SQLException(java.sql.SQLException) InetSocketAddress(java.net.InetSocketAddress) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException)

Example 95 with IgniteSpiException

use of org.apache.ignite.spi.IgniteSpiException in project ignite by apache.

the class TcpDiscoveryMulticastIpFinder method resolveLocalAddresses.

/**
 * Resolve local addresses.
 *
 * @return List of non-loopback addresses.
 */
private Collection<InetAddress> resolveLocalAddresses() {
    // If IGNITE_OVERRIDE_MCAST_GRP system property is set, use its value to override multicast group from
    // configuration. Used for testing purposes.
    String overrideMcastGrp = System.getProperty(IGNITE_OVERRIDE_MCAST_GRP);
    if (overrideMcastGrp != null)
        mcastGrp = overrideMcastGrp;
    if (F.isEmpty(mcastGrp))
        throw new IgniteSpiException("Multicast IP address is not specified.");
    if (mcastPort < 0 || mcastPort > 65535)
        throw new IgniteSpiException("Invalid multicast port: " + mcastPort);
    if (resWaitTime <= 0)
        throw new IgniteSpiException("Invalid wait time, value greater than zero is expected: " + resWaitTime);
    if (addrReqAttempts <= 0)
        throw new IgniteSpiException("Invalid number of address request attempts, " + "value greater than zero is expected: " + addrReqAttempts);
    if (ttl != -1 && (ttl < 0 || ttl > 255))
        throw new IgniteSpiException("Time-to-live value is out of 0 <= TTL <= 255 range: " + ttl);
    try {
        mcastAddr = InetAddress.getByName(mcastGrp);
    } catch (UnknownHostException e) {
        throw new IgniteSpiException("Unknown multicast group: " + mcastGrp, e);
    }
    if (!mcastAddr.isMulticastAddress())
        throw new IgniteSpiException("Invalid multicast group address: " + mcastAddr);
    Collection<String> locAddrs;
    try {
        locAddrs = U.resolveLocalAddresses(U.resolveLocalHost(locAddr)).get1();
    } catch (IOException e) {
        throw new IgniteSpiException("Failed to resolve local addresses [locAddr=" + locAddr + ']', e);
    }
    assert locAddrs != null;
    List<InetAddress> inetAddrs = new ArrayList<>(locAddrs.size());
    for (String locAddr : locAddrs) {
        InetAddress addr;
        try {
            addr = InetAddress.getByName(locAddr);
        } catch (UnknownHostException e) {
            if (log.isDebugEnabled())
                log.debug("Failed to resolve local address [locAddr=" + locAddr + ", err=" + e + ']');
            continue;
        }
        if (!addr.isLoopbackAddress())
            inetAddrs.add(addr);
    }
    return inetAddrs;
}
Also used : UnknownHostException(java.net.UnknownHostException) ArrayList(java.util.ArrayList) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) IOException(java.io.IOException) InetAddress(java.net.InetAddress)

Aggregations

IgniteSpiException (org.apache.ignite.spi.IgniteSpiException)131 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)59 IOException (java.io.IOException)32 InetSocketAddress (java.net.InetSocketAddress)22 ClusterNode (org.apache.ignite.cluster.ClusterNode)21 IgniteInterruptedCheckedException (org.apache.ignite.internal.IgniteInterruptedCheckedException)21 IgniteException (org.apache.ignite.IgniteException)20 ArrayList (java.util.ArrayList)14 ClusterTopologyCheckedException (org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)14 HashMap (java.util.HashMap)13 UUID (java.util.UUID)13 Nullable (org.jetbrains.annotations.Nullable)12 Test (org.junit.Test)12 File (java.io.File)10 Message (org.apache.ignite.plugin.extensions.communication.Message)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 SSLException (javax.net.ssl.SSLException)8 IgniteConfiguration (org.apache.ignite.configuration.IgniteConfiguration)8 SocketTimeoutException (java.net.SocketTimeoutException)7 Ignite (org.apache.ignite.Ignite)7