Search in sources :

Example 6 with RestChannel

use of org.opensearch.rest.RestChannel in project OpenSearch by opensearch-project.

the class NioHttpServerTransportTests method testReadTimeout.

public void testReadTimeout() throws Exception {
    final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() {

        @Override
        public void dispatchRequest(final RestRequest request, final RestChannel channel, final ThreadContext threadContext) {
            logger.error("--> Unexpected successful request [{}]", FakeRestRequest.requestToString(request));
            throw new AssertionError("Should not have received a dispatched request");
        }

        @Override
        public void dispatchBadRequest(final RestChannel channel, final ThreadContext threadContext, final Throwable cause) {
            logger.error(new ParameterizedMessage("--> Unexpected bad request [{}]", FakeRestRequest.requestToString(channel.request())), cause);
            throw new AssertionError("Should not have received a dispatched request");
        }
    };
    Settings settings = createBuilderWithPort().put(HttpTransportSettings.SETTING_HTTP_READ_TIMEOUT.getKey(), new TimeValue(randomIntBetween(100, 300))).build();
    try (NioHttpServerTransport transport = new NioHttpServerTransport(settings, networkService, bigArrays, pageRecycler, threadPool, xContentRegistry(), dispatcher, new NioGroupFactory(settings, logger), new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS))) {
        transport.start();
        final TransportAddress remoteAddress = randomFrom(transport.boundAddress().boundAddresses());
        try (NioHttpClient client = new NioHttpClient()) {
            NioSocketChannel channel = null;
            try {
                CountDownLatch channelClosedLatch = new CountDownLatch(1);
                channel = client.connect(remoteAddress.address());
                channel.addCloseListener((r, t) -> channelClosedLatch.countDown());
                assertTrue("Channel should be closed due to read timeout", channelClosedLatch.await(1, TimeUnit.MINUTES));
            } finally {
                if (channel != null) {
                    channel.close();
                }
            }
        }
    }
}
Also used : ClusterSettings(org.opensearch.common.settings.ClusterSettings) TransportAddress(org.opensearch.common.transport.TransportAddress) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) RestChannel(org.opensearch.rest.RestChannel) HttpServerTransport(org.opensearch.http.HttpServerTransport) NullDispatcher(org.opensearch.http.NullDispatcher) CountDownLatch(java.util.concurrent.CountDownLatch) NioSocketChannel(org.opensearch.nio.NioSocketChannel) FakeRestRequest(org.opensearch.test.rest.FakeRestRequest) RestRequest(org.opensearch.rest.RestRequest) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) NioGroupFactory(org.opensearch.transport.nio.NioGroupFactory) Settings(org.opensearch.common.settings.Settings) HttpTransportSettings(org.opensearch.http.HttpTransportSettings) ClusterSettings(org.opensearch.common.settings.ClusterSettings) TimeValue(org.opensearch.common.unit.TimeValue)

Example 7 with RestChannel

use of org.opensearch.rest.RestChannel in project OpenSearch by opensearch-project.

the class ActionModuleTests method testPluginCanRegisterRestHandler.

public void testPluginCanRegisterRestHandler() {
    class FakeHandler implements RestHandler {

        @Override
        public List<Route> routes() {
            return singletonList(new Route(Method.GET, "/_dummy"));
        }

        @Override
        public void handleRequest(RestRequest request, RestChannel channel, NodeClient client) throws Exception {
        }
    }
    ActionPlugin registersFakeHandler = new ActionPlugin() {

        @Override
        public List<RestHandler> getRestHandlers(Settings settings, RestController restController, ClusterSettings clusterSettings, IndexScopedSettings indexScopedSettings, SettingsFilter settingsFilter, IndexNameExpressionResolver indexNameExpressionResolver, Supplier<DiscoveryNodes> nodesInCluster) {
            return singletonList(new FakeHandler());
        }
    };
    SettingsModule settings = new SettingsModule(Settings.EMPTY);
    ThreadPool threadPool = new TestThreadPool(getTestName());
    try {
        UsageService usageService = new UsageService();
        ActionModule actionModule = new ActionModule(settings.getSettings(), new IndexNameExpressionResolver(threadPool.getThreadContext()), settings.getIndexScopedSettings(), settings.getClusterSettings(), settings.getSettingsFilter(), threadPool, singletonList(registersFakeHandler), null, null, usageService, null);
        actionModule.initRestHandlers(null);
        // At this point the easiest way to confirm that a handler is loaded is to try to register another one on top of it and to fail
        Exception e = expectThrows(IllegalArgumentException.class, () -> actionModule.getRestController().registerHandler(new RestHandler() {

            @Override
            public void handleRequest(RestRequest request, RestChannel channel, NodeClient client) throws Exception {
            }

            @Override
            public List<Route> routes() {
                return singletonList(new Route(Method.GET, "/_dummy"));
            }
        }));
        assertThat(e.getMessage(), startsWith("Cannot replace existing handler for [/_dummy] for method: GET"));
    } finally {
        threadPool.shutdown();
    }
}
Also used : NodeClient(org.opensearch.client.node.NodeClient) ClusterSettings(org.opensearch.common.settings.ClusterSettings) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) ActionPlugin(org.opensearch.plugins.ActionPlugin) ThreadPool(org.opensearch.threadpool.ThreadPool) TestThreadPool(org.opensearch.threadpool.TestThreadPool) RestChannel(org.opensearch.rest.RestChannel) RestController(org.opensearch.rest.RestController) TestThreadPool(org.opensearch.threadpool.TestThreadPool) IOException(java.io.IOException) SettingsFilter(org.opensearch.common.settings.SettingsFilter) RestRequest(org.opensearch.rest.RestRequest) RestHandler(org.opensearch.rest.RestHandler) UsageService(org.opensearch.usage.UsageService) SettingsModule(org.opensearch.common.settings.SettingsModule) Supplier(java.util.function.Supplier) IndexNameExpressionResolver(org.opensearch.cluster.metadata.IndexNameExpressionResolver) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) ClusterSettings(org.opensearch.common.settings.ClusterSettings) Settings(org.opensearch.common.settings.Settings)

Example 8 with RestChannel

use of org.opensearch.rest.RestChannel in project OpenSearch by opensearch-project.

the class AbstractHttpServerTransportTests method testDispatchDoesNotModifyThreadContext.

public void testDispatchDoesNotModifyThreadContext() {
    final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() {

        @Override
        public void dispatchRequest(final RestRequest request, final RestChannel channel, final ThreadContext threadContext) {
            threadContext.putHeader("foo", "bar");
            threadContext.putTransient("bar", "baz");
        }

        @Override
        public void dispatchBadRequest(final RestChannel channel, final ThreadContext threadContext, final Throwable cause) {
            threadContext.putHeader("foo_bad", "bar");
            threadContext.putTransient("bar_bad", "baz");
        }
    };
    try (AbstractHttpServerTransport transport = new AbstractHttpServerTransport(Settings.EMPTY, networkService, bigArrays, threadPool, xContentRegistry(), dispatcher, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)) {

        @Override
        protected HttpServerChannel bind(InetSocketAddress hostAddress) {
            return null;
        }

        @Override
        protected void doStart() {
        }

        @Override
        protected void stopInternal() {
        }

        @Override
        public HttpStats stats() {
            return null;
        }
    }) {
        transport.dispatchRequest(null, null, null);
        assertNull(threadPool.getThreadContext().getHeader("foo"));
        assertNull(threadPool.getThreadContext().getTransient("bar"));
        transport.dispatchRequest(null, null, new Exception());
        assertNull(threadPool.getThreadContext().getHeader("foo_bad"));
        assertNull(threadPool.getThreadContext().getTransient("bar_bad"));
    }
}
Also used : FakeRestRequest(org.opensearch.test.rest.FakeRestRequest) RestRequest(org.opensearch.rest.RestRequest) ClusterSettings(org.opensearch.common.settings.ClusterSettings) InetSocketAddress(java.net.InetSocketAddress) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) RestChannel(org.opensearch.rest.RestChannel) UnknownHostException(java.net.UnknownHostException)

Example 9 with RestChannel

use of org.opensearch.rest.RestChannel in project OpenSearch by opensearch-project.

the class DefaultRestChannelTests method executeRequest.

private TestHttpResponse executeRequest(final Settings settings, final String originValue, final String host) {
    HttpRequest httpRequest = new TestHttpRequest(HttpRequest.HttpVersion.HTTP_1_1, RestRequest.Method.GET, "/");
    if (originValue != null) {
        httpRequest.getHeaders().put(CorsHandler.ORIGIN, Collections.singletonList(originValue));
    }
    httpRequest.getHeaders().put(CorsHandler.HOST, Collections.singletonList(host));
    final RestRequest request = RestRequest.request(xContentRegistry(), httpRequest, httpChannel);
    HttpHandlingSettings httpHandlingSettings = HttpHandlingSettings.fromSettings(settings);
    RestChannel channel = new DefaultRestChannel(httpChannel, httpRequest, request, bigArrays, httpHandlingSettings, threadPool.getThreadContext(), new CorsHandler(CorsHandler.buildConfig(settings)), null);
    channel.sendResponse(new TestRestResponse());
    // get the response
    ArgumentCaptor<TestHttpResponse> responseCaptor = ArgumentCaptor.forClass(TestHttpResponse.class);
    verify(httpChannel, atLeastOnce()).sendResponse(responseCaptor.capture(), any());
    return responseCaptor.getValue();
}
Also used : RestRequest(org.opensearch.rest.RestRequest) RestChannel(org.opensearch.rest.RestChannel)

Example 10 with RestChannel

use of org.opensearch.rest.RestChannel in project OpenSearch by opensearch-project.

the class Netty4HttpServerTransportTests method runExpectHeaderTest.

private void runExpectHeaderTest(final Settings settings, final String expectation, final int contentLength, final HttpResponseStatus expectedStatus) throws InterruptedException {
    final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() {

        @Override
        public void dispatchRequest(RestRequest request, RestChannel channel, ThreadContext threadContext) {
            channel.sendResponse(new BytesRestResponse(OK, BytesRestResponse.TEXT_CONTENT_TYPE, new BytesArray("done")));
        }

        @Override
        public void dispatchBadRequest(RestChannel channel, ThreadContext threadContext, Throwable cause) {
            logger.error(new ParameterizedMessage("--> Unexpected bad request [{}]", FakeRestRequest.requestToString(channel.request())), cause);
            throw new AssertionError();
        }
    };
    try (Netty4HttpServerTransport transport = new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, xContentRegistry(), dispatcher, clusterSettings, new SharedGroupFactory(settings))) {
        transport.start();
        final TransportAddress remoteAddress = randomFrom(transport.boundAddress().boundAddresses());
        try (Netty4HttpClient client = new Netty4HttpClient()) {
            final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
            request.headers().set(HttpHeaderNames.EXPECT, expectation);
            HttpUtil.setContentLength(request, contentLength);
            final FullHttpResponse response = client.send(remoteAddress.address(), request);
            try {
                assertThat(response.status(), equalTo(expectedStatus));
                if (expectedStatus.equals(HttpResponseStatus.CONTINUE)) {
                    final FullHttpRequest continuationRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", Unpooled.EMPTY_BUFFER);
                    final FullHttpResponse continuationResponse = client.send(remoteAddress.address(), continuationRequest);
                    try {
                        assertThat(continuationResponse.status(), is(HttpResponseStatus.OK));
                        assertThat(new String(ByteBufUtil.getBytes(continuationResponse.content()), StandardCharsets.UTF_8), is("done"));
                    } finally {
                        continuationResponse.release();
                    }
                }
            } finally {
                response.release();
            }
        }
    }
}
Also used : BytesArray(org.opensearch.common.bytes.BytesArray) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) TransportAddress(org.opensearch.common.transport.TransportAddress) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) RestChannel(org.opensearch.rest.RestChannel) SharedGroupFactory(org.opensearch.transport.SharedGroupFactory) Matchers.containsString(org.hamcrest.Matchers.containsString) HttpServerTransport(org.opensearch.http.HttpServerTransport) NullDispatcher(org.opensearch.http.NullDispatcher) FakeRestRequest(org.opensearch.test.rest.FakeRestRequest) RestRequest(org.opensearch.rest.RestRequest) BytesRestResponse(org.opensearch.rest.BytesRestResponse) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse)

Aggregations

RestChannel (org.opensearch.rest.RestChannel)17 RestRequest (org.opensearch.rest.RestRequest)17 ThreadContext (org.opensearch.common.util.concurrent.ThreadContext)15 ClusterSettings (org.opensearch.common.settings.ClusterSettings)12 FakeRestRequest (org.opensearch.test.rest.FakeRestRequest)12 TransportAddress (org.opensearch.common.transport.TransportAddress)11 HttpServerTransport (org.opensearch.http.HttpServerTransport)11 NullDispatcher (org.opensearch.http.NullDispatcher)10 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)9 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)8 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)8 Matchers.containsString (org.hamcrest.Matchers.containsString)8 Settings (org.opensearch.common.settings.Settings)8 HttpTransportSettings (org.opensearch.http.HttpTransportSettings)7 BytesRestResponse (org.opensearch.rest.BytesRestResponse)7 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)6 IOException (java.io.IOException)6 SharedGroupFactory (org.opensearch.transport.SharedGroupFactory)6 NioGroupFactory (org.opensearch.transport.nio.NioGroupFactory)5 OpenSearchException (org.opensearch.OpenSearchException)3