Search in sources :

Example 6 with ThreadContext

use of org.elasticsearch.common.util.concurrent.ThreadContext in project elasticsearch by elastic.

the class RestControllerTests method testDispatchRequestLimitsBytes.

public void testDispatchRequestLimitsBytes() {
    int contentLength = BREAKER_LIMIT.bytesAsInt() + 1;
    String content = randomAsciiOfLength(contentLength);
    TestRestRequest request = new TestRestRequest("/", content, XContentType.JSON);
    AssertingChannel channel = new AssertingChannel(request, true, RestStatus.SERVICE_UNAVAILABLE);
    restController.dispatchRequest(request, channel, new ThreadContext(Settings.EMPTY));
    assertEquals(1, inFlightRequestsBreaker.getTrippedCount());
    assertEquals(0, inFlightRequestsBreaker.getUsed());
}
Also used : ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) Matchers.containsString(org.hamcrest.Matchers.containsString)

Example 7 with ThreadContext

use of org.elasticsearch.common.util.concurrent.ThreadContext in project elasticsearch by elastic.

the class RestControllerTests method testDispatchUnsupportedContentType.

public void testDispatchUnsupportedContentType() {
    FakeRestRequest fakeRestRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withContent(new BytesArray("{}"), null).withPath("/").withHeaders(Collections.singletonMap("Content-Type", Collections.singletonList("application/x-www-form-urlencoded"))).build();
    AssertingChannel channel = new AssertingChannel(fakeRestRequest, true, RestStatus.NOT_ACCEPTABLE);
    assertFalse(channel.getSendResponseCalled());
    restController.dispatchRequest(fakeRestRequest, channel, new ThreadContext(Settings.EMPTY));
    assertTrue(channel.getSendResponseCalled());
}
Also used : BytesArray(org.elasticsearch.common.bytes.BytesArray) ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) FakeRestRequest(org.elasticsearch.test.rest.FakeRestRequest)

Example 8 with ThreadContext

use of org.elasticsearch.common.util.concurrent.ThreadContext in project elasticsearch by elastic.

the class RestControllerTests method testRestHandlerWrapper.

public void testRestHandlerWrapper() throws Exception {
    AtomicBoolean handlerCalled = new AtomicBoolean(false);
    AtomicBoolean wrapperCalled = new AtomicBoolean(false);
    RestHandler handler = (RestRequest request, RestChannel channel, NodeClient client) -> {
        handlerCalled.set(true);
    };
    UnaryOperator<RestHandler> wrapper = h -> {
        assertSame(handler, h);
        return (RestRequest request, RestChannel channel, NodeClient client) -> wrapperCalled.set(true);
    };
    final RestController restController = new RestController(Settings.EMPTY, Collections.emptySet(), wrapper, null, circuitBreakerService);
    final ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
    restController.dispatchRequest(new FakeRestRequest.Builder(xContentRegistry()).build(), null, null, threadContext, handler);
    assertTrue(wrapperCalled.get());
    assertFalse(handlerCalled.get());
}
Also used : HttpServerTransport(org.elasticsearch.http.HttpServerTransport) Mockito.doCallRealMethod(org.mockito.Mockito.doCallRealMethod) Arrays(java.util.Arrays) DeprecationLogger(org.elasticsearch.common.logging.DeprecationLogger) XContentType(org.elasticsearch.common.xcontent.XContentType) ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) UnaryOperator(java.util.function.UnaryOperator) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) AtomicReference(java.util.concurrent.atomic.AtomicReference) BytesArray(org.elasticsearch.common.bytes.BytesArray) HashSet(java.util.HashSet) Settings(org.elasticsearch.common.settings.Settings) YamlXContent(org.elasticsearch.common.xcontent.yaml.YamlXContent) Matchers.eq(org.mockito.Matchers.eq) Map(java.util.Map) CircuitBreaker(org.elasticsearch.common.breaker.CircuitBreaker) NodeClient(org.elasticsearch.client.node.NodeClient) HttpTransportSettings(org.elasticsearch.http.HttpTransportSettings) ESTestCase(org.elasticsearch.test.ESTestCase) HttpStats(org.elasticsearch.http.HttpStats) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) Before(org.junit.Before) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) Set(java.util.Set) FakeRestRequest(org.elasticsearch.test.rest.FakeRestRequest) IOException(java.io.IOException) BytesReference(org.elasticsearch.common.bytes.BytesReference) AbstractLifecycleComponent(org.elasticsearch.common.component.AbstractLifecycleComponent) Mockito.verify(org.mockito.Mockito.verify) Matchers.any(org.mockito.Matchers.any) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) List(java.util.List) HierarchyCircuitBreakerService(org.elasticsearch.indices.breaker.HierarchyCircuitBreakerService) TransportAddress(org.elasticsearch.common.transport.TransportAddress) HttpInfo(org.elasticsearch.http.HttpInfo) Collections(java.util.Collections) Matchers.containsString(org.hamcrest.Matchers.containsString) Mockito.mock(org.mockito.Mockito.mock) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NodeClient(org.elasticsearch.client.node.NodeClient) FakeRestRequest(org.elasticsearch.test.rest.FakeRestRequest) ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext)

Example 9 with ThreadContext

use of org.elasticsearch.common.util.concurrent.ThreadContext in project elasticsearch by elastic.

the class Netty4HttpServerTransportTests method testBadRequest.

public void testBadRequest() throws InterruptedException {
    final AtomicReference<Throwable> causeReference = new AtomicReference<>();
    final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() {

        @Override
        public void dispatchRequest(final RestRequest request, final RestChannel channel, final ThreadContext threadContext) {
            throw new AssertionError();
        }

        @Override
        public void dispatchBadRequest(final RestRequest request, final RestChannel channel, final ThreadContext threadContext, final Throwable cause) {
            causeReference.set(cause);
            try {
                final ElasticsearchException e = new ElasticsearchException("you sent a bad request and you should feel bad");
                channel.sendResponse(new BytesRestResponse(channel, BAD_REQUEST, e));
            } catch (final IOException e) {
                throw new AssertionError(e);
            }
        }
    };
    final Settings settings;
    final int maxInitialLineLength;
    final Setting<ByteSizeValue> httpMaxInitialLineLengthSetting = HttpTransportSettings.SETTING_HTTP_MAX_INITIAL_LINE_LENGTH;
    if (randomBoolean()) {
        maxInitialLineLength = httpMaxInitialLineLengthSetting.getDefault(Settings.EMPTY).bytesAsInt();
        settings = Settings.EMPTY;
    } else {
        maxInitialLineLength = randomIntBetween(1, 8192);
        settings = Settings.builder().put(httpMaxInitialLineLengthSetting.getKey(), maxInitialLineLength + "b").build();
    }
    try (Netty4HttpServerTransport transport = new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, xContentRegistry(), dispatcher)) {
        transport.start();
        final TransportAddress remoteAddress = randomFrom(transport.boundAddress.boundAddresses());
        try (Netty4HttpClient client = new Netty4HttpClient()) {
            final String url = "/" + new String(new byte[maxInitialLineLength], Charset.forName("UTF-8"));
            final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, url);
            final FullHttpResponse response = client.post(remoteAddress.address(), request);
            assertThat(response.status(), equalTo(HttpResponseStatus.BAD_REQUEST));
            assertThat(new String(response.content().array(), Charset.forName("UTF-8")), containsString("you sent a bad request and you should feel bad"));
        }
    }
    assertNotNull(causeReference.get());
    assertThat(causeReference.get(), instanceOf(TooLongFrameException.class));
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) TransportAddress(org.elasticsearch.common.transport.TransportAddress) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) ElasticsearchException(org.elasticsearch.ElasticsearchException) Matchers.containsString(org.hamcrest.Matchers.containsString) Strings.collectionToDelimitedString(org.elasticsearch.common.Strings.collectionToDelimitedString) NullDispatcher(org.elasticsearch.http.NullDispatcher) HttpServerTransport(org.elasticsearch.http.HttpServerTransport) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Settings(org.elasticsearch.common.settings.Settings) HttpTransportSettings(org.elasticsearch.http.HttpTransportSettings) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) RestChannel(org.elasticsearch.rest.RestChannel) IOException(java.io.IOException) RestRequest(org.elasticsearch.rest.RestRequest)

Example 10 with ThreadContext

use of org.elasticsearch.common.util.concurrent.ThreadContext in project elasticsearch by elastic.

the class IndexShardOperationsLockTests method testThreadContextPreservedIfBlock.

/**
     * Tests that the ThreadContext is restored when a operation is executed after it has been delayed due to a block
     */
public void testThreadContextPreservedIfBlock() throws ExecutionException, InterruptedException, TimeoutException {
    final ThreadContext context = threadPool.getThreadContext();
    final Function<ActionListener<Releasable>, Boolean> contextChecker = (listener) -> {
        if ("bar".equals(context.getHeader("foo")) == false) {
            listener.onFailure(new IllegalStateException("context did not have value [bar] for header [foo]. Actual value [" + context.getHeader("foo") + "]"));
        } else if ("baz".equals(context.getTransient("bar")) == false) {
            listener.onFailure(new IllegalStateException("context did not have value [baz] for transient [bar]. Actual value [" + context.getTransient("bar") + "]"));
        } else {
            return true;
        }
        return false;
    };
    PlainActionFuture<Releasable> future = new PlainActionFuture<Releasable>() {

        @Override
        public void onResponse(Releasable releasable) {
            if (contextChecker.apply(this)) {
                super.onResponse(releasable);
            }
        }
    };
    PlainActionFuture<Releasable> future2 = new PlainActionFuture<Releasable>() {

        @Override
        public void onResponse(Releasable releasable) {
            if (contextChecker.apply(this)) {
                super.onResponse(releasable);
            }
        }
    };
    try (Releasable releasable = blockAndWait()) {
        // when the releasable is closed
        try (ThreadContext.StoredContext ignore = context.newStoredContext(false)) {
            context.putHeader("foo", "bar");
            context.putTransient("bar", "baz");
            // test both with and without a executor name
            block.acquire(future, ThreadPool.Names.GENERIC, true);
            block.acquire(future2, null, true);
        }
        assertFalse(future.isDone());
    }
    future.get(1, TimeUnit.HOURS).close();
    future2.get(1, TimeUnit.HOURS).close();
}
Also used : TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) AfterClass(org.junit.AfterClass) BeforeClass(org.junit.BeforeClass) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) TimeoutException(java.util.concurrent.TimeoutException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) After(org.junit.After) Matchers.equalTo(org.hamcrest.Matchers.equalTo) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ESTestCase(org.elasticsearch.test.ESTestCase) ActionListener(org.elasticsearch.action.ActionListener) Releasable(org.elasticsearch.common.lease.Releasable) Before(org.junit.Before) ActionListener(org.elasticsearch.action.ActionListener) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) Releasable(org.elasticsearch.common.lease.Releasable)

Aggregations

ThreadContext (org.elasticsearch.common.util.concurrent.ThreadContext)33 Matchers.containsString (org.hamcrest.Matchers.containsString)15 IOException (java.io.IOException)12 FakeRestRequest (org.elasticsearch.test.rest.FakeRestRequest)12 NodeClient (org.elasticsearch.client.node.NodeClient)8 BytesArray (org.elasticsearch.common.bytes.BytesArray)8 List (java.util.List)7 ActionListener (org.elasticsearch.action.ActionListener)4 Before (org.junit.Before)4 HashSet (java.util.HashSet)3 Map (java.util.Map)3 Settings (org.elasticsearch.common.settings.Settings)3 TransportAddress (org.elasticsearch.common.transport.TransportAddress)3 HttpServerTransport (org.elasticsearch.http.HttpServerTransport)3 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)2 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)2 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)2 HashMap (java.util.HashMap)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Strings.collectionToDelimitedString (org.elasticsearch.common.Strings.collectionToDelimitedString)2