Search in sources :

Example 91 with ChannelHandler

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandler in project riposte by Nike-Inc.

the class RequestStateCleanerHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        // New request incoming - setup/clear *all* state objects for new requests
        for (ProcessingStateClassAndKeyPair<? extends ProcessingState> stateClassAndKeyPair : PROCESSING_STATE_ATTRIBUTE_KEYS) {
            // See if we have an existing state object for this channel for the given state type.
            @SuppressWarnings("unchecked") AttributeKey<ProcessingState> attrKey = (AttributeKey<ProcessingState>) stateClassAndKeyPair.getRight();
            Attribute<ProcessingState> processingStateAttr = ctx.channel().attr(attrKey);
            ProcessingState processingState = processingStateAttr.get();
            if (processingState == null) {
                // We don't already have one for this channel, so create one and register it.
                processingState = stateClassAndKeyPair.getLeft().newInstance();
                processingStateAttr.set(processingState);
            }
            // Clean the state for the new request.
            processingState.cleanStateForNewRequest();
        }
        HttpProcessingState httpProcessingState = ChannelAttributes.getHttpProcessingStateForChannel(ctx).get();
        // Set the DistributedTracingConfig on the HttpProcessingState.
        // noinspection deprecation - This is the only place that should actually be calling this method.
        httpProcessingState.setDistributedTracingConfig(distributedTracingConfig);
        // Send a request received event to the metricsListener.
        if (metricsListener != null) {
            metricsListener.onEvent(ServerMetricsEvent.REQUEST_RECEIVED, httpProcessingState);
        }
        // Remove the idle channel timeout handler (if there is one) so that it doesn't kill this new request if the
        // endpoint takes longer to complete than the idle timeout value - the idle channel timeout is only for
        // timing out channels that are idle *in-between* requests.
        ChannelPipeline pipeline = ctx.pipeline();
        ChannelHandler idleChannelTimeoutHandler = pipeline.get(HttpChannelInitializer.IDLE_CHANNEL_TIMEOUT_HANDLER_NAME);
        if (idleChannelTimeoutHandler != null)
            pipeline.remove(idleChannelTimeoutHandler);
        // last chunk when the timeout hits.
        if (incompleteHttpCallTimeoutMillis > 0 && !(msg instanceof LastHttpContent)) {
            IncompleteHttpCallTimeoutHandler newHandler = new IncompleteHttpCallTimeoutHandler(incompleteHttpCallTimeoutMillis);
            ChannelHandler existingHandler = pipeline.get(INCOMPLETE_HTTP_CALL_TIMEOUT_HANDLER_NAME);
            if (existingHandler == null) {
                pipeline.addFirst(INCOMPLETE_HTTP_CALL_TIMEOUT_HANDLER_NAME, newHandler);
            } else {
                logger.error("Handling HttpRequest for new request and found an IncompleteHttpCallTimeoutHandler " + "already in the pipeline. This should not be possible. A new " + "IncompleteHttpCallTimeoutHandler will replace the old one. worker_channel_id={}", ctx.channel().toString());
                pipeline.replace(existingHandler, INCOMPLETE_HTTP_CALL_TIMEOUT_HANDLER_NAME, newHandler);
            }
        }
        ProxyRouterProcessingState proxyRouterProcessingState = ChannelAttributes.getProxyRouterProcessingStateForChannel(ctx).get();
        // Set the DistributedTracingConfig on the ProxyRouterProcessingState.
        // noinspection deprecation - This is the only place that should actually be calling this method.
        proxyRouterProcessingState.setDistributedTracingConfig(distributedTracingConfig);
    } else if (msg instanceof LastHttpContent) {
        // The HTTP call is complete, so we can remove the IncompleteHttpCallTimeoutHandler.
        ChannelPipeline pipeline = ctx.pipeline();
        ChannelHandler existingHandler = pipeline.get(INCOMPLETE_HTTP_CALL_TIMEOUT_HANDLER_NAME);
        if (existingHandler != null)
            pipeline.remove(INCOMPLETE_HTTP_CALL_TIMEOUT_HANDLER_NAME);
    }
    // Continue on the pipeline processing.
    super.channelRead(ctx, msg);
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) ProxyRouterProcessingState(com.nike.riposte.server.http.ProxyRouterProcessingState) ChannelHandler(io.netty.channel.ChannelHandler) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ChannelPipeline(io.netty.channel.ChannelPipeline) AttributeKey(io.netty.util.AttributeKey) HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) ProcessingState(com.nike.riposte.server.http.ProcessingState) ProxyRouterProcessingState(com.nike.riposte.server.http.ProxyRouterProcessingState)

Example 92 with ChannelHandler

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandler in project riposte by Nike-Inc.

the class HttpChannelInitializerTest method initChannel_adds_ResponseSenderHandler_after_NonblockingEndpointExecutionHandler_and_uses_responseSender.

@Test
public void initChannel_adds_ResponseSenderHandler_after_NonblockingEndpointExecutionHandler_and_uses_responseSender() {
    // given
    HttpChannelInitializer hci = basicHttpChannelInitializerNoUtilityHandlers();
    ResponseSender expectedResponseSender = extractField(hci, "responseSender");
    // when
    hci.initChannel(socketChannelMock);
    // then
    ArgumentCaptor<ChannelHandler> channelHandlerArgumentCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
    verify(channelPipelineMock, atLeastOnce()).addLast(anyString(), channelHandlerArgumentCaptor.capture());
    List<ChannelHandler> handlers = channelHandlerArgumentCaptor.getAllValues();
    Pair<Integer, NonblockingEndpointExecutionHandler> nonblockingEndpointExecutionHandler = findChannelHandler(handlers, NonblockingEndpointExecutionHandler.class);
    Pair<Integer, ResponseSenderHandler> responseSenderHandler = findChannelHandler(handlers, ResponseSenderHandler.class);
    assertThat(nonblockingEndpointExecutionHandler, notNullValue());
    assertThat(responseSenderHandler, notNullValue());
    assertThat(responseSenderHandler.getLeft(), is(greaterThan(nonblockingEndpointExecutionHandler.getLeft())));
    // and then
    ResponseSender actualResponseSender = (ResponseSender) Whitebox.getInternalState(responseSenderHandler.getRight(), "responseSender");
    assertThat(actualResponseSender, is(expectedResponseSender));
}
Also used : ChannelHandler(io.netty.channel.ChannelHandler) NonblockingEndpointExecutionHandler(com.nike.riposte.server.handler.NonblockingEndpointExecutionHandler) ResponseSender(com.nike.riposte.server.http.ResponseSender) ResponseSenderHandler(com.nike.riposte.server.handler.ResponseSenderHandler) Test(org.junit.Test)

Example 93 with ChannelHandler

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandler in project riposte by Nike-Inc.

the class HttpChannelInitializerTest method initChannel_adds_before_and_after_RequestFilterHandler_appropriately_before_and_after_security_filter.

@Test
public void initChannel_adds_before_and_after_RequestFilterHandler_appropriately_before_and_after_security_filter() {
    // given
    RequestAndResponseFilter beforeSecurityRequestFilter = mock(RequestAndResponseFilter.class);
    doReturn(true).when(beforeSecurityRequestFilter).shouldExecuteBeforeSecurityValidation();
    RequestAndResponseFilter afterSecurityRequestFilter = mock(RequestAndResponseFilter.class);
    doReturn(false).when(afterSecurityRequestFilter).shouldExecuteBeforeSecurityValidation();
    List<RequestAndResponseFilter> requestAndResponseFilters = Arrays.asList(beforeSecurityRequestFilter, afterSecurityRequestFilter);
    HttpChannelInitializer hci = basicHttpChannelInitializer(null, 0, 42, false, null, requestAndResponseFilters);
    // when
    hci.initChannel(socketChannelMock);
    // then
    ArgumentCaptor<ChannelHandler> channelHandlerArgumentCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
    verify(channelPipelineMock, atLeastOnce()).addLast(anyString(), channelHandlerArgumentCaptor.capture());
    List<ChannelHandler> handlers = channelHandlerArgumentCaptor.getAllValues();
    Pair<Integer, AccessLogStartHandler> accessLogStartHandler = findChannelHandler(handlers, AccessLogStartHandler.class);
    Pair<Integer, RequestFilterHandler> beforeSecurityRequestFilterHandler = findChannelHandler(handlers, RequestFilterHandler.class);
    Pair<Integer, RequestFilterHandler> afterSecurityRequestFilterHandler = findChannelHandler(handlers, RequestFilterHandler.class, true);
    Pair<Integer, RoutingHandler> routingHandler = findChannelHandler(handlers, RoutingHandler.class);
    Pair<Integer, SecurityValidationHandler> securityValidationHandler = findChannelHandler(handlers, SecurityValidationHandler.class);
    Pair<Integer, RequestContentDeserializerHandler> requestContentDeserializerHandler = findChannelHandler(handlers, RequestContentDeserializerHandler.class);
    assertThat(accessLogStartHandler, notNullValue());
    assertThat(beforeSecurityRequestFilterHandler, notNullValue());
    assertThat(routingHandler, notNullValue());
    assertThat(afterSecurityRequestFilterHandler, notNullValue());
    assertThat(securityValidationHandler, notNullValue());
    assertThat(requestContentDeserializerHandler, notNullValue());
    Assertions.assertThat(beforeSecurityRequestFilterHandler.getLeft()).isGreaterThan(accessLogStartHandler.getLeft());
    Assertions.assertThat(beforeSecurityRequestFilterHandler.getLeft()).isLessThan(securityValidationHandler.getLeft());
    // beforeSecurityRequestFilterHandler must come before RoutingHandler as well (so that it is executed before any 404 gets thrown)
    Assertions.assertThat(beforeSecurityRequestFilterHandler.getLeft()).isLessThan(routingHandler.getLeft());
    Assertions.assertThat(afterSecurityRequestFilterHandler.getLeft()).isGreaterThan(securityValidationHandler.getLeft());
    Assertions.assertThat(afterSecurityRequestFilterHandler.getLeft()).isLessThan(requestContentDeserializerHandler.getLeft());
    // and then
    RequestFilterHandler beforeSecurityCachedHandler = extractField(hci, "beforeSecurityRequestFilterHandler");
    Assertions.assertThat(beforeSecurityRequestFilterHandler.getRight()).isSameAs(beforeSecurityCachedHandler);
    RequestFilterHandler afterSecurityCachedHandler = extractField(hci, "afterSecurityRequestFilterHandler");
    Assertions.assertThat(afterSecurityRequestFilterHandler.getRight()).isSameAs(afterSecurityCachedHandler);
}
Also used : AccessLogStartHandler(com.nike.riposte.server.handler.AccessLogStartHandler) RequestAndResponseFilter(com.nike.riposte.server.http.filter.RequestAndResponseFilter) RequestContentDeserializerHandler(com.nike.riposte.server.handler.RequestContentDeserializerHandler) ChannelHandler(io.netty.channel.ChannelHandler) RequestFilterHandler(com.nike.riposte.server.handler.RequestFilterHandler) RoutingHandler(com.nike.riposte.server.handler.RoutingHandler) SecurityValidationHandler(com.nike.riposte.server.handler.SecurityValidationHandler) Test(org.junit.Test)

Example 94 with ChannelHandler

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandler in project riposte by Nike-Inc.

the class HttpChannelInitializerTest method initChannel_adds_sslCtx_handler_first_if_available_and_no_utility_handlers.

@Test
public void initChannel_adds_sslCtx_handler_first_if_available_and_no_utility_handlers() throws SSLException {
    // given
    SslContext sslCtx = SslContextBuilder.forClient().build();
    HttpChannelInitializer hci = basicHttpChannelInitializer(sslCtx, 0, 100, false, mock(RequestValidator.class), createRequestAndResponseFilterMock());
    // when
    hci.initChannel(socketChannelMock);
    // then
    ArgumentCaptor<ChannelHandler> channelHandlerArgumentCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
    verify(channelPipelineMock, atLeastOnce()).addLast(anyString(), channelHandlerArgumentCaptor.capture());
    List<ChannelHandler> handlers = channelHandlerArgumentCaptor.getAllValues();
    assertThat(handlers.get(0), instanceOf(SslHandler.class));
}
Also used : RequestValidator(com.nike.riposte.server.error.validation.RequestValidator) ChannelHandler(io.netty.channel.ChannelHandler) SslHandler(io.netty.handler.ssl.SslHandler) SslContext(io.netty.handler.ssl.SslContext) Test(org.junit.Test)

Example 95 with ChannelHandler

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandler in project riposte by Nike-Inc.

the class HttpChannelInitializerTest method initChannel_adds_ResponseFilterHandler_after_ExceptionHandlingHandler_and_before_ResponseSenderHandler_and_uses_cached_handler.

@Test
public void initChannel_adds_ResponseFilterHandler_after_ExceptionHandlingHandler_and_before_ResponseSenderHandler_and_uses_cached_handler() {
    // given
    HttpChannelInitializer hci = basicHttpChannelInitializer(null, 0, 42, false, null, createRequestAndResponseFilterMock());
    // when
    hci.initChannel(socketChannelMock);
    // then
    ArgumentCaptor<ChannelHandler> channelHandlerArgumentCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
    verify(channelPipelineMock, atLeastOnce()).addLast(anyString(), channelHandlerArgumentCaptor.capture());
    List<ChannelHandler> handlers = channelHandlerArgumentCaptor.getAllValues();
    Pair<Integer, ExceptionHandlingHandler> exceptionHandler = findChannelHandler(handlers, ExceptionHandlingHandler.class);
    Pair<Integer, ResponseFilterHandler> responseFilterHandler = findChannelHandler(handlers, ResponseFilterHandler.class);
    Pair<Integer, ResponseSenderHandler> responseSenderHandler = findChannelHandler(handlers, ResponseSenderHandler.class);
    assertThat(exceptionHandler, notNullValue());
    assertThat(responseFilterHandler, notNullValue());
    assertThat(responseSenderHandler, notNullValue());
    Assertions.assertThat(responseFilterHandler.getLeft()).isGreaterThan(exceptionHandler.getLeft());
    Assertions.assertThat(responseFilterHandler.getLeft()).isLessThan(responseSenderHandler.getLeft());
    // and then
    ResponseFilterHandler cachedHandler = extractField(hci, "cachedResponseFilterHandler");
    Assertions.assertThat(responseFilterHandler.getRight()).isSameAs(cachedHandler);
}
Also used : ExceptionHandlingHandler(com.nike.riposte.server.handler.ExceptionHandlingHandler) ResponseFilterHandler(com.nike.riposte.server.handler.ResponseFilterHandler) ChannelHandler(io.netty.channel.ChannelHandler) ResponseSenderHandler(com.nike.riposte.server.handler.ResponseSenderHandler) Test(org.junit.Test)

Aggregations

ChannelHandler (io.netty.channel.ChannelHandler)216 Test (org.junit.Test)88 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)44 Channel (io.netty.channel.Channel)27 ChannelPipeline (io.netty.channel.ChannelPipeline)26 SslHandler (io.netty.handler.ssl.SslHandler)25 Test (org.junit.jupiter.api.Test)24 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)23 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)21 FilterChainMatchingHandler (io.grpc.xds.FilterChainMatchingProtocolNegotiators.FilterChainMatchingHandler)20 ChannelFuture (io.netty.channel.ChannelFuture)20 FilterChainSelector (io.grpc.xds.FilterChainMatchingProtocolNegotiators.FilterChainMatchingHandler.FilterChainSelector)19 ChannelHandlerAdapter (io.netty.channel.ChannelHandlerAdapter)18 InetSocketAddress (java.net.InetSocketAddress)18 DownstreamTlsContext (io.grpc.xds.EnvoyServerProtoData.DownstreamTlsContext)17 FilterChain (io.grpc.xds.EnvoyServerProtoData.FilterChain)17 LineBasedFrameDecoder (io.netty.handler.codec.LineBasedFrameDecoder)16 AtomicReference (java.util.concurrent.atomic.AtomicReference)16 TcpIngester (com.wavefront.ingester.TcpIngester)15 ByteBuf (io.netty.buffer.ByteBuf)13