Search in sources :

Example 21 with StreamCorruptedException

use of java.io.StreamCorruptedException in project jdk8u_jdk by JetBrains.

the class Path2D method readObject.

final void readObject(java.io.ObjectInputStream s, boolean storedbl) throws java.lang.ClassNotFoundException, java.io.IOException {
    s.defaultReadObject();
    // The subclass calls this method with the storage type that
    // they want us to use (storedbl) so we ignore the storage
    // method hint from the stream.
    s.readByte();
    int nT = s.readInt();
    int nC = s.readInt();
    try {
        setWindingRule(s.readByte());
    } catch (IllegalArgumentException iae) {
        throw new java.io.InvalidObjectException(iae.getMessage());
    }
    pointTypes = new byte[(nT < 0) ? INIT_SIZE : nT];
    if (nC < 0) {
        nC = INIT_SIZE * 2;
    }
    if (storedbl) {
        ((Path2D.Double) this).doubleCoords = new double[nC];
    } else {
        ((Path2D.Float) this).floatCoords = new float[nC];
    }
    PATHDONE: for (int i = 0; nT < 0 || i < nT; i++) {
        boolean isdbl;
        int npoints;
        byte segtype;
        byte serialtype = s.readByte();
        switch(serialtype) {
            case SERIAL_SEG_FLT_MOVETO:
                isdbl = false;
                npoints = 1;
                segtype = SEG_MOVETO;
                break;
            case SERIAL_SEG_FLT_LINETO:
                isdbl = false;
                npoints = 1;
                segtype = SEG_LINETO;
                break;
            case SERIAL_SEG_FLT_QUADTO:
                isdbl = false;
                npoints = 2;
                segtype = SEG_QUADTO;
                break;
            case SERIAL_SEG_FLT_CUBICTO:
                isdbl = false;
                npoints = 3;
                segtype = SEG_CUBICTO;
                break;
            case SERIAL_SEG_DBL_MOVETO:
                isdbl = true;
                npoints = 1;
                segtype = SEG_MOVETO;
                break;
            case SERIAL_SEG_DBL_LINETO:
                isdbl = true;
                npoints = 1;
                segtype = SEG_LINETO;
                break;
            case SERIAL_SEG_DBL_QUADTO:
                isdbl = true;
                npoints = 2;
                segtype = SEG_QUADTO;
                break;
            case SERIAL_SEG_DBL_CUBICTO:
                isdbl = true;
                npoints = 3;
                segtype = SEG_CUBICTO;
                break;
            case SERIAL_SEG_CLOSE:
                isdbl = false;
                npoints = 0;
                segtype = SEG_CLOSE;
                break;
            case SERIAL_PATH_END:
                if (nT < 0) {
                    break PATHDONE;
                }
                throw new StreamCorruptedException("unexpected PATH_END");
            default:
                throw new StreamCorruptedException("unrecognized path type");
        }
        needRoom(segtype != SEG_MOVETO, npoints * 2);
        if (isdbl) {
            while (--npoints >= 0) {
                append(s.readDouble(), s.readDouble());
            }
        } else {
            while (--npoints >= 0) {
                append(s.readFloat(), s.readFloat());
            }
        }
        pointTypes[numTypes++] = segtype;
    }
    if (nT >= 0 && s.readByte() != SERIAL_PATH_END) {
        throw new StreamCorruptedException("missing PATH_END");
    }
}
Also used : StreamCorruptedException(java.io.StreamCorruptedException)

Example 22 with StreamCorruptedException

use of java.io.StreamCorruptedException 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 tstamp = U.currentTimeMillis();
            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);
            spi.stats.onClientSocketInitialized(U.currentTimeMillis() - tstamp);
            locNode.clientRouterNodeId(rmtNodeId);
            tstamp = U.currentTimeMillis();
            TcpDiscoveryAbstractMessage msg;
            if (!recon) {
                TcpDiscoveryNode node = locNode;
                if (locNode.order() > 0) {
                    node = locNode.clientReconnectNode(spi.spiCtx.nodeAttributes());
                    marshalCredentials(node);
                }
                if (discoveryData == null)
                    discoveryData = spi.collectExchangeData(new DiscoveryDataPacket(getLocalNodeId()));
                msg = new TcpDiscoveryJoinRequestMessage(node, discoveryData);
            } else
                msg = new TcpDiscoveryClientReconnectMessage(getLocalNodeId(), rmtNodeId, lastMsgId);
            msg.client(true);
            spi.writeToSocket(sock, msg, timeoutHelper.nextTimeoutChunk(spi.getSocketTimeout()));
            spi.stats.onMessageSent(msg, U.currentTimeMillis() - tstamp);
            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) IOException(java.io.IOException) IgniteSpiOperationTimeoutHelper(org.apache.ignite.spi.IgniteSpiOperationTimeoutHelper) 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 23 with StreamCorruptedException

use of java.io.StreamCorruptedException in project ignite by apache.

the class ServerImpl method sendMessageDirectly.

/**
 * Establishes connection to an address, sends message and returns the response (if any).
 *
 * @param msg Message to send.
 * @param addr Address to send message to.
 * @param timeoutHelper Operation timeout helper.
 * @return Response read from the recipient or {@code null} if no response is supposed.
 * @throws IgniteSpiException If an error occurs.
 */
@Nullable
private Integer sendMessageDirectly(TcpDiscoveryAbstractMessage msg, InetSocketAddress addr, IgniteSpiOperationTimeoutHelper timeoutHelper) throws IgniteSpiException {
    assert msg != null;
    assert addr != null;
    Collection<Throwable> errs = null;
    long ackTimeout0 = spi.getAckTimeout();
    int connectAttempts = 1;
    int sslConnectAttempts = 3;
    boolean joinReqSent;
    UUID locNodeId = getLocalNodeId();
    int reconCnt = 0;
    while (true) {
        // Need to set to false on each new iteration,
        // since remote node may leave in the middle of the first iteration.
        joinReqSent = false;
        boolean openSock = false;
        Socket sock = null;
        try {
            long tstamp = U.currentTimeMillis();
            sock = spi.openSocket(addr, timeoutHelper);
            openSock = true;
            TcpDiscoveryHandshakeRequest req = new TcpDiscoveryHandshakeRequest(locNodeId);
            // Handshake.
            spi.writeToSocket(sock, req, timeoutHelper.nextTimeoutChunk(spi.getSocketTimeout()));
            TcpDiscoveryHandshakeResponse res = spi.readMessage(sock, null, timeoutHelper.nextTimeoutChunk(ackTimeout0));
            if (msg instanceof TcpDiscoveryJoinRequestMessage) {
                boolean ignore = false;
                synchronized (failedNodes) {
                    for (TcpDiscoveryNode failedNode : failedNodes.keySet()) {
                        if (failedNode.id().equals(res.creatorNodeId())) {
                            if (log.isDebugEnabled())
                                log.debug("Ignore response from node from failed list: " + res);
                            ignore = true;
                            break;
                        }
                    }
                }
                if (ignore)
                    break;
            }
            if (locNodeId.equals(res.creatorNodeId())) {
                if (log.isDebugEnabled())
                    log.debug("Handshake response from local node: " + res);
                break;
            }
            spi.stats.onClientSocketInitialized(U.currentTimeMillis() - tstamp);
            // Send message.
            tstamp = U.currentTimeMillis();
            spi.writeToSocket(sock, msg, timeoutHelper.nextTimeoutChunk(spi.getSocketTimeout()));
            long tstamp0 = U.currentTimeMillis();
            if (debugMode)
                debugLog(msg, "Message has been sent directly to address [msg=" + msg + ", addr=" + addr + ", rmtNodeId=" + res.creatorNodeId() + ']');
            if (log.isDebugEnabled())
                log.debug("Message has been sent directly to address [msg=" + msg + ", addr=" + addr + ", rmtNodeId=" + res.creatorNodeId() + ']');
            // Connection has been established, but
            // join request may not be unmarshalled on remote host.
            // E.g. due to class not found issue.
            joinReqSent = msg instanceof TcpDiscoveryJoinRequestMessage;
            int receipt = spi.readReceipt(sock, timeoutHelper.nextTimeoutChunk(ackTimeout0));
            spi.stats.onMessageSent(msg, tstamp0 - tstamp);
            return receipt;
        } catch (ClassCastException e) {
            // on dedicated machines.
            if (log.isDebugEnabled())
                U.error(log, "Class cast exception on direct send: " + addr, e);
            onException("Class cast exception on direct send: " + addr, e);
            if (errs == null)
                errs = new ArrayList<>();
            errs.add(e);
        } catch (IOException | IgniteCheckedException e) {
            if (log.isDebugEnabled())
                log.error("Exception on direct send: " + e.getMessage(), e);
            onException("Exception on direct send: " + e.getMessage(), e);
            if (errs == null)
                errs = new ArrayList<>();
            errs.add(e);
            if (X.hasCause(e, SSLException.class)) {
                if (--sslConnectAttempts == 0)
                    throw new IgniteException("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;
            }
        } finally {
            U.closeQuiet(sock);
        }
    }
    if (joinReqSent) {
        if (log.isDebugEnabled())
            log.debug("Join request has been sent, but receipt has not been read (returning RES_WAIT).");
        // however, warning on timed out join will be output.
        return RES_OK;
    }
    throw new IgniteSpiException("Failed to send message to address [addr=" + addr + ", msg=" + msg + ']', U.exceptionWithSuppressed("Failed to send message to address " + "[addr=" + addr + ", msg=" + msg + ']', errs));
}
Also used : TcpDiscoveryHandshakeRequest(org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryHandshakeRequest) TcpDiscoveryHandshakeResponse(org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryHandshakeResponse) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) SocketTimeoutException(java.net.SocketTimeoutException) IgniteException(org.apache.ignite.IgniteException) StreamCorruptedException(java.io.StreamCorruptedException) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) UUID(java.util.UUID) ServerSocket(java.net.ServerSocket) SSLServerSocket(javax.net.ssl.SSLServerSocket) SSLSocket(javax.net.ssl.SSLSocket) Socket(java.net.Socket) TcpDiscoveryNode(org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoveryNode) TcpDiscoveryJoinRequestMessage(org.apache.ignite.spi.discovery.tcp.messages.TcpDiscoveryJoinRequestMessage) Nullable(org.jetbrains.annotations.Nullable)

Example 24 with StreamCorruptedException

use of java.io.StreamCorruptedException in project ignite by apache.

the class TcpDiscoverySpi method readMessage.

/**
 * Reads message from the socket limiting read time.
 *
 * @param sock Socket.
 * @param in Input stream (in case socket stream was wrapped).
 * @param timeout Socket timeout for this operation.
 * @return Message.
 * @throws IOException If IO failed or read timed out.
 * @throws IgniteCheckedException If unmarshalling failed.
 */
protected <T> T readMessage(Socket sock, @Nullable InputStream in, long timeout) throws IOException, IgniteCheckedException {
    assert sock != null;
    int oldTimeout = sock.getSoTimeout();
    try {
        sock.setSoTimeout((int) timeout);
        T res = U.unmarshal(marshaller(), in == null ? sock.getInputStream() : in, U.resolveClassLoader(ignite.configuration()));
        return res;
    } catch (IOException | IgniteCheckedException e) {
        if (X.hasCause(e, SocketTimeoutException.class))
            LT.warn(log, "Timed out waiting for message to be read (most probably, the reason is " + "long GC pauses on remote node) [curTimeout=" + timeout + ", rmtAddr=" + sock.getRemoteSocketAddress() + ", rmtPort=" + sock.getPort() + ']');
        StreamCorruptedException streamCorruptedCause = X.cause(e, StreamCorruptedException.class);
        if (streamCorruptedCause != null) {
            // Lets check StreamCorruptedException for SSL Alert message
            // Sample SSL Alert message: 15:03:03:00:02:02:0a
            // 15 = Alert
            // 03:03 = SSL version
            // 00:02 = payload length
            // 02:0a = critical (02) / unexpected message (0a)
            // So, check message for "invalid stream header: 150X0X00"
            String msg = streamCorruptedCause.getMessage();
            if (msg != null && sslMsgPattern.matcher(msg).matches())
                streamCorruptedCause.initCause(new SSLException("Detected SSL alert in StreamCorruptedException"));
        }
        throw e;
    } finally {
        // Quietly restore timeout.
        try {
            sock.setSoTimeout(oldTimeout);
        } catch (SocketException ignored) {
        // No-op.
        }
    }
}
Also used : SocketException(java.net.SocketException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) SocketTimeoutException(java.net.SocketTimeoutException) IGNITE_CONSISTENT_ID_BY_HOST_WITHOUT_PORT(org.apache.ignite.IgniteSystemProperties.IGNITE_CONSISTENT_ID_BY_HOST_WITHOUT_PORT) LT(org.apache.ignite.internal.util.typedef.internal.LT) StreamCorruptedException(java.io.StreamCorruptedException) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException)

Example 25 with StreamCorruptedException

use of java.io.StreamCorruptedException in project Chronicle-Queue by OpenHFT.

the class SingleTableBuilder method build.

// *************************************************************************
// 
// *************************************************************************
@NotNull
public TableStore build() {
    if (readOnly && !file.exists()) {
        throw new IORuntimeException("File not found in readOnly mode");
    }
    try {
        MappedBytes bytes = MappedBytes.mappedBytes(file, 64 << 10, 0, readOnly);
        Wire wire = wireType.apply(bytes);
        StoreRecovery recovery = recoverySupplier.apply(wireType);
        try {
            TableStore tableStore;
            if ((!readOnly) && wire.writeFirstHeader()) {
                tableStore = writeTableStore(bytes, wire, recovery);
            } else {
                wire.readFirstHeader(timeoutMS, TimeUnit.MILLISECONDS);
                StringBuilder name = Wires.acquireStringBuilder();
                ValueIn valueIn = wire.readEventName(name);
                if (StringUtils.isEqual(name, MetaDataKeys.header.name())) {
                    tableStore = valueIn.typedMarshallable();
                } else {
                    // noinspection unchecked
                    throw new StreamCorruptedException("The first message should be the header, was " + name);
                }
            }
            return tableStore;
        } catch (TimeoutException e) {
            recovery.recoverAndWriteHeader(wire, 10_000, null, null);
            return writeTableStore(bytes, wire, recovery);
        }
    } catch (IOException e) {
        throw new IORuntimeException(e);
    }
}
Also used : ValueIn(net.openhft.chronicle.wire.ValueIn) IORuntimeException(net.openhft.chronicle.core.io.IORuntimeException) TimedStoreRecovery(net.openhft.chronicle.queue.impl.single.TimedStoreRecovery) StoreRecovery(net.openhft.chronicle.queue.impl.single.StoreRecovery) StreamCorruptedException(java.io.StreamCorruptedException) IOException(java.io.IOException) Wire(net.openhft.chronicle.wire.Wire) MappedBytes(net.openhft.chronicle.bytes.MappedBytes) TableStore(net.openhft.chronicle.queue.impl.TableStore) TimeoutException(java.util.concurrent.TimeoutException) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

StreamCorruptedException (java.io.StreamCorruptedException)26 IOException (java.io.IOException)18 ObjectInputStream (java.io.ObjectInputStream)15 ByteArrayInputStream (java.io.ByteArrayInputStream)11 OptionalDataException (java.io.OptionalDataException)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 InvalidClassException (java.io.InvalidClassException)5 ObjectOutputStream (java.io.ObjectOutputStream)5 NotSerializableException (java.io.NotSerializableException)4 Serializable (java.io.Serializable)4 SSLException (javax.net.ssl.SSLException)4 EOFException (java.io.EOFException)3 FileInputStream (java.io.FileInputStream)3 FileNotFoundException (java.io.FileNotFoundException)3 SocketTimeoutException (java.net.SocketTimeoutException)3 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)3 DataOutputStream (java.io.DataOutputStream)2 File (java.io.File)2 Socket (java.net.Socket)2 UUID (java.util.UUID)2