Search in sources :

Example 11 with ResponseInfo

use of com.nike.riposte.server.http.ResponseInfo in project riposte by Nike-Inc.

the class AccessLogEndHandler method doAccessLogging.

protected void doAccessLogging(ChannelHandlerContext ctx) throws Exception {
    if (accessLogger == null)
        return;
    HttpProcessingState httpProcessingState = ChannelAttributes.getHttpProcessingStateForChannel(ctx).get();
    if (httpProcessingState == null) {
        runnableWithTracingAndMdc(() -> logger.warn("HttpProcessingState is null. This shouldn't happen."), ctx).run();
    }
    //      logging for this request, so make sure we only do it if appropriate
    if (httpProcessingState != null && !httpProcessingState.isAccessLogCompletedOrScheduled()) {
        Instant startTime = httpProcessingState.getRequestStartTime();
        ResponseInfo responseInfo = httpProcessingState.getResponseInfo();
        HttpResponse actualResponseObject = httpProcessingState.getActualResponseObject();
        RequestInfo requestInfo = httpProcessingState.getRequestInfo();
        ChannelFutureListener doTheAccessLoggingOperation = new ChannelFutureListenerWithTracingAndMdc((channelFuture) -> accessLogger.log(requestInfo, actualResponseObject, responseInfo, Instant.now().minusMillis(startTime.toEpochMilli()).toEpochMilli()), ctx);
        //      conditions), otherwise do it when the response finishes.
        if (!httpProcessingState.isResponseSendingLastChunkSent())
            doTheAccessLoggingOperation.operationComplete(null);
        else
            httpProcessingState.getResponseWriterFinalChunkChannelFuture().addListener(doTheAccessLoggingOperation);
        httpProcessingState.setAccessLogCompletedOrScheduled(true);
    }
}
Also used : ResponseInfo(com.nike.riposte.server.http.ResponseInfo) HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) Instant(java.time.Instant) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelFutureListenerWithTracingAndMdc(com.nike.riposte.util.asynchelperwrapper.ChannelFutureListenerWithTracingAndMdc) RequestInfo(com.nike.riposte.server.http.RequestInfo) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 12 with ResponseInfo

use of com.nike.riposte.server.http.ResponseInfo in project riposte by Nike-Inc.

the class ChannelPipelineFinalizerHandler method finalizeChannelPipeline.

/**
     * This will first check the given state to see if a response was sent to the user. If not then this method will
     * send a generic error to the user so they get some response (so this method is kind of a backstop in case requests
     * somehow slip through our pipeline without being handled, which should never happen, but we have to have this just
     * in case). Then it will clean out the state so that it is ready for the next request.
     * <p/>
     * If the state indicates that a response was already sent then this method will only clean out the state for the
     * next request and will not send an error.
     */
protected void finalizeChannelPipeline(ChannelHandlerContext ctx, Object msg, HttpProcessingState state, Throwable cause) throws JsonProcessingException {
    RequestInfo<?> requestInfo = exceptionHandlingHandler.getRequestInfo(state, msg);
    //      is sent it will update the state.isResponseSent() so that further calls will return true.
    if (!state.isResponseSendingStarted()) {
        String errorMsg = "Discovered a request that snuck through without a response being sent. This should not " + "be possible and indicates a major problem in the channel pipeline.";
        logger.error(errorMsg, new Exception("Wrapper exception", cause));
        // Send a generic unhandled error response with a wrapper exception so that the logging info output by the
        //      exceptionHandlingHandler will have the overview of what went wrong.
        Exception exceptionToUse = new Exception(errorMsg, cause);
        ResponseInfo<ErrorResponseBody> responseInfo = exceptionHandlingHandler.processUnhandledError(state, msg, exceptionToUse);
        responseSender.sendErrorResponse(ctx, requestInfo, responseInfo);
    }
    ctx.flush();
    //      the metrics for this request, so make sure we only do it if appropriate.
    if (metricsListener != null && !state.isRequestMetricsRecordedOrScheduled()) {
        //      conditions), otherwise do it when the response finishes.
        if (!state.isResponseSendingLastChunkSent()) {
            // TODO: Somehow mark the state as a failed request and update the metrics listener to handle it
            metricsListener.onEvent(ServerMetricsEvent.RESPONSE_SENT, state);
        } else {
            // We need to use a copy of the state in case the original state gets cleaned.
            HttpProcessingState stateCopy = new HttpProcessingState(state);
            stateCopy.getResponseWriterFinalChunkChannelFuture().addListener((ChannelFutureListener) channelFuture -> {
                if (channelFuture.isSuccess())
                    metricsListener.onEvent(ServerMetricsEvent.RESPONSE_SENT, stateCopy);
                else {
                    metricsListener.onEvent(ServerMetricsEvent.RESPONSE_WRITE_FAILED, null);
                }
            });
        }
        state.setRequestMetricsRecordedOrScheduled(true);
    }
    // Make sure to clear out request info chunks, multipart data, and any other resources to prevent reference
    //      counting memory leaks (or any other kind of memory leaks).
    requestInfo.releaseAllResources();
    //      channel if it sits unused longer than the timeout value before the next request arrives.
    if (workerChannelIdleTimeoutMillis > 0 && ctx.pipeline().get(IDLE_CHANNEL_TIMEOUT_HANDLER_NAME) == null) {
        ctx.pipeline().addFirst(IDLE_CHANNEL_TIMEOUT_HANDLER_NAME, new IdleChannelTimeoutHandler(workerChannelIdleTimeoutMillis, "ServerWorkerChannel"));
    }
    //      request is broken. We can't do anything except kill the channel.
    if ((cause != null) && state.isResponseSendingStarted() && !state.isResponseSendingLastChunkSent()) {
        runnableWithTracingAndMdc(() -> logger.error("Received an error in ChannelPipelineFinalizerHandler after response sending was started, but " + "before it finished. Closing the channel. unexpected_error={}", cause.toString()), ctx).run();
        ctx.channel().close();
    }
}
Also used : HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) Span(com.nike.wingtips.Span) RequestInfo(com.nike.riposte.server.http.RequestInfo) LoggerFactory(org.slf4j.LoggerFactory) ChannelInboundHandler(io.netty.channel.ChannelInboundHandler) ResponseInfo(com.nike.riposte.server.http.ResponseInfo) Tracer(com.nike.wingtips.Tracer) PipelineContinuationBehavior(com.nike.riposte.server.handler.base.PipelineContinuationBehavior) ErrorResponseBody(com.nike.riposte.server.error.handler.ErrorResponseBody) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ChannelPromise(io.netty.channel.ChannelPromise) MetricsListener(com.nike.riposte.metrics.MetricsListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Logger(org.slf4j.Logger) ChannelOutboundHandler(io.netty.channel.ChannelOutboundHandler) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) BaseInboundHandlerWithTracingAndMdcSupport(com.nike.riposte.server.handler.base.BaseInboundHandlerWithTracingAndMdcSupport) IDLE_CHANNEL_TIMEOUT_HANDLER_NAME(com.nike.riposte.server.channelpipeline.HttpChannelInitializer.IDLE_CHANNEL_TIMEOUT_HANDLER_NAME) LastOutboundMessage(com.nike.riposte.server.channelpipeline.message.LastOutboundMessage) ChannelAttributes(com.nike.riposte.server.channelpipeline.ChannelAttributes) AsyncNettyHelper.runnableWithTracingAndMdc(com.nike.riposte.util.AsyncNettyHelper.runnableWithTracingAndMdc) ResponseSender(com.nike.riposte.server.http.ResponseSender) ProxyRouterProcessingState(com.nike.riposte.server.http.ProxyRouterProcessingState) ServerMetricsEvent(com.nike.riposte.server.metrics.ServerMetricsEvent) HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) ErrorResponseBody(com.nike.riposte.server.error.handler.ErrorResponseBody) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 13 with ResponseInfo

use of com.nike.riposte.server.http.ResponseInfo in project riposte by Nike-Inc.

the class SignalFxEndpointMetricsHandlerTest method MetricDimensionConfigurator_chainedWith_returns_ChainedMetricDimensionConfigurator_with_correct_args.

@Test
public void MetricDimensionConfigurator_chainedWith_returns_ChainedMetricDimensionConfigurator_with_correct_args() {
    // given
    MetricDimensionConfigurator orig = (rawBuilder, requestInfo, responseInfo, httpState, responseHttpStatusCode, responseHttpStatusCodeXXValue, elapsedTimeMillis, endpoint, endpointClass, method, matchingPathTemplate) -> null;
    MetricDimensionConfigurator chainMe = mock(MetricDimensionConfigurator.class);
    // when
    MetricDimensionConfigurator result = orig.chainedWith(chainMe);
    // then
    assertThat(result).isInstanceOf(ChainedMetricDimensionConfigurator.class);
    ChainedMetricDimensionConfigurator cmdc = (ChainedMetricDimensionConfigurator) result;
    assertThat(cmdc.firstConfigurator).isSameAs(orig);
    assertThat(cmdc.secondConfigurator).isSameAs(chainMe);
}
Also used : MetricDimensionConfigurator(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.MetricDimensionConfigurator) MetricMetadata(com.signalfx.codahale.reporter.MetricMetadata) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ResponseInfo(com.nike.riposte.server.http.ResponseInfo) ServerConfig(com.nike.riposte.server.config.ServerConfig) Reservoir(com.codahale.metrics.Reservoir) DataProviderRunner(com.tngtech.java.junit.dataprovider.DataProviderRunner) DEFAULT_URI_DIMENSION_KEY(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.DefaultMetricDimensionConfigurator.DEFAULT_URI_DIMENSION_KEY) SignalFxReporter(com.signalfx.codahale.reporter.SignalFxReporter) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Matchers.eq(org.mockito.Matchers.eq) Matchers.anyInt(org.mockito.Matchers.anyInt) Mockito.doReturn(org.mockito.Mockito.doReturn) Metric(com.codahale.metrics.Metric) UUID(java.util.UUID) Instant(java.time.Instant) DefaultMetricDimensionConfigurator(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.DefaultMetricDimensionConfigurator) Matchers.any(org.mockito.Matchers.any) SignalFxReporterFactory(com.nike.riposte.metrics.codahale.contrib.SignalFxReporterFactory) RollingWindowTimerBuilder(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.RollingWindowTimerBuilder) Endpoint(com.nike.riposte.server.http.Endpoint) Timer(com.codahale.metrics.Timer) Gauge(com.codahale.metrics.Gauge) Whitebox.getInternalState(org.mockito.internal.util.reflection.Whitebox.getInternalState) BuilderTagger(com.signalfx.codahale.reporter.MetricMetadata.BuilderTagger) SlidingTimeWindowReservoir(com.codahale.metrics.SlidingTimeWindowReservoir) Mockito.mock(org.mockito.Mockito.mock) HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) Histogram(com.codahale.metrics.Histogram) RequestInfo(com.nike.riposte.server.http.RequestInfo) MetricBuilder(com.signalfx.codahale.metrics.MetricBuilder) RunWith(org.junit.runner.RunWith) DataProvider(com.tngtech.java.junit.dataprovider.DataProvider) Matchers.anyString(org.mockito.Matchers.anyString) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) ChainedMetricDimensionConfigurator(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.ChainedMetricDimensionConfigurator) DEFAULT_METHOD_DIMENSION_KEY(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.DefaultMetricDimensionConfigurator.DEFAULT_METHOD_DIMENSION_KEY) Matchers.anyLong(org.mockito.Matchers.anyLong) Assertions.catchThrowable(org.assertj.core.api.Assertions.catchThrowable) DEFAULT_REQUEST_LATENCY_TIMER_DIMENSION_CONFIGURATOR(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.DEFAULT_REQUEST_LATENCY_TIMER_DIMENSION_CONFIGURATOR) Before(org.junit.Before) DEFAULT_ENDPOINT_CLASS_DIMENSION_KEY(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.DefaultMetricDimensionConfigurator.DEFAULT_ENDPOINT_CLASS_DIMENSION_KEY) DEFAULT_RESPONSE_CODE_DIMENSION_KEY(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.DefaultMetricDimensionConfigurator.DEFAULT_RESPONSE_CODE_DIMENSION_KEY) MetricRegistry(com.codahale.metrics.MetricRegistry) HttpMethod(io.netty.handler.codec.http.HttpMethod) Test(org.junit.Test) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) ChronoUnit(java.time.temporal.ChronoUnit) Pair(com.nike.internal.util.Pair) MetricDimensionConfigurator(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.MetricDimensionConfigurator) DefaultMetricDimensionConfigurator(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.DefaultMetricDimensionConfigurator) ChainedMetricDimensionConfigurator(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.ChainedMetricDimensionConfigurator) ChainedMetricDimensionConfigurator(com.nike.riposte.metrics.codahale.impl.SignalFxEndpointMetricsHandler.ChainedMetricDimensionConfigurator) Test(org.junit.Test)

Aggregations

ResponseInfo (com.nike.riposte.server.http.ResponseInfo)13 RequestInfo (com.nike.riposte.server.http.RequestInfo)9 Test (org.junit.Test)9 HttpProcessingState (com.nike.riposte.server.http.HttpProcessingState)7 LastOutboundMessageSendFullResponseInfo (com.nike.riposte.server.channelpipeline.message.LastOutboundMessageSendFullResponseInfo)5 PipelineContinuationBehavior (com.nike.riposte.server.handler.base.PipelineContinuationBehavior)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 ErrorResponseBody (com.nike.riposte.server.error.handler.ErrorResponseBody)4 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)4 Pair (com.nike.internal.util.Pair)3 ChannelAttributes (com.nike.riposte.server.channelpipeline.ChannelAttributes)3 IncompleteHttpCallTimeoutException (com.nike.riposte.server.error.exception.IncompleteHttpCallTimeoutException)3 TooManyOpenChannelsException (com.nike.riposte.server.error.exception.TooManyOpenChannelsException)3 ErrorResponseInfo (com.nike.riposte.server.error.handler.ErrorResponseInfo)3 FullResponseInfo (com.nike.riposte.server.http.impl.FullResponseInfo)3 DataProvider (com.tngtech.java.junit.dataprovider.DataProvider)3 ScheduledFuture (io.netty.util.concurrent.ScheduledFuture)3 TimeUnit (java.util.concurrent.TimeUnit)3 RiposteErrorHandler (com.nike.riposte.server.error.handler.RiposteErrorHandler)2 BaseInboundHandlerWithTracingAndMdcSupport (com.nike.riposte.server.handler.base.BaseInboundHandlerWithTracingAndMdcSupport)2