Search in sources :

Example 1 with ContentTooLongException

use of org.apache.http.ContentTooLongException in project elasticsearch by elastic.

the class RemoteScrollableHitSourceTests method testTooLargeResponse.

@SuppressWarnings({ "unchecked", "rawtypes" })
public void testTooLargeResponse() throws Exception {
    ContentTooLongException tooLong = new ContentTooLongException("too long!");
    CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class);
    when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class))).then(new Answer<Future<HttpResponse>>() {

        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
            HeapBufferedAsyncResponseConsumer consumer = (HeapBufferedAsyncResponseConsumer) invocationOnMock.getArguments()[1];
            FutureCallback callback = (FutureCallback) invocationOnMock.getArguments()[3];
            assertEquals(new ByteSizeValue(100, ByteSizeUnit.MB).bytesAsInt(), consumer.getBufferLimit());
            callback.failed(tooLong);
            return null;
        }
    });
    RemoteScrollableHitSource source = sourceWithMockedClient(true, httpClient);
    AtomicBoolean called = new AtomicBoolean();
    Consumer<Response> checkResponse = r -> called.set(true);
    Throwable e = expectThrows(RuntimeException.class, () -> source.doStartNextScroll(FAKE_SCROLL_ID, timeValueMillis(0), checkResponse));
    // Unwrap the some artifacts from the test
    while (e.getMessage().equals("failed")) {
        e = e.getCause();
    }
    // This next exception is what the user sees
    assertEquals("Remote responded with a chunk that was too large. Use a smaller batch size.", e.getMessage());
    // And that exception is reported as being caused by the underlying exception returned by the client
    assertSame(tooLong, e.getCause());
    assertFalse(called.get());
}
Also used : Response(org.elasticsearch.action.bulk.byscroll.ScrollableHitSource.Response) ByteSizeUnit(org.elasticsearch.common.unit.ByteSizeUnit) ScheduledFuture(java.util.concurrent.ScheduledFuture) URL(java.net.URL) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) StatusLine(org.apache.http.StatusLine) HeapBufferedAsyncResponseConsumer(org.elasticsearch.client.HeapBufferedAsyncResponseConsumer) Future(java.util.concurrent.Future) After(org.junit.After) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) Streams(org.elasticsearch.common.io.Streams) ThreadPool(org.elasticsearch.threadpool.ThreadPool) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) StandardCharsets(java.nio.charset.StandardCharsets) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) Matchers.any(org.mockito.Matchers.any) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) Version(org.elasticsearch.Version) RestStatus(org.elasticsearch.rest.RestStatus) TimeValue.timeValueMinutes(org.elasticsearch.common.unit.TimeValue.timeValueMinutes) Matchers.containsString(org.hamcrest.Matchers.containsString) Mockito.mock(org.mockito.Mockito.mock) RestClient(org.elasticsearch.client.RestClient) ContentTooLongException(org.apache.http.ContentTooLongException) ParsingException(org.elasticsearch.common.ParsingException) BasicStatusLine(org.apache.http.message.BasicStatusLine) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SearchRequest(org.elasticsearch.action.search.SearchRequest) BackoffPolicy(org.elasticsearch.action.bulk.BackoffPolicy) BytesArray(org.elasticsearch.common.bytes.BytesArray) HttpAsyncResponseConsumer(org.apache.http.nio.protocol.HttpAsyncResponseConsumer) Answer(org.mockito.stubbing.Answer) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) InvocationOnMock(org.mockito.invocation.InvocationOnMock) TimeValue(org.elasticsearch.common.unit.TimeValue) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) TimeValue.timeValueMillis(org.elasticsearch.common.unit.TimeValue.timeValueMillis) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ESTestCase(org.elasticsearch.test.ESTestCase) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) FileSystemUtils(org.elasticsearch.common.io.FileSystemUtils) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) Matchers.empty(org.hamcrest.Matchers.empty) EsExecutors(org.elasticsearch.common.util.concurrent.EsExecutors) FutureCallback(org.apache.http.concurrent.FutureCallback) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) InputStreamReader(java.io.InputStreamReader) Consumer(java.util.function.Consumer) ProtocolVersion(org.apache.http.ProtocolVersion) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException) HttpResponse(org.apache.http.HttpResponse) InputStreamEntity(org.apache.http.entity.InputStreamEntity) HttpHost(org.apache.http.HttpHost) ContentTooLongException(org.apache.http.ContentTooLongException) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) HttpAsyncResponseConsumer(org.apache.http.nio.protocol.HttpAsyncResponseConsumer) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HeapBufferedAsyncResponseConsumer(org.elasticsearch.client.HeapBufferedAsyncResponseConsumer) Response(org.elasticsearch.action.bulk.byscroll.ScrollableHitSource.Response) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) ScheduledFuture(java.util.concurrent.ScheduledFuture) Future(java.util.concurrent.Future) FutureCallback(org.apache.http.concurrent.FutureCallback)

Example 2 with ContentTooLongException

use of org.apache.http.ContentTooLongException in project elasticsearch by elastic.

the class RemoteScrollableHitSource method execute.

private <T> void execute(String method, String uri, Map<String, String> params, HttpEntity entity, BiFunction<XContentParser, XContentType, T> parser, Consumer<? super T> listener) {
    // Preserve the thread context so headers survive after the call
    java.util.function.Supplier<ThreadContext.StoredContext> contextSupplier = threadPool.getThreadContext().newRestorableContext(true);
    class RetryHelper extends AbstractRunnable {

        private final Iterator<TimeValue> retries = backoffPolicy.iterator();

        @Override
        protected void doRun() throws Exception {
            client.performRequestAsync(method, uri, params, entity, new ResponseListener() {

                @Override
                public void onSuccess(org.elasticsearch.client.Response response) {
                    // Restore the thread context to get the precious headers
                    try (ThreadContext.StoredContext ctx = contextSupplier.get()) {
                        // eliminates compiler warning
                        assert ctx != null;
                        T parsedResponse;
                        try {
                            HttpEntity responseEntity = response.getEntity();
                            InputStream content = responseEntity.getContent();
                            XContentType xContentType = null;
                            if (responseEntity.getContentType() != null) {
                                final String mimeType = ContentType.parse(responseEntity.getContentType().getValue()).getMimeType();
                                xContentType = XContentType.fromMediaType(mimeType);
                            }
                            if (xContentType == null) {
                                try {
                                    throw new ElasticsearchException("Response didn't include Content-Type: " + bodyMessage(response.getEntity()));
                                } catch (IOException e) {
                                    ElasticsearchException ee = new ElasticsearchException("Error extracting body from response");
                                    ee.addSuppressed(e);
                                    throw ee;
                                }
                            }
                            // EMPTY is safe here because we don't call namedObject
                            try (XContentParser xContentParser = xContentType.xContent().createParser(NamedXContentRegistry.EMPTY, content)) {
                                parsedResponse = parser.apply(xContentParser, xContentType);
                            } catch (ParsingException e) {
                                /* Because we're streaming the response we can't get a copy of it here. The best we can do is hint that it
                                 * is totally wrong and we're probably not talking to Elasticsearch. */
                                throw new ElasticsearchException("Error parsing the response, remote is likely not an Elasticsearch instance", e);
                            }
                        } catch (IOException e) {
                            throw new ElasticsearchException("Error deserializing response, remote is likely not an Elasticsearch instance", e);
                        }
                        listener.accept(parsedResponse);
                    }
                }

                @Override
                public void onFailure(Exception e) {
                    try (ThreadContext.StoredContext ctx = contextSupplier.get()) {
                        // eliminates compiler warning
                        assert ctx != null;
                        if (e instanceof ResponseException) {
                            ResponseException re = (ResponseException) e;
                            if (RestStatus.TOO_MANY_REQUESTS.getStatus() == re.getResponse().getStatusLine().getStatusCode()) {
                                if (retries.hasNext()) {
                                    TimeValue delay = retries.next();
                                    logger.trace((Supplier<?>) () -> new ParameterizedMessage("retrying rejected search after [{}]", delay), e);
                                    countSearchRetry.run();
                                    threadPool.schedule(delay, ThreadPool.Names.SAME, RetryHelper.this);
                                    return;
                                }
                            }
                            e = wrapExceptionToPreserveStatus(re.getResponse().getStatusLine().getStatusCode(), re.getResponse().getEntity(), re);
                        } else if (e instanceof ContentTooLongException) {
                            e = new IllegalArgumentException("Remote responded with a chunk that was too large. Use a smaller batch size.", e);
                        }
                        fail.accept(e);
                    }
                }
            });
        }

        @Override
        public void onFailure(Exception t) {
            fail.accept(t);
        }
    }
    new RetryHelper().run();
}
Also used : AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) HttpEntity(org.apache.http.HttpEntity) ResponseException(org.elasticsearch.client.ResponseException) ElasticsearchException(org.elasticsearch.ElasticsearchException) XContentType(org.elasticsearch.common.xcontent.XContentType) ParsingException(org.elasticsearch.common.ParsingException) Iterator(java.util.Iterator) Supplier(org.apache.logging.log4j.util.Supplier) TimeValue(org.elasticsearch.common.unit.TimeValue) InputStream(java.io.InputStream) ContentTooLongException(org.apache.http.ContentTooLongException) ResponseListener(org.elasticsearch.client.ResponseListener) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) ResponseException(org.elasticsearch.client.ResponseException) ContentTooLongException(org.apache.http.ContentTooLongException) ParsingException(org.elasticsearch.common.ParsingException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) IOException(java.io.IOException) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 3 with ContentTooLongException

use of org.apache.http.ContentTooLongException in project elasticsearch by elastic.

the class HeapBufferedAsyncResponseConsumer method onEntityEnclosed.

@Override
protected void onEntityEnclosed(HttpEntity entity, ContentType contentType) throws IOException {
    long len = entity.getContentLength();
    if (len > bufferLimitBytes) {
        throw new ContentTooLongException("entity content is too long [" + len + "] for the configured buffer limit [" + bufferLimitBytes + "]");
    }
    if (len < 0) {
        len = 4096;
    }
    this.buf = new SimpleInputBuffer((int) len, getByteBufferAllocator());
    this.response.setEntity(new ContentBufferEntity(entity, this.buf));
}
Also used : SimpleInputBuffer(org.apache.http.nio.util.SimpleInputBuffer) ContentTooLongException(org.apache.http.ContentTooLongException) ContentBufferEntity(org.apache.http.nio.entity.ContentBufferEntity)

Example 4 with ContentTooLongException

use of org.apache.http.ContentTooLongException in project fc-java-sdk by aliyun.

the class AbstractResponseConsumer method onEntityEnclosed.

protected void onEntityEnclosed(HttpEntity entity, ContentType contentType) throws IOException {
    long len = entity.getContentLength();
    if (len > 2147483647L) {
        throw new ContentTooLongException("Entity content is too long: " + len);
    } else {
        if (len < 0L) {
            len = 4096L;
        }
        this.buf = new SimpleInputBuffer((int) len, new HeapByteBufferAllocator());
        this.httpResponse.setEntity(new ContentBufferEntity(entity, this.buf));
    }
}
Also used : SimpleInputBuffer(org.apache.http.nio.util.SimpleInputBuffer) HeapByteBufferAllocator(org.apache.http.nio.util.HeapByteBufferAllocator) ContentTooLongException(org.apache.http.ContentTooLongException) ContentBufferEntity(org.apache.http.nio.entity.ContentBufferEntity)

Example 5 with ContentTooLongException

use of org.apache.http.ContentTooLongException in project elasticsearch by elastic.

the class HeapBufferedAsyncResponseConsumerTests method bufferLimitTest.

private static void bufferLimitTest(HeapBufferedAsyncResponseConsumer consumer, int bufferLimit) throws Exception {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK");
    consumer.onResponseReceived(new BasicHttpResponse(statusLine));
    final AtomicReference<Long> contentLength = new AtomicReference<>();
    HttpEntity entity = new StringEntity("", ContentType.APPLICATION_JSON) {

        @Override
        public long getContentLength() {
            return contentLength.get();
        }
    };
    contentLength.set(randomLong(bufferLimit));
    consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON);
    contentLength.set(randomLongBetween(bufferLimit + 1, MAX_TEST_BUFFER_SIZE));
    try {
        consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON);
    } catch (ContentTooLongException e) {
        assertEquals("entity content is too long [" + entity.getContentLength() + "] for the configured buffer limit [" + bufferLimit + "]", e.getMessage());
    }
}
Also used : BasicStatusLine(org.apache.http.message.BasicStatusLine) StatusLine(org.apache.http.StatusLine) StringEntity(org.apache.http.entity.StringEntity) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpEntity(org.apache.http.HttpEntity) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) ContentTooLongException(org.apache.http.ContentTooLongException) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProtocolVersion(org.apache.http.ProtocolVersion) BasicStatusLine(org.apache.http.message.BasicStatusLine)

Aggregations

ContentTooLongException (org.apache.http.ContentTooLongException)5 HttpEntity (org.apache.http.HttpEntity)3 IOException (java.io.IOException)2 ProtocolVersion (org.apache.http.ProtocolVersion)2 StatusLine (org.apache.http.StatusLine)2 StringEntity (org.apache.http.entity.StringEntity)2 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)2 BasicStatusLine (org.apache.http.message.BasicStatusLine)2 ContentBufferEntity (org.apache.http.nio.entity.ContentBufferEntity)2 SimpleInputBuffer (org.apache.http.nio.util.SimpleInputBuffer)2 ElasticsearchStatusException (org.elasticsearch.ElasticsearchStatusException)2 ParsingException (org.elasticsearch.common.ParsingException)2 TimeValue (org.elasticsearch.common.unit.TimeValue)2 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 URL (java.net.URL)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Iterator (java.util.Iterator)1 ExecutorService (java.util.concurrent.ExecutorService)1 Future (java.util.concurrent.Future)1