Example usage for org.apache.thrift.transport TTransportException END_OF_FILE

List of usage examples for org.apache.thrift.transport TTransportException END_OF_FILE

Introduction

In this page you can find the example usage for org.apache.thrift.transport TTransportException END_OF_FILE.

Prototype

int END_OF_FILE

To view the source code for org.apache.thrift.transport TTransportException END_OF_FILE.

Click Source Link

Usage

From source file:alluxio.network.thrift.BootstrapServerTransport.java

License:Apache License

@Override
public void open() throws TTransportException {
    LOG.debug("opening server transport");
    if (!mBaseTransport.isOpen()) {
        mBaseTransport.open();/*  w  w  w  .  jav  a2 s.c  om*/
    }
    byte[] messageHeader = new byte[BOOTSTRAP_HEADER.length];
    int bytes;
    try {
        bytes = mBaseTransport.peek(messageHeader, 0, BOOTSTRAP_HEADER.length);
    } catch (TTransportException e) {
        if (e.getType() == TTransportException.END_OF_FILE) {
            LOG.debug("No data in the stream {}", mBaseTransport);
            mBaseTransport.close();
            throw new TTransportException("No data in the stream.");
        }
        throw e;
    }

    if (bytes == BOOTSTRAP_HEADER.length && Arrays.equals(messageHeader, BOOTSTRAP_HEADER)) {
        mBaseTransport.consumeBuffer(BOOTSTRAP_HEADER.length);
        mTransport = mBaseTransport;
    } else {
        mTransport = mTransportFactory.getTransport(mBaseTransport);
    }
    if (!mTransport.isOpen()) {
        mTransport.open();
    }
}

From source file:com.cloudera.recordservice.core.RecordServicePlannerClient.java

License:Apache License

/**
 * Opens a connection to the RecordServicePlanner.
 * Will retry maxAttempts if it got SERVICE_BUSY error.
 *//*from w  w  w.j a  va  2s . c  o  m*/
private void connect(String hostname, int port, int maxAttempts) throws IOException, RecordServiceException {
    for (int i = 0; i < maxAttempts; ++i) {
        if (i > 0) {
            LOG.info("Connect to RecordServicePlanner at {}:{} with attempt {}/{}", hostname, port, i + 1,
                    maxAttempts);
        }
        TTransport transport = ThriftUtils.createTransport("RecordServicePlanner", hostname, port,
                kerberosPrincipal_, delegationToken_, connectionTimeoutMs_);
        protocol_ = new TBinaryProtocol(transport);
        plannerClient_ = new RecordServicePlanner.Client(protocol_);
        try {
            protocolVersion_ = ThriftUtils.fromThrift(plannerClient_.GetProtocolVersion());
            LOG.debug("Connected to RecordServicePlanner with version: " + protocolVersion_);
            // Now that we've connected, set a larger timeout as RPCs that do work can take
            // much longer.
            ThriftUtils.getSocketTransport(transport).setTimeout(rpcTimeoutMs_);
            if (!protocolVersion_.isValidProtocolVersion()) {
                String errorMsg = "Current RecordServiceClient does not support server protocol version: "
                        + protocolVersion_.getVersion();
                LOG.warn(errorMsg);
                throw new RecordServiceException(errorMsg, new TRecordServiceException());
            }
            return;
        } catch (TRecordServiceException e) {
            // For 'GetProtocolVersion' call, the server side will first establish
            // the connection, and then throws the exception when it's processing the call.
            // The client is responsible to close the connection after seeing the exception.
            close();
            if (i + 1 < maxAttempts && e.code == TErrorCode.SERVICE_BUSY) {
                // Only retry when service is busy.
                LOG.warn("Failed to connect: ", e);
                sleepForRetry();
                continue;
            }
            LOG.warn("Connection is rejected because RecordServicePlanner has reached "
                    + "the maximum number of connections it is able to handle.");
            throw new RecordServiceException(
                    "Connection to RecordServicePlanner at " + hostname + ":" + port + " is rejected. ", e);
        } catch (TTransportException e) {
            String errorMsg = "Could not get service protocol version from " + "RecordServicePlanner at "
                    + hostname + ":" + port + ". ";
            LOG.warn(errorMsg + e);
            if (e.getType() == TTransportException.END_OF_FILE) {
                TRecordServiceException ex = new TRecordServiceException();
                ex.code = TErrorCode.AUTHENTICATION_ERROR;
                ex.message = "Connection to RecordServicePlanner at " + hostname + ":" + port
                        + " has failed. Please check if the client has the same security setting "
                        + "as the server.";
                throw new RecordServiceException(ex);
            }
            throw new IOException(errorMsg, e);
        } catch (TException e) {
            String errorMsg = "Could not get service protocol version. It's likely " + "the service at "
                    + hostname + ":" + port + " is not running the " + "RecordServicePlanner. ";
            LOG.warn(errorMsg + e);
            throw new IOException(errorMsg, e);
        }
    }
}

From source file:com.cloudera.recordservice.core.RecordServiceWorkerClient.java

License:Apache License

/**
 * Connects to the RecordServiceWorker running on hostname/port.
 * Will retry maxAttempts_ if it got SERVICE_BUSY error.
 *///from  ww  w  .ja  v a  2 s. c om
private void connect(String hostname, int port) throws IOException, RecordServiceException {
    if (workerClient_ != null) {
        throw new RuntimeException("Already connected. Must call close() first.");
    }

    for (int i = 0; i < maxAttempts_; ++i) {
        if (i > 0) {
            LOG.info("Connect to RecordServiceWorker at {}:{} with attempt {}/{}", hostname, port, i + 1,
                    maxAttempts_);
        }
        TTransport transport = ThriftUtils.createTransport("RecordServiceWorker", hostname, port,
                kerberosPrincipal_, delegationToken_, connectionTimeoutMs_);
        protocol_ = new TBinaryProtocol(transport);
        workerClient_ = new RecordServiceWorker.Client(protocol_);
        try {
            protocolVersion_ = ThriftUtils.fromThrift(workerClient_.GetProtocolVersion());
            LOG.debug("Connected to RecordServiceWorker with version: " + protocolVersion_);
            // Now that we've connected, set a larger timeout as RPCs that do work can take
            // much longer.
            ThriftUtils.getSocketTransport(transport).setTimeout(rpcTimeoutMs_);
            if (!protocolVersion_.isValidProtocolVersion()) {
                String errorMsg = "Current RecordServiceClient does not support server protocol version: "
                        + protocolVersion_.getVersion();
                LOG.warn(errorMsg);
                throw new RecordServiceException(errorMsg, new TRecordServiceException());
            }
            return;
        } catch (TRecordServiceException e) {
            // For 'GetProtocolVersion' call, the server side will first establish
            // the connection, and then throws the exception when it's processing the call.
            // The client is responsible to close the connection after seeing the exception.
            close();
            if (i + 1 < maxAttempts_ && e.getCode() == TErrorCode.SERVICE_BUSY) {
                // Only retry when service is busy.
                LOG.warn("Failed to connect: ", e);
                sleepForRetry();
                continue;
            }
            LOG.warn("Connection is rejected because RecordServiceWorker has reached the "
                    + "maximum number of connections it is able to handle.");
            throw new RecordServiceException(
                    "Connection to RecordServiceWorker at " + hostname + ":" + port + " is rejected. ", e);
        } catch (TTransportException e) {
            String errorMsg = "Could not get service protocol version from " + "RecordServiceWorker at "
                    + hostname + ":" + port + ". ";
            LOG.warn(errorMsg + e);
            if (e.getType() == TTransportException.END_OF_FILE) {
                TRecordServiceException ex = new TRecordServiceException();
                ex.code = TErrorCode.AUTHENTICATION_ERROR;
                ex.message = "Connection to RecordServiceWorker at " + hostname + ":" + port
                        + " has failed. Please check if the client has the same security setting "
                        + "as the server.";
                throw new RecordServiceException(ex);
            }
            throw new IOException(errorMsg, e);
        } catch (TException e) {
            String errorMsg = "Could not get service protocol version. It's likely " + "the service at "
                    + hostname + ":" + port + " is not running the " + "RecordServiceWorker. ";
            LOG.warn(errorMsg + e);
            throw new IOException(errorMsg, e);
        }
    }
}

From source file:com.cloudera.recordservice.core.ThriftUtils.java

License:Apache License

/**
 * Connects to a thrift service running at hostname/port, returning a TTransport
 * object to that service. If kerberosPrincipal is not null, the connection will
 * be kerberized. If delegationToken is not null, we will authenticate using
 * delegation tokens./*from  w w w  .  j  av  a  2s. c o  m*/
 */
static TTransport createTransport(String service, String hostname, int port, String kerberosPrincipal,
        DelegationToken token, int timeoutMs) throws IOException {
    if (kerberosPrincipal != null && token != null) {
        throw new IllegalArgumentException("Cannot specify both kerberos principal and delegation token.");
    }

    TTransport transport = new TSocket(hostname, port, timeoutMs);

    if (kerberosPrincipal != null) {
        // Replace _HOST to hostname in kerberosPrincipal
        kerberosPrincipal = kerberosPrincipal.replace("_HOST", hostname);
        LOG.info(String.format("Connecting to %s at %s:%d with kerberos principal: %s, with timeout: %sms",
                service, hostname, port, kerberosPrincipal, timeoutMs));

        // Kerberized, wrap the transport in a sasl transport.
        String[] names = kerberosPrincipal.split("[/@]");
        if (names.length != 3) {
            throw new IllegalArgumentException("Kerberos principal should have 3 parts: " + kerberosPrincipal);
        }
        System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
        Map<String, String> saslProps = new HashMap<String, String>();
        saslProps.put(Sasl.SERVER_AUTH, "true");
        transport = new TSaslClientTransport(KERBEROS_MECHANISM, null, names[0], names[1], saslProps, null,
                transport);
    } else if (token != null) {
        LOG.info(String.format("Connecting to %s at %s:%d using delegation token, with timeout: %sms", service,
                hostname, port, timeoutMs));

        // Delegation token, wrap the transport in a sasl transport.
        CallbackHandler callback = new DigestHandler(token);
        transport = new TSaslClientTransport(TOKEN_MECHANISM, null, "impala", "default",
                new HashMap<String, String>(), callback, transport);
    } else {
        LOG.info(String.format("Connecting to %s at %s:%d, with timeout: %sms", service, hostname, port,
                timeoutMs));
    }

    try {
        transport.open();
    } catch (TTransportException e) {
        String msg = String.format("Could not connect to %s: %s:%d", service, hostname, port);
        LOG.warn(String.format("%s: error: %s", msg, e));
        if (e.getType() == TTransportException.END_OF_FILE && (kerberosPrincipal != null || token != null)) {
            // If connecting from a secure connection to a non-secure server, the
            // connection will fail because the client is expecting the server
            // to participate in the handshake which it is not.
            // This is a heuristic (it might because of other reasons) but
            // likely helpful.
            msg += " Attempting to connect with a secure connection. "
                    + "Ensure the server has security enabled.";
        }
        throw new IOException(msg, e);
    }

    LOG.info(String.format("Connected to %s at %s:%d", service, hostname, port));
    return transport;
}

From source file:com.flaptor.indextank.storage.RecordIterator.java

License:Apache License

@Override
protected LogRecord computeNext() {
    if (end >= 0 && transport.getBytesRead() >= end) {
        if (transport != null) {
            totalRead = transport.getBytesRead();
            transport.close();//from   w ww  .  j  av a  2  s .  c om
        }
        return endOfData();
    }
    LogRecord record = new LogRecord();
    try {
        ((TBinaryProtocol) protocol).setReadLength(10000000);
        record.read(protocol);
        if (transport != null) {
            safelyRead = transport.getBytesRead();
        }
    } catch (TTransportException e) {
        switch (e.getType()) {
        case TTransportException.END_OF_FILE:
            if (transport != null) {
                totalRead = transport.getBytesRead();
                transport.close();
            }
            return endOfData();
        case TTransportException.UNKNOWN:
            if (e.getMessage().startsWith("Cannot read. Remote side has closed")) {
                if (transport != null) {
                    totalRead = transport.getBytesRead();
                    transport.close();
                }
                return endOfData();
            }
        default:
            transport.close();
            throw new RuntimeException("Failed while iterating: " + description, e);
        }
    } catch (TException e) {
        transport.close();
        throw new RuntimeException("Failed while iterating: " + description, e);
    }
    return record;
}

From source file:com.linecorp.armeria.common.thrift.text.TTextProtocol.java

License:Apache License

/**
 * Read in the root node if it has not yet been read.
 *///from   ww  w  . ja  v  a2s  .c  o m
private void readRoot() throws IOException {
    if (root != null) {
        return;
    }
    ByteArrayOutputStream content = new ByteArrayOutputStream();
    byte[] buffer = new byte[READ_BUFFER_SIZE];
    try {
        while (trans_.read(buffer, 0, READ_BUFFER_SIZE) > 0) {
            content.write(buffer);
        }
    } catch (TTransportException e) {
        if (TTransportException.END_OF_FILE != e.getType()) {
            throw new IOException(e);
        }
    }
    root = OBJECT_MAPPER.readTree(content.toByteArray());
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CassandraClientPoolingContainer.java

License:Open Source License

@SuppressWarnings("unchecked")
private <V, K extends Exception> V runWithGoodResource(FunctionCheckedException<Client, V, K> f) throws K {
    boolean shouldReuse = true;
    Client resource = null;/*from   w ww .  j av a2s .  co  m*/
    try {
        resource = clientPool.borrowObject();
        return f.apply(resource);
    } catch (Exception e) {
        if (e instanceof TTransportException || e instanceof TProtocolException
                || e instanceof NoSuchElementException) {
            log.warn("Not reusing resource {} due to {}", resource, e);
            shouldReuse = false;
        }
        if (e instanceof TTransportException
                && ((TTransportException) e).getType() == TTransportException.END_OF_FILE) {
            // If we have an end of file this is most likely due to this cassandra node being bounced.
            clientPool.clear();
        }
        throw (K) e;
    } finally {
        if (resource != null) {
            if (shouldReuse) {
                log.info("Returning {} to pool", resource);
                clientPool.returnObject(resource);
            } else {
                invalidateQuietly(resource);
            }
        }
    }
}

From source file:com.pinterest.quasar.thrift.TFiberSocket.java

License:Apache License

/**
 * Reads up to limit bytes from the underlying socket into the bytes buffer starting at offset.
 *
 * @param bytes must be at least offset + bytes in size.
 * @param offset the offset at which to start writing into bytes.
 * @param limit the maximum number of bytes to read into bytes.
 * @return the number of bytes actually read from the underlying socket.
 * @throws TTransportException if an error occurred while reading.
 *///  www .  ja  v a2s.  com
@Override
@Suspendable
public int read(byte[] bytes, int offset, int limit) throws TTransportException {
    ByteBuffer buf = ByteBuffer.wrap(bytes, offset, limit);

    int bytesRead;
    try {
        bytesRead = socketChannel.read(buf, timeout, timeoutUnit);
        if (bytesRead < 0) {
            throw new TTransportException(TTransportException.END_OF_FILE);
        }
        return bytesRead;
    } catch (IOException ioex) {
        throw new TTransportException(TTransportException.UNKNOWN, ioex);
    } catch (SuspendExecution ex) {
        throw new TTransportException(TTransportException.UNKNOWN, ex);
    }
}

From source file:com.pinterest.quasar.thrift.TFiberSocket.java

License:Apache License

@Override
@Suspendable//from   w  w w.j a va2s  .c o m
public void flush() throws TTransportException {
    if (curWriteBuffer < 2) {
        throw new RuntimeException("Attempted to flush with less than two buffers, make sure you "
                + "are using TFastFramedTransport or TFramedTransport");
    }

    curWriteBuffer = 0;

    try {
        while (writeBuffers[1].hasRemaining()) {
            long bytesWritten = socketChannel.write(writeBuffers);
            if (bytesWritten < 0) {
                throw new TTransportException(TTransportException.END_OF_FILE);
            }
        }
    } catch (IOException ioex) {
        throw new TTransportException(TTransportException.UNKNOWN, ioex);
    }
}

From source file:com.twitter.common.thrift.text.TTextProtocol.java

License:Apache License

/**
 * Set up the stream parser to read from the trans_ TTransport
 * buffer./*from   w w  w.  j  a  v  a 2s . c om*/
 */
private JsonStreamParser createParser() throws IOException {
    return new JsonStreamParser(new String(ByteStreams.toByteArray(new InputStream() {
        private int index;
        private int max;
        private final byte[] buffer = new byte[READ_BUFFER_SIZE];

        @Override
        public int read() throws IOException {
            if (max == -1) {
                return -1;
            }
            if (max > 0 && index < max) {
                return buffer[index++];
            }
            try {
                max = trans_.read(buffer, 0, READ_BUFFER_SIZE);
                index = 0;
            } catch (TTransportException e) {
                if (TTransportException.END_OF_FILE != e.getType()) {
                    throw new IOException(e);
                }
                max = -1;
            }
            return read();
        }
    }), Charsets.UTF_8));
}