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());
}
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;
}
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;
}
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();
}
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;
}
Aggregations