OpenSearch/server/src/main/java/org/elasticsearch/rest/BytesRestResponse.java

187 lines
7.1 KiB
Java
Raw Normal View History

2010-02-08 15:30:06 +02:00
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
2010-02-08 15:30:06 +02:00
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest;
2010-02-08 15:30:06 +02:00
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.Supplier;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import static java.util.Collections.singletonMap;
import static org.elasticsearch.ElasticsearchException.REST_EXCEPTION_SKIP_STACK_TRACE;
import static org.elasticsearch.ElasticsearchException.REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT;
import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken;
public class BytesRestResponse extends RestResponse {
public static final String TEXT_CONTENT_TYPE = "text/plain; charset=UTF-8";
private static final String STATUS = "status";
private final RestStatus status;
private final BytesReference content;
private final String contentType;
/**
* Creates a new response based on {@link XContentBuilder}.
*/
public BytesRestResponse(RestStatus status, XContentBuilder builder) {
this(status, builder.contentType().mediaType(), BytesReference.bytes(builder));
}
/**
* Creates a new plain text response.
*/
public BytesRestResponse(RestStatus status, String content) {
this(status, TEXT_CONTENT_TYPE, new BytesArray(content));
}
/**
* Creates a new plain text response.
*/
public BytesRestResponse(RestStatus status, String contentType, String content) {
this(status, contentType, new BytesArray(content));
}
/**
* Creates a binary response.
*/
public BytesRestResponse(RestStatus status, String contentType, byte[] content) {
this(status, contentType, new BytesArray(content));
}
/**
* Creates a binary response.
*/
public BytesRestResponse(RestStatus status, String contentType, BytesReference content) {
this.status = status;
this.content = content;
this.contentType = contentType;
}
public BytesRestResponse(RestChannel channel, Exception e) throws IOException {
this(channel, ExceptionsHelper.status(e), e);
}
public BytesRestResponse(RestChannel channel, RestStatus status, Exception e) throws IOException {
this.status = status;
try (XContentBuilder builder = build(channel, status, e)) {
this.content = BytesReference.bytes(builder);
this.contentType = builder.contentType().mediaType();
}
if (e instanceof ElasticsearchException) {
copyHeaders(((ElasticsearchException) e));
}
}
2011-12-06 02:42:25 +02:00
@Override
public String contentType() {
return this.contentType;
}
2010-02-08 15:30:06 +02:00
@Override
public BytesReference content() {
return this.content;
}
2011-12-06 02:42:25 +02:00
@Override
public RestStatus status() {
return this.status;
}
private static final Logger SUPPRESSED_ERROR_LOGGER = LogManager.getLogger("rest.suppressed");
private static XContentBuilder build(RestChannel channel, RestStatus status, Exception e) throws IOException {
ToXContent.Params params = channel.request();
if (params.paramAsBoolean("error_trace", !REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT)) {
params = new ToXContent.DelegatingMapParams(singletonMap(REST_EXCEPTION_SKIP_STACK_TRACE, "false"), params);
} else if (e != null) {
Supplier<?> messageSupplier = () -> new ParameterizedMessage("path: {}, params: {}",
channel.request().rawPath(), channel.request().params());
if (status.getStatus() < 500) {
SUPPRESSED_ERROR_LOGGER.debug(messageSupplier, e);
} else {
SUPPRESSED_ERROR_LOGGER.warn(messageSupplier, e);
}
}
XContentBuilder builder = channel.newErrorBuilder().startObject();
ElasticsearchException.generateFailureXContent(builder, params, e, channel.detailedErrorsEnabled());
builder.field(STATUS, status.getStatus());
builder.endObject();
return builder;
}
Closing a ReleasableBytesStreamOutput closes the underlying BigArray (#23941) This commit makes closing a ReleasableBytesStreamOutput release the underlying BigArray so that we can use try-with-resources with these streams and avoid leaking memory by not returning the BigArray. As part of this change, the ReleasableBytesStreamOutput adds protection to only release the BigArray once. In order to make some of the changes cleaner, the ReleasableBytesStream interface has been removed. The BytesStream interface is changed to a abstract class so that we can use it as a useable return type for a new method, Streams#flushOnCloseStream. This new method wraps a given stream and overrides the close method so that the stream is simply flushed and not closed. This behavior is used in the TcpTransport when compression is used with a ReleasableBytesStreamOutput as we need to close the compressed stream to ensure all of the data is written from this stream. Closing the compressed stream will try to close the underlying stream but we only want to flush so that all of the written bytes are available. Additionally, an error message method added in the BytesRestResponse did not use a builder provided by the channel and instead created its own JSON builder. This changes that method to use the channel builder and in turn the bytes stream output that is managed by the channel. Note, this commit differs from 6bfecdf921a1941b48273d76551872df4062cfae in that it updates ReleasableBytesStreamOutput to handle the case of the BigArray decreasing in size, which changes the reference to the BigArray. When the reference is changed, the releasable needs to be updated otherwise there could be a leak of bytes and corruption of data in unrelated streams. This reverts commit afd45c14327cd0f8d155e5ac9740f48e8e39b09c, which reverted #23572.
2017-04-14 10:50:31 -04:00
static BytesRestResponse createSimpleErrorResponse(RestChannel channel, RestStatus status, String errorMessage) throws IOException {
return new BytesRestResponse(status, channel.newErrorBuilder().startObject()
.field("error", errorMessage)
.field("status", status.getStatus())
.endObject());
}
public static ElasticsearchStatusException errorFromXContent(XContentParser parser) throws IOException {
XContentParser.Token token = parser.nextToken();
ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser::getTokenLocation);
ElasticsearchException exception = null;
RestStatus status = null;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
}
if (STATUS.equals(currentFieldName)) {
if (token != XContentParser.Token.FIELD_NAME) {
ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser::getTokenLocation);
status = RestStatus.fromCode(parser.intValue());
}
} else {
exception = ElasticsearchException.failureFromXContent(parser);
}
}
if (exception == null) {
throw new IllegalStateException("Failed to parse elasticsearch status exception: no exception was found");
}
ElasticsearchStatusException result = new ElasticsearchStatusException(exception.getMessage(), status, exception.getCause());
for (String header : exception.getHeaderKeys()) {
result.addHeader(header, exception.getHeader(header));
}
for (String metadata : exception.getMetadataKeys()) {
result.addMetadata(metadata, exception.getMetadata(metadata));
}
return result;
}
}