Search in sources :

Example 36 with FullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpResponse in project ambry by linkedin.

the class MockChannelHandlerContext method clientEarlyTerminationTest.

/**
 * Tests that client initiated terminations don't count towards {@link HttpResponseStatus#INTERNAL_SERVER_ERROR}.
 */
@Test
public void clientEarlyTerminationTest() throws Exception {
    EmbeddedChannel channel = createEmbeddedChannel();
    TestingUri uri = TestingUri.OnResponseCompleteWithEarlyClientTermination;
    HttpRequest httpRequest = RestTestUtils.createRequest(HttpMethod.POST, uri.toString(), null);
    HttpUtil.setKeepAlive(httpRequest, false);
    String iseMetricName = MetricRegistry.name(NettyResponseChannel.class, "InternalServerErrorCount");
    long iseBeforeCount = MockNettyMessageProcessor.METRIC_REGISTRY.getCounters().get(iseMetricName).getCount();
    String cetMetricName = MetricRegistry.name(NettyResponseChannel.class, "ClientEarlyTerminationCount");
    long cetBeforeCount = MockNettyMessageProcessor.METRIC_REGISTRY.getCounters().get(cetMetricName).getCount();
    channel.writeInbound(httpRequest);
    // first outbound has to be response.
    HttpResponse response = channel.readOutbound();
    assertEquals("Unexpected response status", HttpResponseStatus.INTERNAL_SERVER_ERROR, response.status());
    if (!(response instanceof FullHttpResponse)) {
        // empty the channel
        while (channel.readOutbound() != null) {
        }
    }
    assertEquals("Client terminations should not count towards InternalServerError count", iseBeforeCount, MockNettyMessageProcessor.METRIC_REGISTRY.getCounters().get(iseMetricName).getCount());
    assertEquals("Client terminations should have been tracked", cetBeforeCount + 1, MockNettyMessageProcessor.METRIC_REGISTRY.getCounters().get(cetMetricName).getCount());
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) HttpResponse(io.netty.handler.codec.http.HttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Test(org.junit.Test)

Example 37 with FullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpResponse in project ambry by linkedin.

the class NettyResponseChannel method getErrorResponse.

/**
 * Provided a cause, returns an error response with the right status and error message.
 * @param cause the cause of the error.
 * @return a {@link FullHttpResponse} with the error message that can be sent to the client.
 */
private FullHttpResponse getErrorResponse(Throwable cause) {
    HttpResponseStatus status;
    RestServiceErrorCode restServiceErrorCode = null;
    String errReason = null;
    Map<String, String> errHeaders = null;
    if (cause instanceof RestServiceException) {
        RestServiceException restServiceException = (RestServiceException) cause;
        restServiceErrorCode = restServiceException.getErrorCode();
        errorResponseStatus = ResponseStatus.getResponseStatus(restServiceErrorCode);
        status = getHttpResponseStatus(errorResponseStatus);
        if (shouldSendFailureReason(status, restServiceException)) {
            errReason = new String(Utils.getRootCause(cause).getMessage().replaceAll("[\n\t\r]", " ").getBytes(StandardCharsets.US_ASCII), StandardCharsets.US_ASCII);
        }
        if (restServiceException.shouldIncludeExceptionMetadataInResponse()) {
            errHeaders = restServiceException.getExceptionHeadersMap();
        }
    } else if (Utils.isPossibleClientTermination(cause)) {
        nettyMetrics.clientEarlyTerminationCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        errorResponseStatus = ResponseStatus.InternalServerError;
    } else {
        nettyMetrics.internalServerErrorCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        errorResponseStatus = ResponseStatus.InternalServerError;
    }
    logger.trace("Constructed error response for the client - [{} - {}]", status, errReason);
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
    response.headers().set(HttpHeaderNames.DATE, new GregorianCalendar().getTime());
    HttpUtil.setContentLength(response, 0);
    if (errReason != null) {
        response.headers().set(FAILURE_REASON_HEADER, errReason);
    }
    if (errHeaders != null) {
        errHeaders.forEach((errHeaderKey, errHeaderVal) -> response.headers().set(errHeaderKey, errHeaderVal));
    }
    if (restServiceErrorCode != null && HttpStatusClass.CLIENT_ERROR.contains(status.code())) {
        response.headers().set(ERROR_CODE_HEADER, restServiceErrorCode.name());
    }
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
    // if there is an ALLOW header in the response so far constructed, copy it
    if (responseMetadata.headers().contains(HttpHeaderNames.ALLOW)) {
        response.headers().set(HttpHeaderNames.ALLOW, responseMetadata.headers().get(HttpHeaderNames.ALLOW));
    } else if (errorResponseStatus == ResponseStatus.MethodNotAllowed) {
        logger.warn("Response is {} but there is no value for {}", ResponseStatus.MethodNotAllowed, HttpHeaderNames.ALLOW);
    }
    copyTrackingHeaders(responseMetadata, response);
    HttpUtil.setKeepAlive(response, shouldKeepAlive(status));
    return response;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) GregorianCalendar(java.util.GregorianCalendar) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse)

Example 38 with FullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpResponse in project ambry by linkedin.

the class NettyResponseChannel method maybeSendErrorResponse.

/**
 * Builds and sends an error response to the client based on {@code cause}.
 * @param exception the cause of the request handling failure.
 * @return {@code true} if error response was scheduled to be sent. {@code false} otherwise.
 */
private boolean maybeSendErrorResponse(Exception exception) {
    long processingStartTime = System.currentTimeMillis();
    boolean responseSent = false;
    logger.trace("Sending error response to client on channel {}", ctx.channel());
    FullHttpResponse errorResponse = getErrorResponse(exception);
    if (maybeWriteResponseMetadata(errorResponse, new ErrorResponseWriteListener())) {
        logger.trace("Scheduled error response sending on channel {}", ctx.channel());
        responseStatus = errorResponseStatus;
        responseSent = true;
        long processingTime = System.currentTimeMillis() - processingStartTime;
        nettyMetrics.errorResponseProcessingTimeInMs.update(processingTime);
    } else {
        logger.debug("Could not send error response on channel {}", ctx.channel());
    }
    return responseSent;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse)

Example 39 with FullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpResponse in project ambry by linkedin.

the class HealthCheckHandlerTest method testNonHealthCheckRequest.

/**
 * Does a test to see that a non health check request results in expected responses
 * @param httpMethod the {@link HttpMethod} for the request.
 * @param uri Uri to be used during the request
 * @throws IOException
 */
private void testNonHealthCheckRequest(HttpMethod httpMethod, String uri) throws IOException {
    EmbeddedChannel channel = createChannel();
    HttpRequest request = RestTestUtils.createRequest(httpMethod, uri, null);
    FullHttpResponse response = sendRequestAndGetResponse(channel, request);
    assertEquals("Unexpected response status", HttpResponseStatus.OK, response.status());
    assertEquals("Unexpected content", httpMethod.toString(), RestTestUtils.getContentString(response));
    channel.close();
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse)

Example 40 with FullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpResponse in project java by wavefrontHQ.

the class ChannelUtils method makeResponse.

/**
 * Create {@link FullHttpResponse} based on provided status and body contents.
 *
 * @param status   response status.
 * @param contents response body.
 * @return http response object
 */
public static HttpResponse makeResponse(final HttpResponseStatus status, final Object contents) {
    final FullHttpResponse response;
    if (contents instanceof JsonNode) {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(contents.toString(), CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    } else if (contents instanceof CharSequence) {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer((CharSequence) contents, CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);
    } else {
        throw new IllegalArgumentException("Unexpected response content type, JsonNode or " + "CharSequence expected: " + contents.getClass().getName());
    }
    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) JsonNode(com.fasterxml.jackson.databind.JsonNode)

Aggregations

FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)261 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)174 ByteBuf (io.netty.buffer.ByteBuf)53 Test (org.junit.Test)50 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)38 HttpRequest (io.netty.handler.codec.http.HttpRequest)34 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)24 HttpObject (io.netty.handler.codec.http.HttpObject)23 IOException (java.io.IOException)23 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)23 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)22 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)21 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)21 Test (org.junit.jupiter.api.Test)21 ChannelFuture (io.netty.channel.ChannelFuture)20 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)20 HttpResponse (io.netty.handler.codec.http.HttpResponse)20 HttpInitiator (org.jocean.http.client.HttpClient.HttpInitiator)20 Subscription (rx.Subscription)20 LocalAddress (io.netty.channel.local.LocalAddress)19