From 2cd0ad8e9ce15ac4f53ef31b0b731c0d11163e7d Mon Sep 17 00:00:00 2001 From: Nicholas Walter Knize Date: Fri, 16 Jun 2023 11:33:31 -0500 Subject: [PATCH] Refactor ExceptionsHelper to opensearch-core and remove BaseExceptionsHelper Signed-off-by: Nicholas Walter Knize --- .../org/opensearch/BaseExceptionsHelper.java | 311 ------ .../java/org/opensearch/ExceptionsHelper.java | 104 +- .../org/opensearch/OpenSearchException.java | 926 ++++++++++-------- .../DefaultShardOperationFailedException.java | 8 +- .../NotSerializableExceptionWrapper.java | 8 +- .../geogrid/GeoTileGridParserTests.java | 4 +- .../reindex/AsyncBulkByScrollActionTests.java | 3 +- .../opensearch/action/RejectionActionIT.java | 4 +- .../action/search/TransportSearchIT.java | 8 +- .../org/opensearch/blocks/SimpleBlocksIT.java | 6 +- .../breaker/CircuitBreakerServiceIT.java | 4 +- .../indices/state/CloseIndexIT.java | 4 +- .../aggregations/pipeline/DerivativeIT.java | 4 +- .../pipeline/ExtendedStatsBucketIT.java | 4 +- .../pipeline/PercentilesBucketIT.java | 6 +- .../SharedClusterSnapshotRestoreIT.java | 4 +- .../OpenSearchSecurityException.java | 2 +- .../action/TaskOperationFailure.java | 6 +- .../NodesReloadSecureSettingsResponse.java | 4 +- .../shards/IndicesShardStoresResponse.java | 4 +- .../action/bulk/BulkItemResponse.java | 14 +- .../action/bulk/TransportBulkAction.java | 4 +- .../action/bulk/TransportShardBulkAction.java | 4 +- .../action/search/MultiSearchResponse.java | 4 +- .../search/SearchPhaseExecutionException.java | 9 +- .../action/search/ShardSearchFailure.java | 12 +- .../action/support/TransportActions.java | 4 +- .../replication/ReplicationOperation.java | 8 +- .../replication/ReplicationResponse.java | 6 +- .../TransportBroadcastReplicationAction.java | 4 +- .../action/shard/ShardStateAction.java | 3 +- .../cluster/routing/UnassignedInfo.java | 4 +- .../routing/allocation/FailedShard.java | 4 +- .../allocation/NodeAllocationResult.java | 4 +- .../java/org/opensearch/common/Strings.java | 4 +- .../common/lucene/search/Queries.java | 4 +- .../opensearch/gateway/AsyncShardFetch.java | 4 +- .../index/engine/InternalEngine.java | 6 +- .../index/mapper/MappedFieldType.java | 6 +- .../index/query/MoreLikeThisQueryBuilder.java | 3 +- .../index/reindex/BulkByScrollTask.java | 3 +- .../index/reindex/ScrollableHitSource.java | 9 +- .../opensearch/index/shard/IndexShard.java | 3 +- .../opensearch/index/shard/StoreRecovery.java | 4 +- .../recovery/PeerRecoveryTargetService.java | 6 +- .../recovery/RetryableTransportClient.java | 6 +- .../SegmentReplicationTargetService.java | 4 +- .../replication/common/ReplicationTarget.java | 4 +- .../opensearch/rest/BytesRestResponse.java | 15 +- .../DirectCandidateGeneratorBuilder.java | 4 +- .../tasks/TaskCancellationService.java | 6 +- .../org/opensearch/tasks/TaskManager.java | 5 +- .../java/org/opensearch/tasks/TaskResult.java | 4 +- .../opensearch/tasks/TaskResultsService.java | 4 +- .../org/opensearch/ExceptionsHelperTests.java | 15 +- .../opensearch/OpenSearchExceptionTests.java | 24 +- .../action/bulk/BulkItemResponseTests.java | 4 +- .../action/bulk/BulkResponseTests.java | 4 +- .../client/AbstractClientHeadersTestCase.java | 4 +- .../rest/BytesRestResponseTests.java | 4 +- .../pipeline/DerivativeAggregatorTests.java | 4 +- .../transport/TransportActionProxyTests.java | 4 +- .../test/OpenSearchIntegTestCase.java | 4 +- .../test/hamcrest/OpenSearchAssertions.java | 5 +- .../AbstractSimpleTransportTestCase.java | 11 +- 65 files changed, 791 insertions(+), 904 deletions(-) delete mode 100644 libs/core/src/main/java/org/opensearch/BaseExceptionsHelper.java rename {server => libs/core}/src/main/java/org/opensearch/ExceptionsHelper.java (76%) diff --git a/libs/core/src/main/java/org/opensearch/BaseExceptionsHelper.java b/libs/core/src/main/java/org/opensearch/BaseExceptionsHelper.java deleted file mode 100644 index 129ff99e65458..0000000000000 --- a/libs/core/src/main/java/org/opensearch/BaseExceptionsHelper.java +++ /dev/null @@ -1,311 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - * - * The OpenSearch Contributors require contributions made to - * this file be licensed under the Apache-2.0 license or a - * compatible open source license. - */ - -/* - * 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 - * - * 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. - */ - -/* - * Modifications Copyright OpenSearch Contributors. See - * GitHub history for details. - */ -package org.opensearch; - -import com.fasterxml.jackson.core.JsonParseException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.opensearch.common.compress.NotXContentException; -import org.opensearch.core.ParseField; -import org.opensearch.core.common.Strings; -import org.opensearch.core.concurrency.OpenSearchRejectedExecutionException; -import org.opensearch.core.xcontent.ToXContent; -import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.rest.RestStatus; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.List; -import java.util.Map; - -import static java.util.Collections.emptyMap; - -/** - * Base helper class for OpenSearch Exceptions - * - * @opensearch.internal - */ -public abstract class BaseExceptionsHelper { - /** - * Passed in the {@link ToXContent.Params} of {@link #generateThrowableXContent(XContentBuilder, ToXContent.Params, Throwable)} - * to control if the {@code stack_trace} element should render. Unlike most parameters to {@code toXContent} methods this parameter is - * internal only and not available as a URL parameter. Use the {@code error_trace} parameter instead. - */ - public static final String REST_EXCEPTION_SKIP_STACK_TRACE = "rest.exception.stacktrace.skip"; - public static final boolean REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT = true; - public static final String STACK_TRACE = "stack_trace"; - protected static final Logger logger = LogManager.getLogger(BaseExceptionsHelper.class); - protected static final String OPENSEARCH_PREFIX_KEY = "opensearch."; - /** - * Passed in the {@link ToXContent.Params} of {@link #generateThrowableXContent(XContentBuilder, ToXContent.Params, Throwable)} - * to control if the {@code caused_by} element should render. Unlike most parameters to {@code toXContent} methods this parameter is - * internal only and not available as a URL parameter. - */ - protected static final String REST_EXCEPTION_SKIP_CAUSE = "rest.exception.cause.skip"; - protected static final String TYPE = "type"; - protected static final String REASON = "reason"; - protected static final String CAUSED_BY = "caused_by"; - protected static final ParseField SUPPRESSED = new ParseField("suppressed"); - protected static final String HEADER = "header"; - private static final boolean REST_EXCEPTION_SKIP_CAUSE_DEFAULT = false; - - public static Throwable unwrapCause(Throwable t) { - int counter = 0; - Throwable result = t; - while (result instanceof OpenSearchWrapperException) { - if (result.getCause() == null) { - return result; - } - if (result.getCause() == result) { - return result; - } - if (counter++ > 10) { - // dear god, if we got more than 10 levels down, WTF? just bail - logger.warn("Exception cause unwrapping ran for 10 levels...", t); - return result; - } - result = result.getCause(); - } - return result; - } - - /** - * @deprecated Don't swallow exceptions, allow them to propagate. - */ - @Deprecated - public static String detailedMessage(Throwable t) { - if (t == null) { - return "Unknown"; - } - if (t.getCause() != null) { - StringBuilder sb = new StringBuilder(); - while (t != null) { - sb.append(getExceptionSimpleClassName(t)); - if (t.getMessage() != null) { - sb.append("["); - sb.append(t.getMessage()); - sb.append("]"); - } - sb.append("; "); - t = t.getCause(); - if (t != null) { - sb.append("nested: "); - } - } - return sb.toString(); - } else { - return getExceptionSimpleClassName(t) + "[" + t.getMessage() + "]"; - } - } - - public static String stackTrace(Throwable e) { - StringWriter stackTraceStringWriter = new StringWriter(); - PrintWriter printWriter = new PrintWriter(stackTraceStringWriter); - e.printStackTrace(printWriter); - return stackTraceStringWriter.toString(); - } - - public static String summaryMessage(Throwable t) { - if (t != null) { - if (t instanceof OpenSearchException) { - return getExceptionSimpleClassName(t) + "[" + t.getMessage() + "]"; - } else if (t instanceof IllegalArgumentException) { - return "Invalid argument"; - } else if (t instanceof JsonParseException) { - return "Failed to parse JSON"; - } else if (t instanceof OpenSearchRejectedExecutionException) { - return "Too many requests"; - } - } - return "Internal failure"; - } - - public static void innerToXContent( - XContentBuilder builder, - ToXContent.Params params, - Throwable throwable, - String type, - String message, - Map> headers, - Map> metadata, - Throwable cause - ) throws IOException { - builder.field(TYPE, type); - builder.field(REASON, message); - - for (Map.Entry> entry : metadata.entrySet()) { - headerToXContent(builder, entry.getKey().substring(OPENSEARCH_PREFIX_KEY.length()), entry.getValue()); - } - - if (throwable instanceof OpenSearchException) { - OpenSearchException exception = (OpenSearchException) throwable; - exception.metadataToXContent(builder, params); - } - - if (params.paramAsBoolean(REST_EXCEPTION_SKIP_CAUSE, REST_EXCEPTION_SKIP_CAUSE_DEFAULT) == false) { - if (cause != null) { - builder.field(CAUSED_BY); - builder.startObject(); - generateThrowableXContent(builder, params, cause); - builder.endObject(); - } - } - - if (headers.isEmpty() == false) { - builder.startObject(HEADER); - for (Map.Entry> entry : headers.entrySet()) { - headerToXContent(builder, entry.getKey(), entry.getValue()); - } - builder.endObject(); - } - - if (params.paramAsBoolean(REST_EXCEPTION_SKIP_STACK_TRACE, REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT) == false) { - builder.field(STACK_TRACE, stackTrace(throwable)); - } - - Throwable[] allSuppressed = throwable.getSuppressed(); - if (allSuppressed.length > 0) { - builder.startArray(SUPPRESSED.getPreferredName()); - for (Throwable suppressed : allSuppressed) { - builder.startObject(); - generateThrowableXContent(builder, params, suppressed); - builder.endObject(); - } - builder.endArray(); - } - } - - /** - * Static toXContent helper method that renders {@link OpenSearchException} or {@link Throwable} instances - * as XContent, delegating the rendering to {@link OpenSearchException#toXContent(XContentBuilder, ToXContent.Params)} - * or {@link #innerToXContent(XContentBuilder, ToXContent.Params, Throwable, String, String, Map, Map, Throwable)}. - * - * This method is usually used when the {@link Throwable} is rendered as a part of another XContent object, and its result can - * be parsed back using the {@code OpenSearchException.fromXContent(XContentParser)} method. - */ - public static void generateThrowableXContent(XContentBuilder builder, ToXContent.Params params, Throwable t) throws IOException { - t = unwrapCause(t); - - if (t instanceof OpenSearchException) { - ((OpenSearchException) t).toXContent(builder, params); - } else { - innerToXContent(builder, params, t, getExceptionName(t), t.getMessage(), emptyMap(), emptyMap(), t.getCause()); - } - } - - /** - * Returns an underscore case name for the given exception. This method strips {@code OpenSearch} prefixes from exception names. - */ - public static String getExceptionName(Throwable ex) { - String simpleName = getExceptionSimpleClassName(ex); - if (simpleName.startsWith("OpenSearch")) { - simpleName = simpleName.substring("OpenSearch".length()); - } - // TODO: do we really need to make the exception name in underscore casing? - return toUnderscoreCase(simpleName); - } - - private static String getExceptionSimpleClassName(final Throwable ex) { - String simpleName = ex.getClass().getSimpleName(); - if (Strings.isEmpty(simpleName)) { - simpleName = "OpenSearchException"; - } - return simpleName; - } - - // lower cases and adds underscores to transitions in a name - private static String toUnderscoreCase(String value) { - StringBuilder sb = new StringBuilder(); - boolean changed = false; - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - if (Character.isUpperCase(c)) { - if (!changed) { - // copy it over here - for (int j = 0; j < i; j++) { - sb.append(value.charAt(j)); - } - changed = true; - if (i == 0) { - sb.append(Character.toLowerCase(c)); - } else { - sb.append('_'); - sb.append(Character.toLowerCase(c)); - } - } else { - sb.append('_'); - sb.append(Character.toLowerCase(c)); - } - } else { - if (changed) { - sb.append(c); - } - } - } - if (!changed) { - return value; - } - return sb.toString(); - } - - protected static void headerToXContent(XContentBuilder builder, String key, List values) throws IOException { - if (values != null && values.isEmpty() == false) { - if (values.size() == 1) { - builder.field(key, values.get(0)); - } else { - builder.startArray(key); - for (String value : values) { - builder.value(value); - } - builder.endArray(); - } - } - } - - public static RestStatus status(Throwable t) { - if (t != null) { - if (t instanceof OpenSearchException) { - return ((OpenSearchException) t).status(); - } else if (t instanceof IllegalArgumentException) { - return RestStatus.BAD_REQUEST; - } else if (t instanceof JsonParseException) { - return RestStatus.BAD_REQUEST; - } else if (t instanceof OpenSearchRejectedExecutionException) { - return RestStatus.TOO_MANY_REQUESTS; - } else if (t instanceof NotXContentException) { - return RestStatus.BAD_REQUEST; - } - } - return RestStatus.INTERNAL_SERVER_ERROR; - } -} diff --git a/server/src/main/java/org/opensearch/ExceptionsHelper.java b/libs/core/src/main/java/org/opensearch/ExceptionsHelper.java similarity index 76% rename from server/src/main/java/org/opensearch/ExceptionsHelper.java rename to libs/core/src/main/java/org/opensearch/ExceptionsHelper.java index f4cf68b203a3a..d5c905f5dc528 100644 --- a/server/src/main/java/org/opensearch/ExceptionsHelper.java +++ b/libs/core/src/main/java/org/opensearch/ExceptionsHelper.java @@ -32,6 +32,9 @@ package org.opensearch; +import com.fasterxml.jackson.core.JsonParseException; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexFormatTooNewException; import org.apache.lucene.index.IndexFormatTooOldException; @@ -39,9 +42,14 @@ import org.opensearch.common.CheckedRunnable; import org.opensearch.common.CheckedSupplier; import org.opensearch.common.Nullable; +import org.opensearch.common.compress.NotXContentException; +import org.opensearch.core.concurrency.OpenSearchRejectedExecutionException; import org.opensearch.index.Index; +import org.opensearch.rest.RestStatus; import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -56,12 +64,18 @@ import java.util.function.Predicate; import java.util.stream.Collectors; +import static org.opensearch.OpenSearchException.getExceptionSimpleClassName; + /** * Helper class for OpenSearch Exceptions * * @opensearch.internal */ -public final class ExceptionsHelper extends BaseExceptionsHelper { +public final class ExceptionsHelper { + protected static final Logger logger = LogManager.getLogger(ExceptionsHelper.class); + + // utility class: no ctor + private ExceptionsHelper() {} public static RuntimeException convertToRuntime(Exception e) { if (e instanceof RuntimeException) { @@ -77,6 +91,94 @@ public static OpenSearchException convertToOpenSearchException(Exception e) { return new OpenSearchException(e); } + public static RestStatus status(Throwable t) { + if (t != null) { + if (t instanceof OpenSearchException) { + return ((OpenSearchException) t).status(); + } else if (t instanceof IllegalArgumentException) { + return RestStatus.BAD_REQUEST; + } else if (t instanceof JsonParseException) { + return RestStatus.BAD_REQUEST; + } else if (t instanceof OpenSearchRejectedExecutionException) { + return RestStatus.TOO_MANY_REQUESTS; + } else if (t instanceof NotXContentException) { + return RestStatus.BAD_REQUEST; + } + } + return RestStatus.INTERNAL_SERVER_ERROR; + } + + public static String summaryMessage(Throwable t) { + if (t != null) { + if (t instanceof OpenSearchException) { + return getExceptionSimpleClassName(t) + "[" + t.getMessage() + "]"; + } else if (t instanceof IllegalArgumentException) { + return "Invalid argument"; + } else if (t instanceof JsonParseException) { + return "Failed to parse JSON"; + } else if (t instanceof OpenSearchRejectedExecutionException) { + return "Too many requests"; + } + } + return "Internal failure"; + } + + public static Throwable unwrapCause(Throwable t) { + int counter = 0; + Throwable result = t; + while (result instanceof OpenSearchWrapperException) { + if (result.getCause() == null) { + return result; + } + if (result.getCause() == result) { + return result; + } + if (counter++ > 10) { + // dear god, if we got more than 10 levels down, WTF? just bail + logger.warn("Exception cause unwrapping ran for 10 levels...", t); + return result; + } + result = result.getCause(); + } + return result; + } + + /** + * @deprecated Don't swallow exceptions, allow them to propagate. + */ + @Deprecated + public static String detailedMessage(Throwable t) { + if (t == null) { + return "Unknown"; + } + if (t.getCause() != null) { + StringBuilder sb = new StringBuilder(); + while (t != null) { + sb.append(getExceptionSimpleClassName(t)); + if (t.getMessage() != null) { + sb.append("["); + sb.append(t.getMessage()); + sb.append("]"); + } + sb.append("; "); + t = t.getCause(); + if (t != null) { + sb.append("nested: "); + } + } + return sb.toString(); + } else { + return getExceptionSimpleClassName(t) + "[" + t.getMessage() + "]"; + } + } + + public static String stackTrace(Throwable e) { + StringWriter stackTraceStringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stackTraceStringWriter); + e.printStackTrace(printWriter); + return stackTraceStringWriter.toString(); + } + public static String formatStackTrace(final StackTraceElement[] stackTrace) { return Arrays.stream(stackTrace).skip(1).map(e -> "\tat " + e).collect(Collectors.joining("\n")); } diff --git a/libs/core/src/main/java/org/opensearch/OpenSearchException.java b/libs/core/src/main/java/org/opensearch/OpenSearchException.java index e201fe7b1b788..707b53dfa58f9 100644 --- a/libs/core/src/main/java/org/opensearch/OpenSearchException.java +++ b/libs/core/src/main/java/org/opensearch/OpenSearchException.java @@ -37,6 +37,7 @@ import org.opensearch.common.io.stream.StreamInput; import org.opensearch.common.io.stream.StreamOutput; import org.opensearch.common.io.stream.Writeable; +import org.opensearch.core.ParseField; import org.opensearch.core.common.Strings; import org.opensearch.core.common.logging.LoggerMessageFormat; import org.opensearch.core.xcontent.ToXContent; @@ -59,6 +60,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import static java.util.Collections.emptyMap; import static org.opensearch.OpenSearchException.OpenSearchExceptionHandleRegistry.registerExceptionHandle; import static org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken; import static org.opensearch.common.xcontent.XContentParserUtils.ensureFieldName; @@ -72,14 +74,38 @@ */ public class OpenSearchException extends RuntimeException implements Writeable, ToXContentFragment { - protected static final String ERROR = "error"; - protected static final String ROOT_CAUSE = "root_cause"; - protected static final String RESOURCE_METADATA_TYPE_KEY = "opensearch.resource.type"; - protected static final String RESOURCE_METADATA_ID_KEY = "opensearch.resource.id"; protected static final Version UNKNOWN_VERSION_ADDED = Version.fromId(0); - protected static final String INDEX_METADATA_KEY = "opensearch.index"; - protected static final String SHARD_METADATA_KEY = "opensearch.shard"; - protected static final String INDEX_METADATA_KEY_UUID = "opensearch.index_uuid"; + + /** + * Passed in the {@link ToXContent.Params} of {@link #generateThrowableXContent(XContentBuilder, ToXContent.Params, Throwable)} + * to control if the {@code caused_by} element should render. Unlike most parameters to {@code toXContent} methods this parameter is + * internal only and not available as a URL parameter. + */ + private static final String REST_EXCEPTION_SKIP_CAUSE = "rest.exception.cause.skip"; + /** + * Passed in the {@link ToXContent.Params} of {@link #generateThrowableXContent(XContentBuilder, ToXContent.Params, Throwable)} + * to control if the {@code stack_trace} element should render. Unlike most parameters to {@code toXContent} methods this parameter is + * internal only and not available as a URL parameter. Use the {@code error_trace} parameter instead. + */ + public static final String REST_EXCEPTION_SKIP_STACK_TRACE = "rest.exception.stacktrace.skip"; + public static final boolean REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT = true; + private static final boolean REST_EXCEPTION_SKIP_CAUSE_DEFAULT = false; + private static final String RESOURCE_METADATA_TYPE_KEY = "opensearch.resource.type"; + private static final String RESOURCE_METADATA_ID_KEY = "opensearch.resource.id"; + private static final String INDEX_METADATA_KEY = "opensearch.index"; + private static final String INDEX_METADATA_KEY_UUID = "opensearch.index_uuid"; + private static final String SHARD_METADATA_KEY = "opensearch.shard"; + private static final String OPENSEARCH_PREFIX_KEY = "opensearch."; + + private static final String TYPE = "type"; + private static final String REASON = "reason"; + private static final String CAUSED_BY = "caused_by"; + private static final ParseField SUPPRESSED = new ParseField("suppressed"); + public static final String STACK_TRACE = "stack_trace"; + private static final String HEADER = "header"; + private static final String ERROR = "error"; + private static final String ROOT_CAUSE = "root_cause"; + protected final Map> metadata = new HashMap<>(); protected final Map> headers = new HashMap<>(); @@ -161,101 +187,6 @@ public void writeTo(final StreamOutput out) throws IOException { out.writeMapOfLists(metadata, StreamOutput::writeString, StreamOutput::writeString); } - /** - * Render any exception as a xcontent, encapsulated within a field or object named "error". The level of details that are rendered - * depends on the value of the "detailed" parameter: when it's false only a simple message based on the type and message of the - * exception is rendered. When it's true all detail are provided including guesses root causes, cause and potentially stack - * trace. - * - * This method is usually used when the {@link Exception} is rendered as a full XContent object, and its output can be parsed - * by the {@code #OpenSearchException.failureFromXContent(XContentParser)} method. - */ - public static void generateFailureXContent(XContentBuilder builder, ToXContent.Params params, @Nullable Exception e, boolean detailed) - throws IOException { - // No exception to render as an error - if (e == null) { - builder.field(ERROR, "unknown"); - return; - } - - // Render the exception with a simple message - if (detailed == false) { - Throwable t = e; - for (int counter = 0; counter < 10 && t != null; counter++) { - if (t instanceof OpenSearchException) { - break; - } - t = t.getCause(); - } - builder.field(ERROR, BaseExceptionsHelper.summaryMessage(t != null ? t : e)); - return; - } - - // Render the exception with all details - final OpenSearchException[] rootCauses = OpenSearchException.guessRootCauses(e); - builder.startObject(ERROR); - { - builder.startArray(ROOT_CAUSE); - for (OpenSearchException rootCause : rootCauses) { - builder.startObject(); - rootCause.toXContent( - builder, - new ToXContent.DelegatingMapParams(singletonMap(BaseExceptionsHelper.REST_EXCEPTION_SKIP_CAUSE, "true"), params) - ); - builder.endObject(); - } - builder.endArray(); - } - BaseExceptionsHelper.generateThrowableXContent(builder, params, e); - builder.endObject(); - } - - /** - * Returns the root cause of this exception or multiple if different shards caused different exceptions. - * If the given exception is not an instance of {@link OpenSearchException} an empty array - * is returned. - */ - public static OpenSearchException[] guessRootCauses(Throwable t) { - Throwable ex = BaseExceptionsHelper.unwrapCause(t); - if (ex instanceof OpenSearchException) { - // OpenSearchException knows how to guess its own root cause - return ((OpenSearchException) ex).guessRootCauses(); - } - if (ex instanceof XContentParseException) { - /* - * We'd like to unwrap parsing exceptions to the inner-most - * parsing exception because that is generally the most interesting - * exception to return to the user. If that exception is caused by - * an OpenSearchException we'd like to keep unwrapping because - * OpenSearchException instances tend to contain useful information - * for the user. - */ - Throwable cause = ex.getCause(); - if (cause != null) { - if (cause instanceof XContentParseException || cause instanceof OpenSearchException) { - return OpenSearchException.guessRootCauses(ex.getCause()); - } - } - } - return new OpenSearchException[] { new OpenSearchException(ex.getMessage(), ex) { - @Override - protected String getExceptionName() { - return BaseExceptionsHelper.getExceptionName(getCause()); - } - } }; - } - - static String buildMessage(String type, String reason, String stack) { - StringBuilder message = new StringBuilder("OpenSearch exception ["); - message.append(BaseExceptionsHelper.TYPE).append('=').append(type).append(", "); - message.append(BaseExceptionsHelper.REASON).append('=').append(reason); - if (stack != null) { - message.append(", ").append(BaseExceptionsHelper.STACK_TRACE).append('=').append(stack); - } - message.append(']'); - return message.toString(); - } - /** * Adds a new piece of metadata with the given key. * If the provided key is already present, the corresponding metadata will be replaced @@ -271,7 +202,7 @@ public void addMetadata(String key, String... values) { public void addMetadata(String key, List values) { // we need to enforce this otherwise bw comp doesn't work properly, as "opensearch." // was the previous criteria to split headers in two sets - if (key.startsWith(BaseExceptionsHelper.OPENSEARCH_PREFIX_KEY) == false) { + if (key.startsWith(OPENSEARCH_PREFIX_KEY) == false) { throw new IllegalArgumentException("exception metadata must start with [opensearch.], found [" + key + "] instead"); } this.metadata.put(key, values); @@ -303,7 +234,7 @@ protected Map> getMetadata() { public void addHeader(String key, List value) { // we need to enforce this otherwise bw comp doesn't work properly, as "opensearch." // was the previous criteria to split headers in two sets - if (key.startsWith(BaseExceptionsHelper.OPENSEARCH_PREFIX_KEY)) { + if (key.startsWith(OPENSEARCH_PREFIX_KEY)) { throw new IllegalArgumentException("exception headers must not start with [opensearch.], found [" + key + "] instead"); } this.headers.put(key, value); @@ -336,14 +267,26 @@ protected Map> getHeaders() { return headers; } + /** + * Returns the rest status code associated with this exception. + */ + public RestStatus status() { + Throwable cause = unwrapCause(); + if (cause == this) { + return RestStatus.INTERNAL_SERVER_ERROR; + } else { + return ExceptionsHelper.status(cause); + } + } + /** * Unwraps the actual cause from the exception for cases when the exception is a * {@link OpenSearchWrapperException}. * - * @see BaseExceptionsHelper#unwrapCause(Throwable) + * @see ExceptionsHelper#unwrapCause(Throwable) */ public Throwable unwrapCause() { - return BaseExceptionsHelper.unwrapCause(this); + return ExceptionsHelper.unwrapCause(this); } /** @@ -378,353 +321,162 @@ public Throwable getRootCause() { return rootCause; } - /** - * Renders additional per exception information into the XContent - */ - protected void metadataToXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {} - - public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { - Throwable ex = BaseExceptionsHelper.unwrapCause(this); - if (ex != this) { - BaseExceptionsHelper.generateThrowableXContent(builder, params, this); - } else { - BaseExceptionsHelper.innerToXContent(builder, params, this, getExceptionName(), getMessage(), headers, metadata, getCause()); + @SuppressWarnings("unchecked") + public static OpenSearchException readException(T input, int id) throws IOException { + CheckedFunction opensearchException = (CheckedFunction< + T, + ? extends OpenSearchException, + IOException>) OpenSearchExceptionHandleRegistry.getSupplier(id); + if (opensearchException == null) { + throw new IllegalStateException("unknown exception for id: " + id); } - return builder; - } - - protected String getExceptionName() { - return BaseExceptionsHelper.getExceptionName(this); + return opensearchException.apply(input); } /** - * Returns the root cause of this exception or multiple if different shards caused different exceptions + * Returns true iff the given class is a registered for an exception to be read. */ - public OpenSearchException[] guessRootCauses() { - final Throwable cause = getCause(); - if (cause != null && cause instanceof OpenSearchException) { - return ((OpenSearchException) cause).guessRootCauses(); - } - return new OpenSearchException[] { this }; + public static boolean isRegistered(final Class exception, Version version) { + return OpenSearchExceptionHandleRegistry.isRegistered(exception, version); } - public void setResources(String type, String... id) { - assert type != null; - addMetadata(RESOURCE_METADATA_ID_KEY, id); - addMetadata(RESOURCE_METADATA_TYPE_KEY, type); + static Set> getRegisteredKeys() { // for testing + return OpenSearchExceptionHandleRegistry.getRegisteredKeys(); } - public List getResourceId() { - return getMetadata(RESOURCE_METADATA_ID_KEY); + /** + * Returns the serialization id the given exception. + */ + public static int getId(final Class exception) { + return OpenSearchExceptionHandleRegistry.getId(exception); } - public String getResourceType() { - List header = getMetadata(RESOURCE_METADATA_TYPE_KEY); - if (header != null && header.isEmpty() == false) { - assert header.size() == 1; - return header.get(0); + public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { + Throwable ex = ExceptionsHelper.unwrapCause(this); + if (ex != this) { + generateThrowableXContent(builder, params, this); + } else { + innerToXContent(builder, params, this, getExceptionName(), getMessage(), headers, metadata, getCause()); } - return null; + return builder; } - public String getIndexName() { - List index = getMetadata(INDEX_METADATA_KEY); - if (index != null && index.isEmpty() == false) { - return index.get(0); + protected static void innerToXContent( + XContentBuilder builder, + ToXContent.Params params, + Throwable throwable, + String type, + String message, + Map> headers, + Map> metadata, + Throwable cause + ) throws IOException { + builder.field(TYPE, type); + builder.field(REASON, message); + + for (Map.Entry> entry : metadata.entrySet()) { + headerToXContent(builder, entry.getKey().substring(OPENSEARCH_PREFIX_KEY.length()), entry.getValue()); } - return null; - } - /** - * Get index uuid as a string - * - * @deprecated remove in favor of Index#toString once Index class is moved to core library - */ - @Deprecated - private String getIndexUUID() { - List index_uuid = getMetadata(INDEX_METADATA_KEY_UUID); - if (index_uuid != null && index_uuid.isEmpty() == false) { - return index_uuid.get(0); + if (throwable instanceof OpenSearchException) { + OpenSearchException exception = (OpenSearchException) throwable; + exception.metadataToXContent(builder, params); } - return null; - } - /** - * Returns the rest status code associated with this exception. - */ - public RestStatus status() { - Throwable cause = unwrapCause(); - if (cause == this) { - return RestStatus.INTERNAL_SERVER_ERROR; - } else { - return BaseExceptionsHelper.status(cause); + if (params.paramAsBoolean(REST_EXCEPTION_SKIP_CAUSE, REST_EXCEPTION_SKIP_CAUSE_DEFAULT) == false) { + if (cause != null) { + builder.field(CAUSED_BY); + builder.startObject(); + generateThrowableXContent(builder, params, cause); + builder.endObject(); + } } - } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - if (metadata.containsKey(INDEX_METADATA_KEY)) { - builder.append(getIndexString()); - if (metadata.containsKey(SHARD_METADATA_KEY)) { - builder.append('[').append(getShardIdString()).append(']'); + if (headers.isEmpty() == false) { + builder.startObject(HEADER); + for (Map.Entry> entry : headers.entrySet()) { + headerToXContent(builder, entry.getKey(), entry.getValue()); } - builder.append(' '); + builder.endObject(); } - return builder.append(BaseExceptionsHelper.detailedMessage(this).trim()).toString(); - } - /** - * Get index string - * - * @deprecated remove in favor of Index#toString once Index class is moved to core library - */ - @Deprecated - private String getIndexString() { - String uuid = getIndexUUID(); - if (uuid != null) { - String name = getIndexName(); - if (Strings.UNKNOWN_UUID_VALUE.equals(uuid)) { - return "[" + name + "]"; + if (params.paramAsBoolean(REST_EXCEPTION_SKIP_STACK_TRACE, REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT) == false) { + builder.field(STACK_TRACE, ExceptionsHelper.stackTrace(throwable)); + } + + Throwable[] allSuppressed = throwable.getSuppressed(); + if (allSuppressed.length > 0) { + builder.startArray(SUPPRESSED.getPreferredName()); + for (Throwable suppressed : allSuppressed) { + builder.startObject(); + generateThrowableXContent(builder, params, suppressed); + builder.endObject(); } - return "[" + name + "/" + uuid + "]"; + builder.endArray(); } - return null; } - /** - * Get shard id string - * - * @deprecated remove in favor of ShardId#toString once ShardId class is moved to core library - */ - @Deprecated - private String getShardIdString() { - String indexName = getIndexName(); - List shard = getMetadata(SHARD_METADATA_KEY); - if (indexName != null && shard != null && shard.isEmpty() == false) { - return "[" + indexName + "][" + Integer.parseInt(shard.get(0)) + "]"; + protected static void headerToXContent(XContentBuilder builder, String key, List values) throws IOException { + if (values != null && values.isEmpty() == false) { + if (values.size() == 1) { + builder.field(key, values.get(0)); + } else { + builder.startArray(key); + for (String value : values) { + builder.value(value); + } + builder.endArray(); + } } - return null; } /** - * Returns an array of all registered handle IDs. These are the IDs for every registered - * exception. - * - * @return an array of all registered handle IDs + * Renders additional per exception information into the XContent */ - static int[] ids() { - return OpenSearchExceptionHandleRegistry.ids().stream().mapToInt(i -> i).toArray(); - } + protected void metadataToXContent(XContentBuilder builder, Params params) throws IOException {} /** - * Returns an array of all registered pairs of handle IDs and exception classes. These pairs are - * provided for every registered exception. - * - * @return an array of all registered pairs of handle IDs and exception classes + * Generate a {@link OpenSearchException} from a {@link XContentParser}. This does not + * return the original exception type (ie NodeClosedException for example) but just wraps + * the type, the reason and the cause of the exception. It also recursively parses the + * tree structure of the cause, returning it as a tree structure of {@link OpenSearchException} + * instances. */ - @SuppressWarnings("unchecked") - static Tuple>[] classes() { - final Tuple>[] ts = OpenSearchExceptionHandleRegistry.handles() - .stream() - .map(h -> Tuple.tuple(h.id, h.exceptionClass)) - .toArray(Tuple[]::new); - return ts; + public static OpenSearchException fromXContent(XContentParser parser) throws IOException { + XContentParser.Token token = parser.nextToken(); + ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser); + return innerFromXContent(parser, false); } - public Index getIndex() { - List index = getMetadata(INDEX_METADATA_KEY); - if (index != null && index.isEmpty() == false) { - List index_uuid = getMetadata(INDEX_METADATA_KEY_UUID); - return new Index(index.get(0), index_uuid.get(0)); - } + public static OpenSearchException innerFromXContent(XContentParser parser, boolean parseRootCauses) throws IOException { + XContentParser.Token token = parser.currentToken(); + ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser); - return null; - } + String type = null, reason = null, stack = null; + OpenSearchException cause = null; + Map> metadata = new HashMap<>(); + Map> headers = new HashMap<>(); + List rootCauses = new ArrayList<>(); + List suppressed = new ArrayList<>(); - public void setIndex(Index index) { - if (index != null) { - addMetadata(INDEX_METADATA_KEY, index.getName()); - addMetadata(INDEX_METADATA_KEY_UUID, index.getUUID()); - } - } - - public void setIndex(String index) { - if (index != null) { - setIndex(new Index(index, Strings.UNKNOWN_UUID_VALUE)); - } - } - - public ShardId getShardId() { - List shard = getMetadata(SHARD_METADATA_KEY); - if (shard != null && shard.isEmpty() == false) { - return new ShardId(getIndex(), Integer.parseInt(shard.get(0))); - } - return null; - } - - public void setShard(ShardId shardId) { - if (shardId != null) { - setIndex(shardId.getIndex()); - addMetadata(SHARD_METADATA_KEY, Integer.toString(shardId.id())); - } - } - - /** - * This is the list of Exceptions OpenSearch can throw over the wire or save into a corruption marker. Each value in the enum is a - * single exception tying the Class to an id for use of the encode side and the id back to a constructor for use on the decode side. As - * such its ok if the exceptions to change names so long as their constructor can still read the exception. Each exception is listed - * in id order. If you want to remove an exception leave a tombstone comment and mark the id as null in - * ExceptionSerializationTests.testIds.ids. - * - * @opensearch.internal - */ - protected static class OpenSearchExceptionHandle { - final Class exceptionClass; - final CheckedFunction constructor; - final int id; - final Version versionAdded; - - OpenSearchExceptionHandle( - Class exceptionClass, - CheckedFunction constructor, - int id, - Version versionAdded - ) { - // We need the exceptionClass because you can't dig it out of the constructor reliably. - this.exceptionClass = exceptionClass; - this.constructor = constructor; - this.versionAdded = versionAdded; - this.id = id; - } - } - - @SuppressWarnings("unchecked") - public static OpenSearchException readException(T input, int id) throws IOException { - CheckedFunction opensearchException = (CheckedFunction< - T, - ? extends OpenSearchException, - IOException>) OpenSearchExceptionHandleRegistry.getSupplier(id); - if (opensearchException == null) { - throw new IllegalStateException("unknown exception for id: " + id); - } - return opensearchException.apply(input); - } - - /** - * Deserializes stacktrace elements as well as suppressed exceptions from the given output stream and - * adds it to the given exception. - */ - public static T readStackTrace(T throwable, StreamInput in) throws IOException { - throwable.setStackTrace(in.readArray(i -> { - final String declaringClasss = i.readString(); - final String fileName = i.readOptionalString(); - final String methodName = i.readString(); - final int lineNumber = i.readVInt(); - return new StackTraceElement(declaringClasss, methodName, fileName, lineNumber); - }, StackTraceElement[]::new)); - - int numSuppressed = in.readVInt(); - for (int i = 0; i < numSuppressed; i++) { - throwable.addSuppressed(in.readException()); - } - return throwable; - } - - /** - * Serializes the given exceptions stacktrace elements as well as it's suppressed exceptions to the given output stream. - */ - public static T writeStackTraces( - T throwable, - StreamOutput out, - Writer exceptionWriter - ) throws IOException { - out.writeArray((o, v) -> { - o.writeString(v.getClassName()); - o.writeOptionalString(v.getFileName()); - o.writeString(v.getMethodName()); - o.writeVInt(v.getLineNumber()); - }, throwable.getStackTrace()); - out.writeArray(exceptionWriter, throwable.getSuppressed()); - return throwable; - } - - /** - * Returns the serialization id the given exception. - */ - public static int getId(final Class exception) { - return OpenSearchExceptionHandleRegistry.getId(exception); - } - - /** - * Returns true iff the given class is a registered for an exception to be read. - */ - public static boolean isRegistered(final Class exception, Version version) { - return OpenSearchExceptionHandleRegistry.isRegistered(exception, version); - } - - /** - * Generate a {@link OpenSearchException} from a {@link XContentParser}. This does not - * return the original exception type (ie NodeClosedException for example) but just wraps - * the type, the reason and the cause of the exception. It also recursively parses the - * tree structure of the cause, returning it as a tree structure of {@link OpenSearchException} - * instances. - */ - public static OpenSearchException fromXContent(XContentParser parser) throws IOException { - XContentParser.Token token = parser.nextToken(); - ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser); - return innerFromXContent(parser, false); - } - - /** - * Parses the output of {@link #generateFailureXContent(XContentBuilder, Params, Exception, boolean)} - */ - public static OpenSearchException failureFromXContent(XContentParser parser) throws IOException { - XContentParser.Token token = parser.currentToken(); - ensureFieldName(parser, token, ERROR); - - token = parser.nextToken(); - if (token.isValue()) { - return new OpenSearchException(buildMessage("exception", parser.text(), null)) { - }; - } - - ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser); - token = parser.nextToken(); - - // Root causes are parsed in the innerFromXContent() and are added as suppressed exceptions. - return innerFromXContent(parser, true); - } - - public static OpenSearchException innerFromXContent(XContentParser parser, boolean parseRootCauses) throws IOException { - XContentParser.Token token = parser.currentToken(); - ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser); - - String type = null, reason = null, stack = null; - OpenSearchException cause = null; - Map> metadata = new HashMap<>(); - Map> headers = new HashMap<>(); - List rootCauses = new ArrayList<>(); - List suppressed = new ArrayList<>(); - - for (; token == XContentParser.Token.FIELD_NAME; token = parser.nextToken()) { - String currentFieldName = parser.currentName(); - token = parser.nextToken(); + for (; token == XContentParser.Token.FIELD_NAME; token = parser.nextToken()) { + String currentFieldName = parser.currentName(); + token = parser.nextToken(); if (token.isValue()) { - if (BaseExceptionsHelper.TYPE.equals(currentFieldName)) { + if (TYPE.equals(currentFieldName)) { type = parser.text(); - } else if (BaseExceptionsHelper.REASON.equals(currentFieldName)) { + } else if (REASON.equals(currentFieldName)) { reason = parser.text(); - } else if (BaseExceptionsHelper.STACK_TRACE.equals(currentFieldName)) { + } else if (STACK_TRACE.equals(currentFieldName)) { stack = parser.text(); } else if (token == XContentParser.Token.VALUE_STRING) { metadata.put(currentFieldName, Collections.singletonList(parser.text())); } } else if (token == XContentParser.Token.START_OBJECT) { - if (BaseExceptionsHelper.CAUSED_BY.equals(currentFieldName)) { + if (CAUSED_BY.equals(currentFieldName)) { cause = fromXContent(parser); - } else if (BaseExceptionsHelper.HEADER.equals(currentFieldName)) { + } else if (HEADER.equals(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); @@ -757,7 +509,7 @@ public static OpenSearchException innerFromXContent(XContentParser parser, boole while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { rootCauses.add(fromXContent(parser)); } - } else if (BaseExceptionsHelper.SUPPRESSED.match(currentFieldName, parser.getDeprecationHandler())) { + } else if (SUPPRESSED.match(currentFieldName, parser.getDeprecationHandler())) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { suppressed.add(fromXContent(parser)); } @@ -791,7 +543,7 @@ public static OpenSearchException innerFromXContent(XContentParser parser, boole // by addMetadata. The prefix will get stripped out when printing metadata out so it will be effectively invisible. // TODO move subclasses that print out simple metadata to using addMetadata directly and support also numbers and booleans. // TODO rename metadataToXContent and have only SearchPhaseExecutionException use it, which prints out complex objects - e.addMetadata(BaseExceptionsHelper.OPENSEARCH_PREFIX_KEY + entry.getKey(), entry.getValue()); + e.addMetadata(OPENSEARCH_PREFIX_KEY + entry.getKey(), entry.getValue()); } for (Map.Entry> header : headers.entrySet()) { e.addHeader(header.getKey(), header.getValue()); @@ -808,8 +560,366 @@ public static OpenSearchException innerFromXContent(XContentParser parser, boole return e; } - static Set> getRegisteredKeys() { // for testing - return OpenSearchExceptionHandleRegistry.getRegisteredKeys(); + /** + * Static toXContent helper method that renders {@link OpenSearchException} or {@link Throwable} instances + * as XContent, delegating the rendering to {@link OpenSearchException#toXContent(XContentBuilder, ToXContent.Params)} + * or {@link #innerToXContent(XContentBuilder, ToXContent.Params, Throwable, String, String, Map, Map, Throwable)}. + * + * This method is usually used when the {@link Throwable} is rendered as a part of another XContent object, and its result can + * be parsed back using the {@code OpenSearchException.fromXContent(XContentParser)} method. + */ + public static void generateThrowableXContent(XContentBuilder builder, ToXContent.Params params, Throwable t) throws IOException { + t = ExceptionsHelper.unwrapCause(t); + + if (t instanceof OpenSearchException) { + ((OpenSearchException) t).toXContent(builder, params); + } else { + innerToXContent(builder, params, t, getExceptionName(t), t.getMessage(), emptyMap(), emptyMap(), t.getCause()); + } + } + + /** + * Render any exception as a xcontent, encapsulated within a field or object named "error". The level of details that are rendered + * depends on the value of the "detailed" parameter: when it's false only a simple message based on the type and message of the + * exception is rendered. When it's true all detail are provided including guesses root causes, cause and potentially stack + * trace. + * + * This method is usually used when the {@link Exception} is rendered as a full XContent object, and its output can be parsed + * by the {@code #OpenSearchException.failureFromXContent(XContentParser)} method. + */ + public static void generateFailureXContent(XContentBuilder builder, ToXContent.Params params, @Nullable Exception e, boolean detailed) + throws IOException { + // No exception to render as an error + if (e == null) { + builder.field(ERROR, "unknown"); + return; + } + + // Render the exception with a simple message + if (detailed == false) { + Throwable t = e; + for (int counter = 0; counter < 10 && t != null; counter++) { + if (t instanceof OpenSearchException) { + break; + } + t = t.getCause(); + } + builder.field(ERROR, ExceptionsHelper.summaryMessage(t != null ? t : e)); + return; + } + + // Render the exception with all details + final OpenSearchException[] rootCauses = OpenSearchException.guessRootCauses(e); + builder.startObject(ERROR); + { + builder.startArray(ROOT_CAUSE); + for (OpenSearchException rootCause : rootCauses) { + builder.startObject(); + rootCause.toXContent(builder, new ToXContent.DelegatingMapParams(singletonMap(REST_EXCEPTION_SKIP_CAUSE, "true"), params)); + builder.endObject(); + } + builder.endArray(); + } + generateThrowableXContent(builder, params, e); + builder.endObject(); + } + + /** + * Parses the output of {@link #generateFailureXContent(XContentBuilder, Params, Exception, boolean)} + */ + public static OpenSearchException failureFromXContent(XContentParser parser) throws IOException { + XContentParser.Token token = parser.currentToken(); + ensureFieldName(parser, token, ERROR); + + token = parser.nextToken(); + if (token.isValue()) { + return new OpenSearchException(buildMessage("exception", parser.text(), null)) { + }; + } + + ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser); + token = parser.nextToken(); + + // Root causes are parsed in the innerFromXContent() and are added as suppressed exceptions. + return innerFromXContent(parser, true); + } + + /** + * Returns the root cause of this exception or multiple if different shards caused different exceptions + */ + public OpenSearchException[] guessRootCauses() { + final Throwable cause = getCause(); + if (cause != null && cause instanceof OpenSearchException) { + return ((OpenSearchException) cause).guessRootCauses(); + } + return new OpenSearchException[] { this }; + } + + /** + * Returns the root cause of this exception or multiple if different shards caused different exceptions. + * If the given exception is not an instance of {@link OpenSearchException} an empty array + * is returned. + */ + public static OpenSearchException[] guessRootCauses(Throwable t) { + Throwable ex = ExceptionsHelper.unwrapCause(t); + if (ex instanceof OpenSearchException) { + // OpenSearchException knows how to guess its own root cause + return ((OpenSearchException) ex).guessRootCauses(); + } + if (ex instanceof XContentParseException) { + /* + * We'd like to unwrap parsing exceptions to the inner-most + * parsing exception because that is generally the most interesting + * exception to return to the user. If that exception is caused by + * an OpenSearchException we'd like to keep unwrapping because + * OpenSearchException instances tend to contain useful information + * for the user. + */ + Throwable cause = ex.getCause(); + if (cause != null) { + if (cause instanceof XContentParseException || cause instanceof OpenSearchException) { + return OpenSearchException.guessRootCauses(ex.getCause()); + } + } + } + return new OpenSearchException[] { new OpenSearchException(ex.getMessage(), ex) { + @Override + protected String getExceptionName() { + return getExceptionName(getCause()); + } + } }; + } + + protected String getExceptionName() { + return getExceptionName(this); + } + + /** + * Returns an underscore case name for the given exception. This method strips {@code OpenSearch} prefixes from exception names. + */ + public static String getExceptionName(Throwable ex) { + String simpleName = getExceptionSimpleClassName(ex); + if (simpleName.startsWith("OpenSearch")) { + simpleName = simpleName.substring("OpenSearch".length()); + } + // TODO: do we really need to make the exception name in underscore casing? + return toUnderscoreCase(simpleName); + } + + public static String getExceptionSimpleClassName(final Throwable ex) { + String simpleName = ex.getClass().getSimpleName(); + if (Strings.isEmpty(simpleName)) { + simpleName = "OpenSearchException"; + } + return simpleName; + } + + static String buildMessage(String type, String reason, String stack) { + StringBuilder message = new StringBuilder("OpenSearch exception ["); + message.append(TYPE).append('=').append(type).append(", "); + message.append(REASON).append('=').append(reason); + if (stack != null) { + message.append(", ").append(STACK_TRACE).append('=').append(stack); + } + message.append(']'); + return message.toString(); + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + if (metadata.containsKey(INDEX_METADATA_KEY)) { + builder.append(getIndex()); + if (metadata.containsKey(SHARD_METADATA_KEY)) { + builder.append('[').append(getShardId()).append(']'); + } + builder.append(' '); + } + return builder.append(ExceptionsHelper.detailedMessage(this).trim()).toString(); + } + + /** + * Deserializes stacktrace elements as well as suppressed exceptions from the given output stream and + * adds it to the given exception. + */ + public static T readStackTrace(T throwable, StreamInput in) throws IOException { + throwable.setStackTrace(in.readArray(i -> { + final String declaringClasss = i.readString(); + final String fileName = i.readOptionalString(); + final String methodName = i.readString(); + final int lineNumber = i.readVInt(); + return new StackTraceElement(declaringClasss, methodName, fileName, lineNumber); + }, StackTraceElement[]::new)); + + int numSuppressed = in.readVInt(); + for (int i = 0; i < numSuppressed; i++) { + throwable.addSuppressed(in.readException()); + } + return throwable; + } + + /** + * Serializes the given exceptions stacktrace elements as well as it's suppressed exceptions to the given output stream. + */ + public static T writeStackTraces( + T throwable, + StreamOutput out, + Writer exceptionWriter + ) throws IOException { + out.writeArray((o, v) -> { + o.writeString(v.getClassName()); + o.writeOptionalString(v.getFileName()); + o.writeString(v.getMethodName()); + o.writeVInt(v.getLineNumber()); + }, throwable.getStackTrace()); + out.writeArray(exceptionWriter, throwable.getSuppressed()); + return throwable; + } + + public void setResources(String type, String... id) { + assert type != null; + addMetadata(RESOURCE_METADATA_ID_KEY, id); + addMetadata(RESOURCE_METADATA_TYPE_KEY, type); + } + + public List getResourceId() { + return getMetadata(RESOURCE_METADATA_ID_KEY); + } + + public String getResourceType() { + List header = getMetadata(RESOURCE_METADATA_TYPE_KEY); + if (header != null && header.isEmpty() == false) { + assert header.size() == 1; + return header.get(0); + } + return null; + } + + // lower cases and adds underscores to transitions in a name + private static String toUnderscoreCase(String value) { + StringBuilder sb = new StringBuilder(); + boolean changed = false; + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (Character.isUpperCase(c)) { + if (!changed) { + // copy it over here + for (int j = 0; j < i; j++) { + sb.append(value.charAt(j)); + } + changed = true; + if (i == 0) { + sb.append(Character.toLowerCase(c)); + } else { + sb.append('_'); + sb.append(Character.toLowerCase(c)); + } + } else { + sb.append('_'); + sb.append(Character.toLowerCase(c)); + } + } else { + if (changed) { + sb.append(c); + } + } + } + if (!changed) { + return value; + } + return sb.toString(); + } + + /** + * Returns an array of all registered handle IDs. These are the IDs for every registered + * exception. + * + * @return an array of all registered handle IDs + */ + static int[] ids() { + return OpenSearchExceptionHandleRegistry.ids().stream().mapToInt(i -> i).toArray(); + } + + /** + * Returns an array of all registered pairs of handle IDs and exception classes. These pairs are + * provided for every registered exception. + * + * @return an array of all registered pairs of handle IDs and exception classes + */ + @SuppressWarnings("unchecked") + static Tuple>[] classes() { + final Tuple>[] ts = OpenSearchExceptionHandleRegistry.handles() + .stream() + .map(h -> Tuple.tuple(h.id, h.exceptionClass)) + .toArray(Tuple[]::new); + return ts; + } + + public Index getIndex() { + List index = getMetadata(INDEX_METADATA_KEY); + if (index != null && index.isEmpty() == false) { + List index_uuid = getMetadata(INDEX_METADATA_KEY_UUID); + return new Index(index.get(0), index_uuid.get(0)); + } + + return null; + } + + public void setIndex(Index index) { + if (index != null) { + addMetadata(INDEX_METADATA_KEY, index.getName()); + addMetadata(INDEX_METADATA_KEY_UUID, index.getUUID()); + } + } + + public void setIndex(String index) { + if (index != null) { + setIndex(new Index(index, Strings.UNKNOWN_UUID_VALUE)); + } + } + + public ShardId getShardId() { + List shard = getMetadata(SHARD_METADATA_KEY); + if (shard != null && shard.isEmpty() == false) { + return new ShardId(getIndex(), Integer.parseInt(shard.get(0))); + } + return null; + } + + public void setShard(ShardId shardId) { + if (shardId != null) { + setIndex(shardId.getIndex()); + addMetadata(SHARD_METADATA_KEY, Integer.toString(shardId.id())); + } + } + + /** + * This is the list of Exceptions OpenSearch can throw over the wire or save into a corruption marker. Each value in the enum is a + * single exception tying the Class to an id for use of the encode side and the id back to a constructor for use on the decode side. As + * such its ok if the exceptions to change names so long as their constructor can still read the exception. Each exception is listed + * in id order. If you want to remove an exception leave a tombstone comment and mark the id as null in + * ExceptionSerializationTests.testIds.ids. + * + * @opensearch.internal + */ + protected static class OpenSearchExceptionHandle { + final Class exceptionClass; + final CheckedFunction constructor; + final int id; + final Version versionAdded; + + OpenSearchExceptionHandle( + Class exceptionClass, + CheckedFunction constructor, + int id, + Version versionAdded + ) { + // We need the exceptionClass because you can't dig it out of the constructor reliably. + this.exceptionClass = exceptionClass; + this.constructor = constructor; + this.versionAdded = versionAdded; + this.id = id; + } } /** diff --git a/libs/core/src/main/java/org/opensearch/action/support/DefaultShardOperationFailedException.java b/libs/core/src/main/java/org/opensearch/action/support/DefaultShardOperationFailedException.java index 3f958a50661bd..71f0980e56d4b 100644 --- a/libs/core/src/main/java/org/opensearch/action/support/DefaultShardOperationFailedException.java +++ b/libs/core/src/main/java/org/opensearch/action/support/DefaultShardOperationFailedException.java @@ -32,7 +32,7 @@ package org.opensearch.action.support; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.action.ShardOperationFailedException; import org.opensearch.core.ParseField; @@ -46,7 +46,7 @@ import java.io.IOException; -import static org.opensearch.BaseExceptionsHelper.detailedMessage; +import static org.opensearch.ExceptionsHelper.detailedMessage; import static org.opensearch.core.xcontent.ConstructingObjectParser.constructorArg; /** @@ -93,7 +93,7 @@ public DefaultShardOperationFailedException(OpenSearchException e) { } public DefaultShardOperationFailedException(String index, int shardId, Throwable cause) { - super(index, shardId, BaseExceptionsHelper.detailedMessage(cause), BaseExceptionsHelper.status(cause), cause); + super(index, shardId, ExceptionsHelper.detailedMessage(cause), ExceptionsHelper.status(cause), cause); } public static DefaultShardOperationFailedException readShardOperationFailed(StreamInput in) throws IOException { @@ -135,7 +135,7 @@ protected XContentBuilder innerToXContent(XContentBuilder builder, Params params builder.field("status", status.name()); if (reason != null) { builder.startObject("reason"); - BaseExceptionsHelper.generateThrowableXContent(builder, params, cause); + OpenSearchException.generateThrowableXContent(builder, params, cause); builder.endObject(); } return builder; diff --git a/libs/core/src/main/java/org/opensearch/common/io/stream/NotSerializableExceptionWrapper.java b/libs/core/src/main/java/org/opensearch/common/io/stream/NotSerializableExceptionWrapper.java index 590f9c2a03d57..967957afc8c20 100644 --- a/libs/core/src/main/java/org/opensearch/common/io/stream/NotSerializableExceptionWrapper.java +++ b/libs/core/src/main/java/org/opensearch/common/io/stream/NotSerializableExceptionWrapper.java @@ -32,7 +32,7 @@ package org.opensearch.common.io.stream; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.rest.RestStatus; @@ -53,9 +53,9 @@ public final class NotSerializableExceptionWrapper extends OpenSearchException { private final RestStatus status; public NotSerializableExceptionWrapper(Throwable other) { - super(BaseExceptionsHelper.getExceptionName(other) + ": " + other.getMessage(), other.getCause()); - this.name = BaseExceptionsHelper.getExceptionName(other); - this.status = BaseExceptionsHelper.status(other); + super(OpenSearchException.getExceptionName(other) + ": " + other.getMessage(), other.getCause()); + this.name = OpenSearchException.getExceptionName(other); + this.status = ExceptionsHelper.status(other); setStackTrace(other.getStackTrace()); for (Throwable otherSuppressed : other.getSuppressed()) { addSuppressed(otherSuppressed); diff --git a/modules/geo/src/test/java/org/opensearch/geo/search/aggregations/bucket/geogrid/GeoTileGridParserTests.java b/modules/geo/src/test/java/org/opensearch/geo/search/aggregations/bucket/geogrid/GeoTileGridParserTests.java index a39f66f571d0a..0bf41f37c45a7 100644 --- a/modules/geo/src/test/java/org/opensearch/geo/search/aggregations/bucket/geogrid/GeoTileGridParserTests.java +++ b/modules/geo/src/test/java/org/opensearch/geo/search/aggregations/bucket/geogrid/GeoTileGridParserTests.java @@ -31,7 +31,7 @@ package org.opensearch.geo.search.aggregations.bucket.geogrid; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.core.xcontent.XContentParseException; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.json.JsonXContent; @@ -77,7 +77,7 @@ public void testParseErrorOnBooleanPrecision() throws Exception { () -> GeoTileGridAggregationBuilder.PARSER.parse(stParser, "geotile_grid") ); assertThat( - BaseExceptionsHelper.detailedMessage(e), + ExceptionsHelper.detailedMessage(e), containsString("[geotile_grid] precision doesn't support values of type: VALUE_BOOLEAN") ); } diff --git a/modules/reindex/src/test/java/org/opensearch/index/reindex/AsyncBulkByScrollActionTests.java b/modules/reindex/src/test/java/org/opensearch/index/reindex/AsyncBulkByScrollActionTests.java index e11ad3b5013c1..61336156a83d0 100644 --- a/modules/reindex/src/test/java/org/opensearch/index/reindex/AsyncBulkByScrollActionTests.java +++ b/modules/reindex/src/test/java/org/opensearch/index/reindex/AsyncBulkByScrollActionTests.java @@ -33,7 +33,6 @@ package org.opensearch.index.reindex; import org.apache.lucene.search.TotalHits; -import org.opensearch.BaseExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.ExceptionsHelper; import org.opensearch.Version; @@ -216,7 +215,7 @@ public void testStartRetriesOnRejectionButFailsOnTooManyRejections() throws Exce assertBusy(() -> assertEquals(testRequest.getMaxRetries() + 1, client.searchAttempts.get())); assertBusy(() -> assertTrue(listener.isDone())); ExecutionException e = expectThrows(ExecutionException.class, () -> listener.get()); - assertThat(BaseExceptionsHelper.stackTrace(e), containsString(OpenSearchRejectedExecutionException.class.getSimpleName())); + assertThat(ExceptionsHelper.stackTrace(e), containsString(OpenSearchRejectedExecutionException.class.getSimpleName())); assertNull("There shouldn't be a search attempt pending that we didn't reject", client.lastSearch.get()); assertEquals(testRequest.getMaxRetries(), testTask.getStatus().getSearchRetries()); } diff --git a/server/src/internalClusterTest/java/org/opensearch/action/RejectionActionIT.java b/server/src/internalClusterTest/java/org/opensearch/action/RejectionActionIT.java index f2f55b238ab7c..bda24b48b7f10 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/RejectionActionIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/RejectionActionIT.java @@ -32,7 +32,7 @@ package org.opensearch.action; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.search.SearchPhaseExecutionException; import org.opensearch.action.search.SearchResponse; import org.opensearch.action.search.SearchType; @@ -105,7 +105,7 @@ public void onFailure(Exception e) { } } else { Exception t = (Exception) response; - Throwable unwrap = BaseExceptionsHelper.unwrapCause(t); + Throwable unwrap = ExceptionsHelper.unwrapCause(t); if (unwrap instanceof SearchPhaseExecutionException) { SearchPhaseExecutionException e = (SearchPhaseExecutionException) unwrap; for (ShardSearchFailure failure : e.shardFailures()) { diff --git a/server/src/internalClusterTest/java/org/opensearch/action/search/TransportSearchIT.java b/server/src/internalClusterTest/java/org/opensearch/action/search/TransportSearchIT.java index 895d7ebea88b6..8cd7bdeb0c822 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/search/TransportSearchIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/search/TransportSearchIT.java @@ -36,7 +36,7 @@ import org.apache.lucene.search.CollectionTerminatedException; import org.apache.lucene.search.ScoreMode; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.ActionListener; import org.opensearch.action.admin.cluster.node.stats.NodeStats; import org.opensearch.action.admin.cluster.node.stats.NodesStatsRequest; @@ -415,7 +415,7 @@ public void onFailure(Exception e) { SearchPhaseExecutionException.class, () -> client.prepareSearch("test").addAggregation(new TestAggregationBuilder("test")).get() ); - assertThat(BaseExceptionsHelper.unwrapCause(exc).getCause().getMessage(), containsString("")); + assertThat(ExceptionsHelper.unwrapCause(exc).getCause().getMessage(), containsString("")); }); final AtomicArray exceptions = new AtomicArray<>(10); @@ -443,7 +443,7 @@ public void onFailure(Exception exc) { latch.await(); assertThat(exceptions.asList().size(), equalTo(10)); for (Exception exc : exceptions.asList()) { - assertThat(BaseExceptionsHelper.unwrapCause(exc).getCause().getMessage(), containsString("")); + assertThat(ExceptionsHelper.unwrapCause(exc).getCause().getMessage(), containsString("")); } assertBusy(() -> assertThat(requestBreakerUsed(), equalTo(0L))); } finally { @@ -482,7 +482,7 @@ public void onFailure(Exception exc) { latch.await(); assertThat(exceptions.asList().size(), equalTo(10)); for (Exception exc : exceptions.asList()) { - assertThat(BaseExceptionsHelper.unwrapCause(exc).getCause().getMessage(), containsString("boom")); + assertThat(ExceptionsHelper.unwrapCause(exc).getCause().getMessage(), containsString("boom")); } assertBusy(() -> assertThat(requestBreakerUsed(), equalTo(0L))); } diff --git a/server/src/internalClusterTest/java/org/opensearch/blocks/SimpleBlocksIT.java b/server/src/internalClusterTest/java/org/opensearch/blocks/SimpleBlocksIT.java index 872da7bb12b8e..8ede3e25b2e1a 100644 --- a/server/src/internalClusterTest/java/org/opensearch/blocks/SimpleBlocksIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/blocks/SimpleBlocksIT.java @@ -32,7 +32,7 @@ package org.opensearch.blocks; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.ActionRequestValidationException; import org.opensearch.action.admin.indices.create.CreateIndexResponse; import org.opensearch.action.admin.indices.exists.indices.IndicesExistsResponse; @@ -428,7 +428,7 @@ public void testAddBlockWhileIndexingDocuments() throws Exception { try { try (BackgroundIndexer indexer = new BackgroundIndexer(indexName, "_doc", client(), 1000)) { indexer.setFailureAssertion(t -> { - Throwable cause = BaseExceptionsHelper.unwrapCause(t); + Throwable cause = ExceptionsHelper.unwrapCause(t); assertThat(cause, instanceOf(ClusterBlockException.class)); ClusterBlockException e = (ClusterBlockException) cause; assertThat(e.blocks(), hasSize(1)); @@ -474,7 +474,7 @@ public void testAddBlockWhileDeletingIndices() throws Exception { final APIBlock block = randomAddableBlock(); Consumer exceptionConsumer = t -> { - Throwable cause = BaseExceptionsHelper.unwrapCause(t); + Throwable cause = ExceptionsHelper.unwrapCause(t); if (cause instanceof ClusterBlockException) { ClusterBlockException e = (ClusterBlockException) cause; assertThat(e.blocks(), hasSize(1)); diff --git a/server/src/internalClusterTest/java/org/opensearch/indices/memory/breaker/CircuitBreakerServiceIT.java b/server/src/internalClusterTest/java/org/opensearch/indices/memory/breaker/CircuitBreakerServiceIT.java index 6ef3848cec9bb..2dc6b2085b866 100644 --- a/server/src/internalClusterTest/java/org/opensearch/indices/memory/breaker/CircuitBreakerServiceIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/indices/memory/breaker/CircuitBreakerServiceIT.java @@ -32,7 +32,7 @@ package org.opensearch.indices.memory.breaker; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.admin.cluster.node.stats.NodeStats; import org.opensearch.action.admin.cluster.node.stats.NodesStatsResponse; import org.opensearch.action.bulk.BulkItemResponse; @@ -421,7 +421,7 @@ public void testLimitsRequestSize() { } else { // each item must have failed with CircuitBreakingException for (BulkItemResponse bulkItemResponse : response) { - Throwable cause = BaseExceptionsHelper.unwrapCause(bulkItemResponse.getFailure().getCause()); + Throwable cause = ExceptionsHelper.unwrapCause(bulkItemResponse.getFailure().getCause()); assertThat(cause, instanceOf(CircuitBreakingException.class)); assertEquals(((CircuitBreakingException) cause).getByteLimit(), inFlightRequestsLimit.getBytes()); } diff --git a/server/src/internalClusterTest/java/org/opensearch/indices/state/CloseIndexIT.java b/server/src/internalClusterTest/java/org/opensearch/indices/state/CloseIndexIT.java index 995f11bcd79c6..28bd5a6ae252d 100644 --- a/server/src/internalClusterTest/java/org/opensearch/indices/state/CloseIndexIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/indices/state/CloseIndexIT.java @@ -32,7 +32,7 @@ package org.opensearch.indices.state; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.ActionRequestValidationException; import org.opensearch.action.admin.indices.close.CloseIndexRequestBuilder; import org.opensearch.action.admin.indices.close.CloseIndexResponse; @@ -647,7 +647,7 @@ static void assertIndexIsOpened(final String... indices) { } static void assertException(final Throwable throwable, final String indexName) { - final Throwable t = BaseExceptionsHelper.unwrapCause(throwable); + final Throwable t = ExceptionsHelper.unwrapCause(throwable); if (t instanceof ClusterBlockException) { ClusterBlockException clusterBlockException = (ClusterBlockException) t; assertThat(clusterBlockException.blocks(), hasSize(1)); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/DerivativeIT.java b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/DerivativeIT.java index eb6153493323c..406c57d044259 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/DerivativeIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/DerivativeIT.java @@ -32,7 +32,7 @@ package org.opensearch.search.aggregations.pipeline; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.index.IndexRequestBuilder; import org.opensearch.action.search.SearchPhaseExecutionException; import org.opensearch.action.search.SearchResponse; @@ -639,7 +639,7 @@ public void testSingleValueAggDerivative_invalidPath() throws Exception { .get(); fail("Expected an Exception but didn't get one"); } catch (Exception e) { - Throwable cause = BaseExceptionsHelper.unwrapCause(e); + Throwable cause = ExceptionsHelper.unwrapCause(e); if (cause == null) { throw e; } else if (cause instanceof SearchPhaseExecutionException) { diff --git a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/ExtendedStatsBucketIT.java b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/ExtendedStatsBucketIT.java index fc4a2908ae563..85fe794b05fc6 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/ExtendedStatsBucketIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/ExtendedStatsBucketIT.java @@ -32,7 +32,7 @@ package org.opensearch.search.aggregations.pipeline; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.index.IndexRequestBuilder; import org.opensearch.action.search.SearchPhaseExecutionException; import org.opensearch.action.search.SearchResponse; @@ -489,7 +489,7 @@ public void testBadSigmaAsSubAgg() throws Exception { ) .get() ); - Throwable cause = BaseExceptionsHelper.unwrapCause(ex); + Throwable cause = ExceptionsHelper.unwrapCause(ex); if (cause == null) { throw ex; } else if (cause instanceof SearchPhaseExecutionException) { diff --git a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/PercentilesBucketIT.java b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/PercentilesBucketIT.java index 4d7fa05ba5043..1da079781dc63 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/PercentilesBucketIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/PercentilesBucketIT.java @@ -32,7 +32,7 @@ package org.opensearch.search.aggregations.pipeline; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.index.IndexRequestBuilder; import org.opensearch.action.search.SearchPhaseExecutionException; import org.opensearch.action.search.SearchResponse; @@ -439,7 +439,7 @@ public void testBadPercents() throws Exception { fail("Illegal percent's were provided but no exception was thrown."); } catch (Exception e) { - Throwable cause = BaseExceptionsHelper.unwrapCause(e); + Throwable cause = ExceptionsHelper.unwrapCause(e); if (cause == null) { throw e; } else if (cause instanceof SearchPhaseExecutionException) { @@ -474,7 +474,7 @@ public void testBadPercents_asSubAgg() throws Exception { fail("Illegal percent's were provided but no exception was thrown."); } catch (Exception e) { - Throwable cause = BaseExceptionsHelper.unwrapCause(e); + Throwable cause = ExceptionsHelper.unwrapCause(e); if (cause == null) { throw e; } else if (cause instanceof SearchPhaseExecutionException) { diff --git a/server/src/internalClusterTest/java/org/opensearch/snapshots/SharedClusterSnapshotRestoreIT.java b/server/src/internalClusterTest/java/org/opensearch/snapshots/SharedClusterSnapshotRestoreIT.java index 767fd5ea8fde3..9736aba92f3d1 100644 --- a/server/src/internalClusterTest/java/org/opensearch/snapshots/SharedClusterSnapshotRestoreIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/snapshots/SharedClusterSnapshotRestoreIT.java @@ -34,7 +34,7 @@ import org.apache.lucene.util.BytesRef; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.Version; import org.opensearch.action.ActionFuture; @@ -1986,7 +1986,7 @@ public void testSnapshotSucceedsAfterSnapshotFailure() throws Exception { } } catch (SnapshotException | RepositoryException ex) { // sometimes, the snapshot will fail with a top level I/O exception - assertThat(BaseExceptionsHelper.stackTrace(ex), containsString("Random IOException")); + assertThat(ExceptionsHelper.stackTrace(ex), containsString("Random IOException")); } logger.info("--> snapshot with no I/O failures"); diff --git a/server/src/main/java/org/opensearch/OpenSearchSecurityException.java b/server/src/main/java/org/opensearch/OpenSearchSecurityException.java index c663dc0822cfd..6f725573e71ce 100644 --- a/server/src/main/java/org/opensearch/OpenSearchSecurityException.java +++ b/server/src/main/java/org/opensearch/OpenSearchSecurityException.java @@ -53,7 +53,7 @@ public OpenSearchSecurityException(String msg, RestStatus status, Throwable caus * Build the exception with the status derived from the cause. */ public OpenSearchSecurityException(String msg, Exception cause, Object... args) { - this(msg, BaseExceptionsHelper.status(cause), cause, args); + this(msg, ExceptionsHelper.status(cause), cause, args); } /** diff --git a/server/src/main/java/org/opensearch/action/TaskOperationFailure.java b/server/src/main/java/org/opensearch/action/TaskOperationFailure.java index ea6f5508ab332..25e1ab1bb3d6f 100644 --- a/server/src/main/java/org/opensearch/action/TaskOperationFailure.java +++ b/server/src/main/java/org/opensearch/action/TaskOperationFailure.java @@ -32,7 +32,7 @@ package org.opensearch.action; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.core.ParseField; import org.opensearch.common.io.stream.StreamInput; @@ -90,7 +90,7 @@ public TaskOperationFailure(String nodeId, long taskId, Exception e) { this.nodeId = nodeId; this.taskId = taskId; this.reason = e; - status = BaseExceptionsHelper.status(e); + status = ExceptionsHelper.status(e); } /** @@ -144,7 +144,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws if (reason != null) { builder.field(REASON); builder.startObject(); - BaseExceptionsHelper.generateThrowableXContent(builder, params, reason); + OpenSearchException.generateThrowableXContent(builder, params, reason); builder.endObject(); } return builder; diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/node/reload/NodesReloadSecureSettingsResponse.java b/server/src/main/java/org/opensearch/action/admin/cluster/node/reload/NodesReloadSecureSettingsResponse.java index 874f6c9f13ac7..f6d9a5c7b6453 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/node/reload/NodesReloadSecureSettingsResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/node/reload/NodesReloadSecureSettingsResponse.java @@ -32,7 +32,7 @@ package org.opensearch.action.admin.cluster.node.reload; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.OpenSearchException; import org.opensearch.action.FailedNodeException; import org.opensearch.action.support.nodes.BaseNodeResponse; import org.opensearch.action.support.nodes.BaseNodesResponse; @@ -83,7 +83,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws final Exception e = node.reloadException(); if (e != null) { builder.startObject("reload_exception"); - BaseExceptionsHelper.generateThrowableXContent(builder, params, e); + OpenSearchException.generateThrowableXContent(builder, params, e); builder.endObject(); } builder.endObject(); diff --git a/server/src/main/java/org/opensearch/action/admin/indices/shards/IndicesShardStoresResponse.java b/server/src/main/java/org/opensearch/action/admin/indices/shards/IndicesShardStoresResponse.java index 6d1525c6b671b..01321bb09323d 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/shards/IndicesShardStoresResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/shards/IndicesShardStoresResponse.java @@ -33,7 +33,7 @@ package org.opensearch.action.admin.indices.shards; import com.carrotsearch.hppc.cursors.IntObjectCursor; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.OpenSearchException; import org.opensearch.action.ActionResponse; import org.opensearch.action.support.DefaultShardOperationFailedException; import org.opensearch.cluster.node.DiscoveryNode; @@ -202,7 +202,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws builder.field(Fields.ALLOCATED, allocationStatus.value()); if (storeException != null) { builder.startObject(Fields.STORE_EXCEPTION); - BaseExceptionsHelper.generateThrowableXContent(builder, params, storeException); + OpenSearchException.generateThrowableXContent(builder, params, storeException); builder.endObject(); } return builder; diff --git a/server/src/main/java/org/opensearch/action/bulk/BulkItemResponse.java b/server/src/main/java/org/opensearch/action/bulk/BulkItemResponse.java index f5e8967d81c53..c712a18e85013 100644 --- a/server/src/main/java/org/opensearch/action/bulk/BulkItemResponse.java +++ b/server/src/main/java/org/opensearch/action/bulk/BulkItemResponse.java @@ -32,7 +32,7 @@ package org.opensearch.action.bulk; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.Version; import org.opensearch.action.DocWriteRequest.OpType; @@ -94,7 +94,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws builder.field(_ID, failure.getId()); builder.field(STATUS, failure.getStatus().getStatus()); builder.startObject(ERROR); - BaseExceptionsHelper.generateThrowableXContent(builder, params, failure.getCause()); + OpenSearchException.generateThrowableXContent(builder, params, failure.getCause()); builder.endObject(); } builder.endObject(); @@ -218,7 +218,7 @@ public Failure(String index, String id, Exception cause) { index, id, cause, - BaseExceptionsHelper.status(cause), + ExceptionsHelper.status(cause), SequenceNumbers.UNASSIGNED_SEQ_NO, SequenceNumbers.UNASSIGNED_PRIMARY_TERM, false @@ -230,7 +230,7 @@ public Failure(String index, String id, Exception cause, boolean aborted) { index, id, cause, - BaseExceptionsHelper.status(cause), + ExceptionsHelper.status(cause), SequenceNumbers.UNASSIGNED_SEQ_NO, SequenceNumbers.UNASSIGNED_PRIMARY_TERM, aborted @@ -243,7 +243,7 @@ public Failure(String index, String id, Exception cause, RestStatus status) { /** For write failures after operation was assigned a sequence number. */ public Failure(String index, String id, Exception cause, long seqNo, long term) { - this(index, id, cause, BaseExceptionsHelper.status(cause), seqNo, term, false); + this(index, id, cause, ExceptionsHelper.status(cause), seqNo, term, false); } private Failure(String index, String id, Exception cause, RestStatus status, long seqNo, long term, boolean aborted) { @@ -268,7 +268,7 @@ public Failure(StreamInput in) throws IOException { } id = in.readOptionalString(); cause = in.readException(); - status = BaseExceptionsHelper.status(cause); + status = ExceptionsHelper.status(cause); seqNo = in.readZLong(); term = in.readVLong(); aborted = in.readBoolean(); @@ -356,7 +356,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws builder.field(ID_FIELD, id); } builder.startObject(CAUSE_FIELD); - BaseExceptionsHelper.generateThrowableXContent(builder, params, cause); + OpenSearchException.generateThrowableXContent(builder, params, cause); builder.endObject(); builder.field(STATUS_FIELD, status.getStatus()); return builder; diff --git a/server/src/main/java/org/opensearch/action/bulk/TransportBulkAction.java b/server/src/main/java/org/opensearch/action/bulk/TransportBulkAction.java index fe9d0f21e01b2..ed407550b8b2f 100644 --- a/server/src/main/java/org/opensearch/action/bulk/TransportBulkAction.java +++ b/server/src/main/java/org/opensearch/action/bulk/TransportBulkAction.java @@ -35,7 +35,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.lucene.util.SparseFixedBitSet; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.core.Assertions; import org.opensearch.OpenSearchParseException; import org.opensearch.ResourceAlreadyExistsException; @@ -325,7 +325,7 @@ protected void doRun() { @Override public void onFailure(Exception e) { - if (!(BaseExceptionsHelper.unwrapCause(e) instanceof ResourceAlreadyExistsException)) { + if (!(ExceptionsHelper.unwrapCause(e) instanceof ResourceAlreadyExistsException)) { // fail all requests involving this index, if create didn't work for (int i = 0; i < bulkRequest.requests.size(); i++) { DocWriteRequest request = bulkRequest.requests.get(i); diff --git a/server/src/main/java/org/opensearch/action/bulk/TransportShardBulkAction.java b/server/src/main/java/org/opensearch/action/bulk/TransportShardBulkAction.java index ff9226e5e6317..cbb30714ee8e1 100644 --- a/server/src/main/java/org/opensearch/action/bulk/TransportShardBulkAction.java +++ b/server/src/main/java/org/opensearch/action/bulk/TransportShardBulkAction.java @@ -36,7 +36,7 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.util.MessageSupplier; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.ActionListener; import org.opensearch.action.ActionListenerResponseHandler; import org.opensearch.action.ActionRunnable; @@ -719,7 +719,7 @@ && isConflictException(executionResult.getFailure().getCause()) } private static boolean isConflictException(final Exception e) { - return BaseExceptionsHelper.unwrapCause(e) instanceof VersionConflictEngineException; + return ExceptionsHelper.unwrapCause(e) instanceof VersionConflictEngineException; } /** diff --git a/server/src/main/java/org/opensearch/action/search/MultiSearchResponse.java b/server/src/main/java/org/opensearch/action/search/MultiSearchResponse.java index c00eb572b6ac4..b6c30b6be00c9 100644 --- a/server/src/main/java/org/opensearch/action/search/MultiSearchResponse.java +++ b/server/src/main/java/org/opensearch/action/search/MultiSearchResponse.java @@ -32,7 +32,7 @@ package org.opensearch.action.search; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.action.ActionResponse; import org.opensearch.common.Nullable; @@ -192,7 +192,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws builder.startObject(); if (item.isFailure()) { OpenSearchException.generateFailureXContent(builder, params, item.getFailure(), true); - builder.field(Fields.STATUS, BaseExceptionsHelper.status(item.getFailure()).getStatus()); + builder.field(Fields.STATUS, ExceptionsHelper.status(item.getFailure()).getStatus()); } else { item.getResponse().innerToXContent(builder, params); builder.field(Fields.STATUS, item.getResponse().status().getStatus()); diff --git a/server/src/main/java/org/opensearch/action/search/SearchPhaseExecutionException.java b/server/src/main/java/org/opensearch/action/search/SearchPhaseExecutionException.java index aead19afc2942..65c876cbd7c61 100644 --- a/server/src/main/java/org/opensearch/action/search/SearchPhaseExecutionException.java +++ b/server/src/main/java/org/opensearch/action/search/SearchPhaseExecutionException.java @@ -32,7 +32,6 @@ package org.opensearch.action.search; -import org.opensearch.BaseExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.ExceptionsHelper; import org.opensearch.action.ShardOperationFailedException; @@ -100,7 +99,7 @@ public RestStatus status() { if (shardFailures.length == 0) { // if no successful shards, the failure can be due to OpenSearchRejectedExecutionException during fetch phase // on coordinator node. so get the status from cause instead of returning SERVICE_UNAVAILABLE blindly - return getCause() == null ? RestStatus.SERVICE_UNAVAILABLE : BaseExceptionsHelper.status(getCause()); + return getCause() == null ? RestStatus.SERVICE_UNAVAILABLE : ExceptionsHelper.status(getCause()); } RestStatus status = shardFailures[0].status(); if (shardFailures.length > 1) { @@ -160,14 +159,14 @@ protected void metadataToXContent(XContentBuilder builder, Params params) throws @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - Throwable ex = BaseExceptionsHelper.unwrapCause(this); + Throwable ex = ExceptionsHelper.unwrapCause(this); if (ex != this) { - BaseExceptionsHelper.generateThrowableXContent(builder, params, this); + OpenSearchException.generateThrowableXContent(builder, params, this); } else { // We don't have a cause when all shards failed, but we do have shards failures so we can "guess" a cause // (see {@link #getCause()}). Here, we use super.getCause() because we don't want the guessed exception to // be rendered twice (one in the "cause" field, one in "failed_shards") - BaseExceptionsHelper.innerToXContent( + OpenSearchException.innerToXContent( builder, params, this, diff --git a/server/src/main/java/org/opensearch/action/search/ShardSearchFailure.java b/server/src/main/java/org/opensearch/action/search/ShardSearchFailure.java index aafdd553d4522..891f7f3119541 100644 --- a/server/src/main/java/org/opensearch/action/search/ShardSearchFailure.java +++ b/server/src/main/java/org/opensearch/action/search/ShardSearchFailure.java @@ -32,7 +32,7 @@ package org.opensearch.action.search; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.action.OriginalIndices; import org.opensearch.action.ShardOperationFailedException; @@ -85,15 +85,15 @@ public ShardSearchFailure(Exception e) { } public ShardSearchFailure(Exception e, @Nullable SearchShardTarget shardTarget) { - this(e, BaseExceptionsHelper.unwrapCause(e), shardTarget); + this(e, ExceptionsHelper.unwrapCause(e), shardTarget); } private ShardSearchFailure(final Exception e, final Throwable unwrappedCause, @Nullable SearchShardTarget shardTarget) { super( shardTarget == null ? null : shardTarget.getFullyQualifiedIndexName(), shardTarget == null ? -1 : shardTarget.getShardId().getId(), - BaseExceptionsHelper.detailedMessage(e), - BaseExceptionsHelper.status(unwrappedCause), + ExceptionsHelper.detailedMessage(e), + ExceptionsHelper.status(unwrappedCause), unwrappedCause ); @@ -119,7 +119,7 @@ public String toString() { + "], reason [" + reason + "], cause [" - + (cause == null ? "_na" : BaseExceptionsHelper.stackTrace(cause)) + + (cause == null ? "_na" : ExceptionsHelper.stackTrace(cause)) + "]"; } @@ -147,7 +147,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws } builder.field(REASON_FIELD); builder.startObject(); - BaseExceptionsHelper.generateThrowableXContent(builder, params, cause); + OpenSearchException.generateThrowableXContent(builder, params, cause); builder.endObject(); } builder.endObject(); diff --git a/server/src/main/java/org/opensearch/action/support/TransportActions.java b/server/src/main/java/org/opensearch/action/support/TransportActions.java index 62059ca3f0754..03e7509b3b8e3 100644 --- a/server/src/main/java/org/opensearch/action/support/TransportActions.java +++ b/server/src/main/java/org/opensearch/action/support/TransportActions.java @@ -33,7 +33,7 @@ package org.opensearch.action.support; import org.apache.lucene.store.AlreadyClosedException; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.NoShardAvailableActionException; import org.opensearch.action.UnavailableShardsException; import org.opensearch.index.IndexNotFoundException; @@ -48,7 +48,7 @@ public class TransportActions { public static boolean isShardNotAvailableException(final Throwable e) { - final Throwable actual = BaseExceptionsHelper.unwrapCause(e); + final Throwable actual = ExceptionsHelper.unwrapCause(e); return (actual instanceof ShardNotFoundException || actual instanceof IndexNotFoundException || actual instanceof IllegalIndexShardStateException diff --git a/server/src/main/java/org/opensearch/action/support/replication/ReplicationOperation.java b/server/src/main/java/org/opensearch/action/support/replication/ReplicationOperation.java index 968feca583d07..a7c7a799883a6 100644 --- a/server/src/main/java/org/opensearch/action/support/replication/ReplicationOperation.java +++ b/server/src/main/java/org/opensearch/action/support/replication/ReplicationOperation.java @@ -34,7 +34,7 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.lucene.store.AlreadyClosedException; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.core.Assertions; import org.opensearch.OpenSearchException; import org.opensearch.action.ActionListener; @@ -284,7 +284,7 @@ public void onFailure(Exception replicaException) { // Only report "critical" exceptions // TODO: Reach out to the cluster-manager node to get the latest shard state then report. if (TransportActions.isShardNotAvailableException(replicaException) == false) { - RestStatus restStatus = BaseExceptionsHelper.status(replicaException); + RestStatus restStatus = ExceptionsHelper.status(replicaException); shardReplicaFailures.add( new ReplicationResponse.ShardInfo.Failure( shard.shardId(), @@ -333,7 +333,7 @@ public void onFinished() { @Override public boolean shouldRetry(Exception e) { - final Throwable cause = BaseExceptionsHelper.unwrapCause(e); + final Throwable cause = ExceptionsHelper.unwrapCause(e); return cause instanceof CircuitBreakingException || cause instanceof OpenSearchRejectedExecutionException || cause instanceof ConnectTransportException; @@ -358,7 +358,7 @@ private void updateCheckPoints(ShardRouting shard, LongSupplier localCheckpointS } private void onNoLongerPrimary(Exception failure) { - final Throwable cause = BaseExceptionsHelper.unwrapCause(failure); + final Throwable cause = ExceptionsHelper.unwrapCause(failure); final boolean nodeIsClosing = cause instanceof NodeClosedException; final String message; if (nodeIsClosing) { diff --git a/server/src/main/java/org/opensearch/action/support/replication/ReplicationResponse.java b/server/src/main/java/org/opensearch/action/support/replication/ReplicationResponse.java index 1b3b72d45b5b5..6f8f93ccc0ce3 100644 --- a/server/src/main/java/org/opensearch/action/support/replication/ReplicationResponse.java +++ b/server/src/main/java/org/opensearch/action/support/replication/ReplicationResponse.java @@ -32,7 +32,7 @@ package org.opensearch.action.support.replication; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.action.ActionResponse; import org.opensearch.action.ShardOperationFailedException; @@ -261,7 +261,7 @@ public Failure(StreamInput in) throws IOException { } public Failure(ShardId shardId, @Nullable String nodeId, Exception cause, RestStatus status, boolean primary) { - super(shardId.getIndexName(), shardId.getId(), BaseExceptionsHelper.detailedMessage(cause), status, cause); + super(shardId.getIndexName(), shardId.getId(), ExceptionsHelper.detailedMessage(cause), status, cause); this.shardId = shardId; this.nodeId = nodeId; this.primary = primary; @@ -304,7 +304,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws builder.field(_NODE, nodeId); builder.field(REASON); builder.startObject(); - BaseExceptionsHelper.generateThrowableXContent(builder, params, cause); + OpenSearchException.generateThrowableXContent(builder, params, cause); builder.endObject(); builder.field(STATUS, status); builder.field(PRIMARY, primary); diff --git a/server/src/main/java/org/opensearch/action/support/replication/TransportBroadcastReplicationAction.java b/server/src/main/java/org/opensearch/action/support/replication/TransportBroadcastReplicationAction.java index e85b77eba0416..b4bacefad8ad2 100644 --- a/server/src/main/java/org/opensearch/action/support/replication/TransportBroadcastReplicationAction.java +++ b/server/src/main/java/org/opensearch/action/support/replication/TransportBroadcastReplicationAction.java @@ -33,7 +33,7 @@ package org.opensearch.action.support.replication; import com.carrotsearch.hppc.cursors.IntObjectCursor; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.ActionListener; import org.opensearch.action.support.ActionFilters; import org.opensearch.action.support.DefaultShardOperationFailedException; @@ -122,7 +122,7 @@ public void onFailure(Exception e) { shardId, null, e, - BaseExceptionsHelper.status(e), + ExceptionsHelper.status(e), true ); failures = new ReplicationResponse.ShardInfo.Failure[totalNumCopies]; diff --git a/server/src/main/java/org/opensearch/cluster/action/shard/ShardStateAction.java b/server/src/main/java/org/opensearch/cluster/action/shard/ShardStateAction.java index 853690fa1e242..002c5fd3b89db 100644 --- a/server/src/main/java/org/opensearch/cluster/action/shard/ShardStateAction.java +++ b/server/src/main/java/org/opensearch/cluster/action/shard/ShardStateAction.java @@ -35,7 +35,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; -import org.opensearch.BaseExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.ExceptionsHelper; import org.opensearch.action.ActionListener; @@ -630,7 +629,7 @@ public String toString() { components.add("primary term [" + primaryTerm + "]"); components.add("message [" + message + "]"); if (failure != null) { - components.add("failure [" + BaseExceptionsHelper.detailedMessage(failure) + "]"); + components.add("failure [" + ExceptionsHelper.detailedMessage(failure) + "]"); } components.add("markAsStale [" + markAsStale + "]"); return String.join(", ", components); diff --git a/server/src/main/java/org/opensearch/cluster/routing/UnassignedInfo.java b/server/src/main/java/org/opensearch/cluster/routing/UnassignedInfo.java index 4e48441c7a39a..45fdf7ca641de 100644 --- a/server/src/main/java/org/opensearch/cluster/routing/UnassignedInfo.java +++ b/server/src/main/java/org/opensearch/cluster/routing/UnassignedInfo.java @@ -32,7 +32,7 @@ package org.opensearch.cluster.routing; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.cluster.ClusterState; import org.opensearch.cluster.metadata.Metadata; import org.opensearch.cluster.routing.allocation.RoutingAllocation; @@ -390,7 +390,7 @@ public String getDetails() { if (message == null) { return null; } - return message + (failure == null ? "" : ", failure " + BaseExceptionsHelper.detailedMessage(failure)); + return message + (failure == null ? "" : ", failure " + ExceptionsHelper.detailedMessage(failure)); } /** diff --git a/server/src/main/java/org/opensearch/cluster/routing/allocation/FailedShard.java b/server/src/main/java/org/opensearch/cluster/routing/allocation/FailedShard.java index d08dbba3a249d..61ca0f50e93b9 100644 --- a/server/src/main/java/org/opensearch/cluster/routing/allocation/FailedShard.java +++ b/server/src/main/java/org/opensearch/cluster/routing/allocation/FailedShard.java @@ -32,7 +32,7 @@ package org.opensearch.cluster.routing.allocation; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.cluster.routing.ShardRouting; import org.opensearch.common.Nullable; @@ -62,7 +62,7 @@ public String toString() { + ", message [" + message + "], failure [" - + (failure == null ? "null" : BaseExceptionsHelper.detailedMessage(failure)) + + (failure == null ? "null" : ExceptionsHelper.detailedMessage(failure)) + "], markAsStale [" + markAsStale + "]"; diff --git a/server/src/main/java/org/opensearch/cluster/routing/allocation/NodeAllocationResult.java b/server/src/main/java/org/opensearch/cluster/routing/allocation/NodeAllocationResult.java index ab1d56cbf7a9e..d50a474838a6b 100644 --- a/server/src/main/java/org/opensearch/cluster/routing/allocation/NodeAllocationResult.java +++ b/server/src/main/java/org/opensearch/cluster/routing/allocation/NodeAllocationResult.java @@ -32,7 +32,7 @@ package org.opensearch.cluster.routing.allocation; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.OpenSearchException; import org.opensearch.cluster.node.DiscoveryNode; import org.opensearch.cluster.routing.allocation.decider.Decision; import org.opensearch.common.Nullable; @@ -300,7 +300,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws } if (storeException != null) { builder.startObject("store_exception"); - BaseExceptionsHelper.generateThrowableXContent(builder, params, storeException); + OpenSearchException.generateThrowableXContent(builder, params, storeException); builder.endObject(); } } diff --git a/server/src/main/java/org/opensearch/common/Strings.java b/server/src/main/java/org/opensearch/common/Strings.java index 0bec840a15f40..15a4b17252450 100644 --- a/server/src/main/java/org/opensearch/common/Strings.java +++ b/server/src/main/java/org/opensearch/common/Strings.java @@ -33,7 +33,7 @@ package org.opensearch.common; import org.apache.lucene.util.BytesRefBuilder; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.common.bytes.BytesReference; import org.opensearch.common.util.CollectionUtils; @@ -280,7 +280,7 @@ private static String toString(MediaType mediaType, ToXContent toXContent, ToXCo XContentBuilder builder = createBuilder(mediaType, pretty, human); builder.startObject(); builder.field("error", "error building toString out of XContent: " + e.getMessage()); - builder.field("stack_trace", BaseExceptionsHelper.stackTrace(e)); + builder.field("stack_trace", ExceptionsHelper.stackTrace(e)); builder.endObject(); return toString(builder); } catch (IOException e2) { diff --git a/server/src/main/java/org/opensearch/common/lucene/search/Queries.java b/server/src/main/java/org/opensearch/common/lucene/search/Queries.java index 13a9551d9e421..125eab9512be8 100644 --- a/server/src/main/java/org/opensearch/common/lucene/search/Queries.java +++ b/server/src/main/java/org/opensearch/common/lucene/search/Queries.java @@ -47,7 +47,7 @@ import org.apache.lucene.search.ScoreMode; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.Weight; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.OpenSearchException; import org.opensearch.common.Nullable; import org.opensearch.index.mapper.SeqNoFieldMapper; @@ -83,7 +83,7 @@ public static Query newUnmappedFieldsQuery(Collection fields) { } public static Query newLenientFieldQuery(String field, RuntimeException e) { - String message = BaseExceptionsHelper.getExceptionName(e) + ":[" + e.getMessage() + "]"; + String message = OpenSearchException.getExceptionName(e) + ":[" + e.getMessage() + "]"; return Queries.newMatchNoDocsQuery("failed [" + field + "] query, caused by " + message); } diff --git a/server/src/main/java/org/opensearch/gateway/AsyncShardFetch.java b/server/src/main/java/org/opensearch/gateway/AsyncShardFetch.java index 35272d9f54dc6..e4df2e604c320 100644 --- a/server/src/main/java/org/opensearch/gateway/AsyncShardFetch.java +++ b/server/src/main/java/org/opensearch/gateway/AsyncShardFetch.java @@ -33,7 +33,7 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchTimeoutException; import org.opensearch.action.ActionListener; import org.opensearch.action.FailedNodeException; @@ -251,7 +251,7 @@ protected synchronized void processAsyncFetch(List responses, List searchLookup) { throw new IllegalArgumentException("Fielddata is not supported on field [" + name() + "] of type [" + typeName() + "]"); @@ -412,7 +412,7 @@ public Relation isFieldWithinQuery( /** @throws IllegalArgumentException if the fielddata is not supported on this type. * An IllegalArgumentException is needed in order to return an http error 400 - * when this error occurs in a request. see: {@link BaseExceptionsHelper#status} + * when this error occurs in a request. see: {@link ExceptionsHelper#status} **/ protected final void failIfNoDocValues() { if (hasDocValues() == false) { diff --git a/server/src/main/java/org/opensearch/index/query/MoreLikeThisQueryBuilder.java b/server/src/main/java/org/opensearch/index/query/MoreLikeThisQueryBuilder.java index cc5cae168e7b6..ab711d3a0ea00 100644 --- a/server/src/main/java/org/opensearch/index/query/MoreLikeThisQueryBuilder.java +++ b/server/src/main/java/org/opensearch/index/query/MoreLikeThisQueryBuilder.java @@ -37,7 +37,6 @@ import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Query; -import org.opensearch.BaseExceptionsHelper; import org.opensearch.OpenSearchParseException; import org.opensearch.ExceptionsHelper; import org.opensearch.Version; @@ -449,7 +448,7 @@ public String toString() { toXContent(builder, EMPTY_PARAMS); return Strings.toString(builder); } catch (Exception e) { - return "{ \"error\" : \"" + BaseExceptionsHelper.detailedMessage(e) + "\"}"; + return "{ \"error\" : \"" + ExceptionsHelper.detailedMessage(e) + "\"}"; } } diff --git a/server/src/main/java/org/opensearch/index/reindex/BulkByScrollTask.java b/server/src/main/java/org/opensearch/index/reindex/BulkByScrollTask.java index be9cade4925eb..2fe0fe0259c33 100644 --- a/server/src/main/java/org/opensearch/index/reindex/BulkByScrollTask.java +++ b/server/src/main/java/org/opensearch/index/reindex/BulkByScrollTask.java @@ -32,7 +32,6 @@ package org.opensearch.index.reindex; -import org.opensearch.BaseExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.common.Nullable; import org.opensearch.core.ParseField; @@ -1000,7 +999,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws status.toXContent(builder, params); } else { builder.startObject(); - BaseExceptionsHelper.generateThrowableXContent(builder, params, exception); + OpenSearchException.generateThrowableXContent(builder, params, exception); builder.endObject(); } return builder; diff --git a/server/src/main/java/org/opensearch/index/reindex/ScrollableHitSource.java b/server/src/main/java/org/opensearch/index/reindex/ScrollableHitSource.java index 78a3835cf7b33..81560de78b336 100644 --- a/server/src/main/java/org/opensearch/index/reindex/ScrollableHitSource.java +++ b/server/src/main/java/org/opensearch/index/reindex/ScrollableHitSource.java @@ -33,7 +33,8 @@ package org.opensearch.index.reindex; import org.apache.logging.log4j.Logger; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; +import org.opensearch.OpenSearchException; import org.opensearch.action.ActionListener; import org.opensearch.action.bulk.BackoffPolicy; import org.opensearch.action.bulk.BulkItemResponse; @@ -408,7 +409,7 @@ public static class SearchFailure implements Writeable, ToXContentObject { public static final String STATUS_FIELD = BulkItemResponse.Failure.STATUS_FIELD; public SearchFailure(Throwable reason, @Nullable String index, @Nullable Integer shardId, @Nullable String nodeId) { - this(reason, index, shardId, nodeId, BaseExceptionsHelper.status(reason)); + this(reason, index, shardId, nodeId, ExceptionsHelper.status(reason)); } public SearchFailure( @@ -440,7 +441,7 @@ public SearchFailure(StreamInput in) throws IOException { index = in.readOptionalString(); shardId = in.readOptionalVInt(); nodeId = in.readOptionalString(); - status = BaseExceptionsHelper.status(reason); + status = ExceptionsHelper.status(reason); } @Override @@ -488,7 +489,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws builder.field(REASON_FIELD); { builder.startObject(); - BaseExceptionsHelper.generateThrowableXContent(builder, params, reason); + OpenSearchException.generateThrowableXContent(builder, params, reason); builder.endObject(); } builder.endObject(); diff --git a/server/src/main/java/org/opensearch/index/shard/IndexShard.java b/server/src/main/java/org/opensearch/index/shard/IndexShard.java index ec6d8a7b73c99..e368ee82b1084 100644 --- a/server/src/main/java/org/opensearch/index/shard/IndexShard.java +++ b/server/src/main/java/org/opensearch/index/shard/IndexShard.java @@ -57,7 +57,6 @@ import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.util.ThreadInterruptedException; -import org.opensearch.BaseExceptionsHelper; import org.opensearch.common.lucene.store.ByteArrayIndexInput; import org.opensearch.cluster.metadata.DataStream; import org.opensearch.core.Assertions; @@ -2213,7 +2212,7 @@ int runTranslogRecovery(Engine engine, Translog.Snapshot snapshot, Engine.Operat onOperationRecovered.run(); } catch (Exception e) { // TODO: Don't enable this leniency unless users explicitly opt-in - if (origin == Engine.Operation.Origin.LOCAL_TRANSLOG_RECOVERY && BaseExceptionsHelper.status(e) == RestStatus.BAD_REQUEST) { + if (origin == Engine.Operation.Origin.LOCAL_TRANSLOG_RECOVERY && ExceptionsHelper.status(e) == RestStatus.BAD_REQUEST) { // mainly for MapperParsingException and Failure to detect xcontent logger.info("ignoring recovery of a corrupt translog entry", e); } else { diff --git a/server/src/main/java/org/opensearch/index/shard/StoreRecovery.java b/server/src/main/java/org/opensearch/index/shard/StoreRecovery.java index 02397bc356539..a81dc96ff1145 100644 --- a/server/src/main/java/org/opensearch/index/shard/StoreRecovery.java +++ b/server/src/main/java/org/opensearch/index/shard/StoreRecovery.java @@ -42,7 +42,7 @@ import org.apache.lucene.store.FilterDirectory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.ActionListener; import org.opensearch.action.StepListener; import org.opensearch.cluster.metadata.IndexMetadata; @@ -500,7 +500,7 @@ private void internalRecoverFromStore(IndexShard indexShard) throws IndexShardRe files = Arrays.toString(store.directory().listAll()); } catch (Exception inner) { inner.addSuppressed(e); - files += " (failure=" + BaseExceptionsHelper.detailedMessage(inner) + ")"; + files += " (failure=" + ExceptionsHelper.detailedMessage(inner) + ")"; } if (indexShouldExists) { throw new IndexShardRecoveryException( diff --git a/server/src/main/java/org/opensearch/indices/recovery/PeerRecoveryTargetService.java b/server/src/main/java/org/opensearch/indices/recovery/PeerRecoveryTargetService.java index a08d3182fa156..17af529a700d9 100644 --- a/server/src/main/java/org/opensearch/indices/recovery/PeerRecoveryTargetService.java +++ b/server/src/main/java/org/opensearch/indices/recovery/PeerRecoveryTargetService.java @@ -36,7 +36,7 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.lucene.store.AlreadyClosedException; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.OpenSearchTimeoutException; import org.opensearch.action.ActionListener; @@ -679,7 +679,7 @@ private void onException(Exception e) { e ); } - Throwable cause = BaseExceptionsHelper.unwrapCause(e); + Throwable cause = ExceptionsHelper.unwrapCause(e); if (cause instanceof CancellableThreads.ExecutionCancelledException) { // this can also come from the source wrapped in a RemoteTransportException onGoingRecoveries.fail(recoveryId, new RecoveryFailedException(request, "source has canceled the recovery", cause), false); @@ -690,7 +690,7 @@ private void onException(Exception e) { cause = cause.getCause(); } // do it twice, in case we have double transport exception - cause = BaseExceptionsHelper.unwrapCause(cause); + cause = ExceptionsHelper.unwrapCause(cause); if (cause instanceof RecoveryEngineException) { // unwrap an exception that was thrown as part of the recovery cause = cause.getCause(); diff --git a/server/src/main/java/org/opensearch/indices/recovery/RetryableTransportClient.java b/server/src/main/java/org/opensearch/indices/recovery/RetryableTransportClient.java index f7d75b356d6a3..77ffd75d0148a 100644 --- a/server/src/main/java/org/opensearch/indices/recovery/RetryableTransportClient.java +++ b/server/src/main/java/org/opensearch/indices/recovery/RetryableTransportClient.java @@ -9,7 +9,7 @@ package org.opensearch.indices.recovery; import org.apache.logging.log4j.Logger; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.ActionListener; import org.opensearch.action.ActionListenerResponseHandler; import org.opensearch.action.support.RetryableAction; @@ -127,10 +127,10 @@ private static boolean retryableException(Exception e) { if (e instanceof ConnectTransportException) { return true; } else if (e instanceof SendRequestTransportException) { - final Throwable cause = BaseExceptionsHelper.unwrapCause(e); + final Throwable cause = ExceptionsHelper.unwrapCause(e); return cause instanceof ConnectTransportException; } else if (e instanceof RemoteTransportException) { - final Throwable cause = BaseExceptionsHelper.unwrapCause(e); + final Throwable cause = ExceptionsHelper.unwrapCause(e); return cause instanceof CircuitBreakingException || cause instanceof OpenSearchRejectedExecutionException; } return false; diff --git a/server/src/main/java/org/opensearch/indices/replication/SegmentReplicationTargetService.java b/server/src/main/java/org/opensearch/indices/replication/SegmentReplicationTargetService.java index 2931caa353bc6..a7e0c0ec887ab 100644 --- a/server/src/main/java/org/opensearch/indices/replication/SegmentReplicationTargetService.java +++ b/server/src/main/java/org/opensearch/indices/replication/SegmentReplicationTargetService.java @@ -11,7 +11,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.ActionListener; import org.opensearch.cluster.node.DiscoveryNode; import org.opensearch.cluster.routing.ShardRouting; @@ -444,7 +444,7 @@ public void onResponse(Void o) { @Override public void onFailure(Exception e) { - Throwable cause = BaseExceptionsHelper.unwrapCause(e); + Throwable cause = ExceptionsHelper.unwrapCause(e); if (cause instanceof CancellableThreads.ExecutionCancelledException) { if (onGoingReplications.getTarget(replicationId) != null) { IndexShard indexShard = onGoingReplications.getTarget(replicationId).indexShard(); diff --git a/server/src/main/java/org/opensearch/indices/replication/common/ReplicationTarget.java b/server/src/main/java/org/opensearch/indices/replication/common/ReplicationTarget.java index 415fb91874416..4d75ff4896706 100644 --- a/server/src/main/java/org/opensearch/indices/replication/common/ReplicationTarget.java +++ b/server/src/main/java/org/opensearch/indices/replication/common/ReplicationTarget.java @@ -10,7 +10,7 @@ import org.apache.logging.log4j.Logger; import org.apache.lucene.store.RateLimiter; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.action.ActionListener; import org.opensearch.action.support.ChannelActionListener; @@ -176,7 +176,7 @@ public void fail(ReplicationFailedException e, boolean sendShardFailure) { notifyListener(e, sendShardFailure); } finally { try { - cancellableThreads.cancel("failed" + description() + "[" + BaseExceptionsHelper.stackTrace(e) + "]"); + cancellableThreads.cancel("failed" + description() + "[" + ExceptionsHelper.stackTrace(e) + "]"); } finally { // release the initial reference. replication files will be cleaned as soon as ref count goes to zero, potentially now decRef(); diff --git a/server/src/main/java/org/opensearch/rest/BytesRestResponse.java b/server/src/main/java/org/opensearch/rest/BytesRestResponse.java index 4533b2ca9d703..3bb094bcd4ba0 100644 --- a/server/src/main/java/org/opensearch/rest/BytesRestResponse.java +++ b/server/src/main/java/org/opensearch/rest/BytesRestResponse.java @@ -36,7 +36,7 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.util.Supplier; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.OpenSearchStatusException; import org.opensearch.common.bytes.BytesArray; @@ -105,14 +105,14 @@ public BytesRestResponse(RestStatus status, String contentType, BytesReference c } public BytesRestResponse(RestChannel channel, Exception e) throws IOException { - this(channel, BaseExceptionsHelper.status(e), e); + this(channel, ExceptionsHelper.status(e), e); } public BytesRestResponse(RestChannel channel, RestStatus status, Exception e) throws IOException { ToXContent.Params params = paramsFromRequest(channel.request()); if (params.paramAsBoolean( - BaseExceptionsHelper.REST_EXCEPTION_SKIP_STACK_TRACE, - BaseExceptionsHelper.REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT + OpenSearchException.REST_EXCEPTION_SKIP_STACK_TRACE, + OpenSearchException.REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT ) && e != null) { // log exception only if it is not returned in the response Supplier messageSupplier = () -> new ParameterizedMessage( @@ -154,12 +154,9 @@ public RestStatus status() { private ToXContent.Params paramsFromRequest(RestRequest restRequest) { ToXContent.Params params = restRequest; - if (params.paramAsBoolean("error_trace", !BaseExceptionsHelper.REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT) + if (params.paramAsBoolean("error_trace", OpenSearchException.REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT == false) && false == skipStackTrace()) { - params = new ToXContent.DelegatingMapParams( - singletonMap(BaseExceptionsHelper.REST_EXCEPTION_SKIP_STACK_TRACE, "false"), - params - ); + params = new ToXContent.DelegatingMapParams(singletonMap(OpenSearchException.REST_EXCEPTION_SKIP_STACK_TRACE, "false"), params); } return params; } diff --git a/server/src/main/java/org/opensearch/search/suggest/phrase/DirectCandidateGeneratorBuilder.java b/server/src/main/java/org/opensearch/search/suggest/phrase/DirectCandidateGeneratorBuilder.java index dc75088d4c85b..afd46f1a8164c 100644 --- a/server/src/main/java/org/opensearch/search/suggest/phrase/DirectCandidateGeneratorBuilder.java +++ b/server/src/main/java/org/opensearch/search/suggest/phrase/DirectCandidateGeneratorBuilder.java @@ -40,7 +40,7 @@ import org.apache.lucene.search.spell.StringDistance; import org.apache.lucene.search.spell.SuggestMode; import org.apache.lucene.util.automaton.LevenshteinAutomata; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.core.ParseField; import org.opensearch.common.Strings; import org.opensearch.common.io.stream.StreamInput; @@ -510,7 +510,7 @@ public String toString() { toXContent(builder, EMPTY_PARAMS); return Strings.toString(builder); } catch (Exception e) { - return "{ \"error\" : \"" + BaseExceptionsHelper.detailedMessage(e) + "\"}"; + return "{ \"error\" : \"" + ExceptionsHelper.detailedMessage(e) + "\"}"; } } diff --git a/server/src/main/java/org/opensearch/tasks/TaskCancellationService.java b/server/src/main/java/org/opensearch/tasks/TaskCancellationService.java index 4368b5fe0ba3a..ebce26c4bbfbc 100644 --- a/server/src/main/java/org/opensearch/tasks/TaskCancellationService.java +++ b/server/src/main/java/org/opensearch/tasks/TaskCancellationService.java @@ -34,7 +34,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchSecurityException; import org.opensearch.action.ActionListener; import org.opensearch.action.StepListener; @@ -156,7 +156,7 @@ public void handleResponse(TransportResponse.Empty response) { @Override public void handleException(TransportException exp) { - assert BaseExceptionsHelper.unwrapCause(exp) instanceof OpenSearchSecurityException == false; + assert ExceptionsHelper.unwrapCause(exp) instanceof OpenSearchSecurityException == false; logger.warn("Cannot send ban for tasks with the parent [{}] to the node [{}]", taskId, node); groupedListener.onFailure(exp); } @@ -172,7 +172,7 @@ private void removeBanOnNodes(CancellableTask task, Collection ch transportService.sendRequest(node, BAN_PARENT_ACTION_NAME, request, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleException(TransportException exp) { - assert BaseExceptionsHelper.unwrapCause(exp) instanceof OpenSearchSecurityException == false; + assert ExceptionsHelper.unwrapCause(exp) instanceof OpenSearchSecurityException == false; logger.info("failed to remove the parent ban for task {} on node {}", request.parentTaskId, node); } }); diff --git a/server/src/main/java/org/opensearch/tasks/TaskManager.java b/server/src/main/java/org/opensearch/tasks/TaskManager.java index 443a6c0853884..f243cf392bbb8 100644 --- a/server/src/main/java/org/opensearch/tasks/TaskManager.java +++ b/server/src/main/java/org/opensearch/tasks/TaskManager.java @@ -37,7 +37,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; -import org.opensearch.BaseExceptionsHelper; import org.opensearch.core.Assertions; import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; @@ -370,7 +369,7 @@ public void storeResult(Task task, Exception e try { taskResult = task.result(localNode, error); } catch (IOException ex) { - logger.warn(() -> new ParameterizedMessage("couldn't store error {}", BaseExceptionsHelper.detailedMessage(error)), ex); + logger.warn(() -> new ParameterizedMessage("couldn't store error {}", ExceptionsHelper.detailedMessage(error)), ex); listener.onFailure(ex); return; } @@ -382,7 +381,7 @@ public void onResponse(Void aVoid) { @Override public void onFailure(Exception e) { - logger.warn(() -> new ParameterizedMessage("couldn't store error {}", BaseExceptionsHelper.detailedMessage(error)), e); + logger.warn(() -> new ParameterizedMessage("couldn't store error {}", ExceptionsHelper.detailedMessage(error)), e); listener.onFailure(e); } }); diff --git a/server/src/main/java/org/opensearch/tasks/TaskResult.java b/server/src/main/java/org/opensearch/tasks/TaskResult.java index 11ea9a9a82861..2387de173c924 100644 --- a/server/src/main/java/org/opensearch/tasks/TaskResult.java +++ b/server/src/main/java/org/opensearch/tasks/TaskResult.java @@ -31,7 +31,7 @@ package org.opensearch.tasks; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.OpenSearchException; import org.opensearch.client.Requests; import org.opensearch.common.Nullable; import org.opensearch.core.ParseField; @@ -240,7 +240,7 @@ public int hashCode() { private static BytesReference toXContent(Exception error) throws IOException { try (XContentBuilder builder = XContentFactory.contentBuilder(Requests.INDEX_CONTENT_TYPE)) { builder.startObject(); - BaseExceptionsHelper.generateThrowableXContent(builder, ToXContent.EMPTY_PARAMS, error); + OpenSearchException.generateThrowableXContent(builder, ToXContent.EMPTY_PARAMS, error); builder.endObject(); return BytesReference.bytes(builder); } diff --git a/server/src/main/java/org/opensearch/tasks/TaskResultsService.java b/server/src/main/java/org/opensearch/tasks/TaskResultsService.java index 329fc55431bc8..1feb115cb585a 100644 --- a/server/src/main/java/org/opensearch/tasks/TaskResultsService.java +++ b/server/src/main/java/org/opensearch/tasks/TaskResultsService.java @@ -34,7 +34,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.ResourceAlreadyExistsException; import org.opensearch.action.ActionListener; @@ -126,7 +126,7 @@ public void onResponse(CreateIndexResponse result) { @Override public void onFailure(Exception e) { - if (BaseExceptionsHelper.unwrapCause(e) instanceof ResourceAlreadyExistsException) { + if (ExceptionsHelper.unwrapCause(e) instanceof ResourceAlreadyExistsException) { // we have the index, do it try { doStoreResult(taskResult, listener); diff --git a/server/src/test/java/org/opensearch/ExceptionsHelperTests.java b/server/src/test/java/org/opensearch/ExceptionsHelperTests.java index 2761d59958a84..4c65eadf46e89 100644 --- a/server/src/test/java/org/opensearch/ExceptionsHelperTests.java +++ b/server/src/test/java/org/opensearch/ExceptionsHelperTests.java @@ -108,18 +108,15 @@ private void assertError(final Throwable cause, final Error error) { } public void testStatus() { - assertThat(BaseExceptionsHelper.status(new IllegalArgumentException("illegal")), equalTo(RestStatus.BAD_REQUEST)); - assertThat(BaseExceptionsHelper.status(new JsonParseException(null, "illegal")), equalTo(RestStatus.BAD_REQUEST)); - assertThat( - BaseExceptionsHelper.status(new OpenSearchRejectedExecutionException("rejected")), - equalTo(RestStatus.TOO_MANY_REQUESTS) - ); + assertThat(ExceptionsHelper.status(new IllegalArgumentException("illegal")), equalTo(RestStatus.BAD_REQUEST)); + assertThat(ExceptionsHelper.status(new JsonParseException(null, "illegal")), equalTo(RestStatus.BAD_REQUEST)); + assertThat(ExceptionsHelper.status(new OpenSearchRejectedExecutionException("rejected")), equalTo(RestStatus.TOO_MANY_REQUESTS)); } public void testSummaryMessage() { - assertThat(BaseExceptionsHelper.summaryMessage(new IllegalArgumentException("illegal")), equalTo("Invalid argument")); - assertThat(BaseExceptionsHelper.summaryMessage(new JsonParseException(null, "illegal")), equalTo("Failed to parse JSON")); - assertThat(BaseExceptionsHelper.summaryMessage(new OpenSearchRejectedExecutionException("rejected")), equalTo("Too many requests")); + assertThat(ExceptionsHelper.summaryMessage(new IllegalArgumentException("illegal")), equalTo("Invalid argument")); + assertThat(ExceptionsHelper.summaryMessage(new JsonParseException(null, "illegal")), equalTo("Failed to parse JSON")); + assertThat(ExceptionsHelper.summaryMessage(new OpenSearchRejectedExecutionException("rejected")), equalTo("Too many requests")); } public void testGroupBy() { diff --git a/server/src/test/java/org/opensearch/OpenSearchExceptionTests.java b/server/src/test/java/org/opensearch/OpenSearchExceptionTests.java index 08fd4d581f587..a0bd8202abbbe 100644 --- a/server/src/test/java/org/opensearch/OpenSearchExceptionTests.java +++ b/server/src/test/java/org/opensearch/OpenSearchExceptionTests.java @@ -129,7 +129,7 @@ public void testGuessRootCause() { ); OpenSearchException[] rootCauses = exception.guessRootCauses(); assertEquals(rootCauses.length, 1); - assertEquals(BaseExceptionsHelper.getExceptionName(rootCauses[0]), "index_not_found_exception"); + assertEquals(OpenSearchException.getExceptionName(rootCauses[0]), "index_not_found_exception"); assertEquals("no such index [foo]", rootCauses[0].getMessage()); ShardSearchFailure failure = new ShardSearchFailure( new ParsingException(1, 2, "foobar", null), @@ -149,12 +149,12 @@ public void testGuessRootCause() { } else { rootCauses = OpenSearchException.guessRootCauses(randomBoolean() ? new RemoteTransportException("remoteboom", ex) : ex); } - assertEquals("parsing_exception", BaseExceptionsHelper.getExceptionName(rootCauses[0])); + assertEquals("parsing_exception", OpenSearchException.getExceptionName(rootCauses[0])); assertEquals("foobar", rootCauses[0].getMessage()); OpenSearchException oneLevel = new OpenSearchException("foo", new RuntimeException("foobar")); rootCauses = oneLevel.guessRootCauses(); - assertEquals("exception", BaseExceptionsHelper.getExceptionName(rootCauses[0])); + assertEquals("exception", OpenSearchException.getExceptionName(rootCauses[0])); assertEquals("foo", rootCauses[0].getMessage()); } { @@ -177,12 +177,12 @@ public void testGuessRootCause() { ); final OpenSearchException[] rootCauses = ex.guessRootCauses(); assertEquals(rootCauses.length, 2); - assertEquals(BaseExceptionsHelper.getExceptionName(rootCauses[0]), "parsing_exception"); + assertEquals(OpenSearchException.getExceptionName(rootCauses[0]), "parsing_exception"); assertEquals(rootCauses[0].getMessage(), "foobar"); assertEquals(1, ((ParsingException) rootCauses[0]).getLineNumber()); assertEquals(2, ((ParsingException) rootCauses[0]).getColumnNumber()); - assertEquals("query_shard_exception", BaseExceptionsHelper.getExceptionName(rootCauses[1])); - assertEquals("foo1", rootCauses[1].getIndexName()); + assertEquals("query_shard_exception", OpenSearchException.getExceptionName(rootCauses[1])); + assertEquals("foo1", rootCauses[1].getIndex().getName()); assertEquals("foobar", rootCauses[1].getMessage()); } @@ -409,7 +409,7 @@ public void testToXContent() throws IOException { // Test the same exception but with the "rest.exception.stacktrace.skip" parameter disabled: the stack_trace must be present // in the JSON. Since the stack can be large, it only checks the beginning of the JSON. ToXContent.Params params = new ToXContent.MapParams( - Collections.singletonMap(BaseExceptionsHelper.REST_EXCEPTION_SKIP_STACK_TRACE, "false") + Collections.singletonMap(OpenSearchException.REST_EXCEPTION_SKIP_STACK_TRACE, "false") ); String actual; try (XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent())) { @@ -451,7 +451,7 @@ public void testGenerateThrowableToXContent() throws IOException { OpenSearchException ex = new RemoteTransportException("foobar", new FileNotFoundException("foo not found")); String toXContentString = Strings.toString(XContentType.JSON, ex); String throwableString = Strings.toString(XContentType.JSON, (builder, params) -> { - BaseExceptionsHelper.generateThrowableXContent(builder, params, ex); + OpenSearchException.generateThrowableXContent(builder, params, ex); return builder; }); @@ -740,7 +740,7 @@ public void testThrowableToAndFromXContent() throws IOException { } BytesReference throwableBytes = toShuffledXContent((builder, params) -> { - BaseExceptionsHelper.generateThrowableXContent(builder, params, throwable); + OpenSearchException.generateThrowableXContent(builder, params, throwable); return builder; }, xContent.mediaType(), ToXContent.EMPTY_PARAMS, randomBoolean()); @@ -756,7 +756,7 @@ public void testThrowableToAndFromXContent() throws IOException { if (suppressedCount > 0) { XContentBuilder builder = XContentBuilder.builder(xContent); builder.startObject(); - BaseExceptionsHelper.generateThrowableXContent(builder, ToXContent.EMPTY_PARAMS, throwable); + OpenSearchException.generateThrowableXContent(builder, ToXContent.EMPTY_PARAMS, throwable); builder.endObject(); throwableBytes = BytesReference.bytes(builder); try (XContentParser parser = createParser(xContent, throwableBytes)) { @@ -814,7 +814,7 @@ public void testFailureToAndFromXContentWithNoDetails() throws IOException { } assertNotNull(parsedFailure); - String reason = BaseExceptionsHelper.summaryMessage(failure); + String reason = ExceptionsHelper.summaryMessage(failure); assertEquals(OpenSearchException.buildMessage("exception", reason, null), parsedFailure.getMessage()); assertEquals(0, parsedFailure.getHeaders().size()); assertEquals(0, parsedFailure.getMetadata().size()); @@ -983,7 +983,7 @@ private static void assertToXContentAsJson(ToXContent e, String expectedJson) th private static void assertExceptionAsJson(Exception e, String expectedJson) throws IOException { assertToXContentAsJson((builder, params) -> { - BaseExceptionsHelper.generateThrowableXContent(builder, params, e); + OpenSearchException.generateThrowableXContent(builder, params, e); return builder; }, expectedJson); } diff --git a/server/src/test/java/org/opensearch/action/bulk/BulkItemResponseTests.java b/server/src/test/java/org/opensearch/action/bulk/BulkItemResponseTests.java index f71d57f68a406..3e5a7d5ad5242 100644 --- a/server/src/test/java/org/opensearch/action/bulk/BulkItemResponseTests.java +++ b/server/src/test/java/org/opensearch/action/bulk/BulkItemResponseTests.java @@ -32,7 +32,7 @@ package org.opensearch.action.bulk; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.action.DocWriteRequest; import org.opensearch.action.DocWriteResponse; @@ -109,7 +109,7 @@ public void testFailureToAndFromXContent() throws IOException { Exception bulkItemCause = (Exception) exceptions.v1(); Failure bulkItemFailure = new Failure(index, id, bulkItemCause); BulkItemResponse bulkItemResponse = new BulkItemResponse(itemId, opType, bulkItemFailure); - Failure expectedBulkItemFailure = new Failure(index, id, exceptions.v2(), BaseExceptionsHelper.status(bulkItemCause)); + Failure expectedBulkItemFailure = new Failure(index, id, exceptions.v2(), ExceptionsHelper.status(bulkItemCause)); BulkItemResponse expectedBulkItemResponse = new BulkItemResponse(itemId, opType, expectedBulkItemFailure); BytesReference originalBytes = toShuffledXContent(bulkItemResponse, xContentType, ToXContent.EMPTY_PARAMS, randomBoolean()); diff --git a/server/src/test/java/org/opensearch/action/bulk/BulkResponseTests.java b/server/src/test/java/org/opensearch/action/bulk/BulkResponseTests.java index f7fd434b2fb26..aca2419e2d325 100644 --- a/server/src/test/java/org/opensearch/action/bulk/BulkResponseTests.java +++ b/server/src/test/java/org/opensearch/action/bulk/BulkResponseTests.java @@ -32,7 +32,7 @@ package org.opensearch.action.bulk; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.action.DocWriteRequest; import org.opensearch.action.DocWriteResponse; @@ -95,7 +95,7 @@ public void testToAndFromXContent() throws IOException { expectedBulkItems[i] = new BulkItemResponse( i, opType, - new BulkItemResponse.Failure(index, id, failures.v2(), BaseExceptionsHelper.status(bulkItemCause)) + new BulkItemResponse.Failure(index, id, failures.v2(), ExceptionsHelper.status(bulkItemCause)) ); } } diff --git a/server/src/test/java/org/opensearch/client/AbstractClientHeadersTestCase.java b/server/src/test/java/org/opensearch/client/AbstractClientHeadersTestCase.java index f40227beb59b7..92a88aa7940ee 100644 --- a/server/src/test/java/org/opensearch/client/AbstractClientHeadersTestCase.java +++ b/server/src/test/java/org/opensearch/client/AbstractClientHeadersTestCase.java @@ -32,7 +32,7 @@ package org.opensearch.client; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.ActionType; import org.opensearch.action.ActionListener; import org.opensearch.action.admin.cluster.reroute.ClusterRerouteAction; @@ -244,7 +244,7 @@ public Throwable unwrap(Throwable t, Class exceptionType) { } if (counter++ > 10) { // dear god, if we got more than 10 levels down, WTF? just bail - fail("Exception cause unwrapping ran for 10 levels: " + BaseExceptionsHelper.stackTrace(t)); + fail("Exception cause unwrapping ran for 10 levels: " + ExceptionsHelper.stackTrace(t)); return null; } result = result.getCause(); diff --git a/server/src/test/java/org/opensearch/rest/BytesRestResponseTests.java b/server/src/test/java/org/opensearch/rest/BytesRestResponseTests.java index ae6352a6c6636..a5d70886aa651 100644 --- a/server/src/test/java/org/opensearch/rest/BytesRestResponseTests.java +++ b/server/src/test/java/org/opensearch/rest/BytesRestResponseTests.java @@ -32,7 +32,7 @@ package org.opensearch.rest; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchStatusException; import org.opensearch.OpenSearchException; import org.opensearch.ResourceAlreadyExistsException; @@ -183,7 +183,7 @@ public void testConvert() throws IOException { + "\"failed_shards\":[{\"shard\":1,\"index\":\"foo\",\"node\":\"node_1\",\"reason\":{\"type\":\"parsing_exception\"," + "\"reason\":\"foobar\",\"line\":1,\"col\":2}}]},\"status\":400}"; assertEquals(expected.trim(), text.trim()); - String stackTrace = BaseExceptionsHelper.stackTrace(ex); + String stackTrace = ExceptionsHelper.stackTrace(ex); assertTrue(stackTrace.contains("Caused by: ParsingException[foobar]")); } diff --git a/server/src/test/java/org/opensearch/search/aggregations/pipeline/DerivativeAggregatorTests.java b/server/src/test/java/org/opensearch/search/aggregations/pipeline/DerivativeAggregatorTests.java index 801f057d8888d..88628cd44c721 100644 --- a/server/src/test/java/org/opensearch/search/aggregations/pipeline/DerivativeAggregatorTests.java +++ b/server/src/test/java/org/opensearch/search/aggregations/pipeline/DerivativeAggregatorTests.java @@ -41,7 +41,7 @@ import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.store.Directory; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.action.search.SearchPhaseExecutionException; import org.opensearch.common.CheckedConsumer; import org.opensearch.index.mapper.DateFieldMapper; @@ -635,7 +635,7 @@ public void testSingleValueAggDerivative_invalidPath() throws IOException { executeTestCase(query, aggBuilder, history -> {}); fail("Expected an Exception but didn't get one"); } catch (Exception e) { - Throwable cause = BaseExceptionsHelper.unwrapCause(e); + Throwable cause = ExceptionsHelper.unwrapCause(e); if (cause == null) { throw e; } else if (cause instanceof SearchPhaseExecutionException) { diff --git a/server/src/test/java/org/opensearch/transport/TransportActionProxyTests.java b/server/src/test/java/org/opensearch/transport/TransportActionProxyTests.java index 64125863c3c5f..5190495a6253e 100644 --- a/server/src/test/java/org/opensearch/transport/TransportActionProxyTests.java +++ b/server/src/test/java/org/opensearch/transport/TransportActionProxyTests.java @@ -31,7 +31,7 @@ package org.opensearch.transport; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.Version; import org.opensearch.cluster.node.DiscoveryNode; @@ -196,7 +196,7 @@ public void handleResponse(SimpleTestResponse response) { @Override public void handleException(TransportException exp) { try { - Throwable cause = BaseExceptionsHelper.unwrapCause(exp); + Throwable cause = ExceptionsHelper.unwrapCause(exp); assertEquals("greetings from TS_C", cause.getMessage()); } finally { latch.countDown(); diff --git a/test/framework/src/main/java/org/opensearch/test/OpenSearchIntegTestCase.java b/test/framework/src/main/java/org/opensearch/test/OpenSearchIntegTestCase.java index 4474aae1f0631..caa5b90016740 100644 --- a/test/framework/src/main/java/org/opensearch/test/OpenSearchIntegTestCase.java +++ b/test/framework/src/main/java/org/opensearch/test/OpenSearchIntegTestCase.java @@ -41,7 +41,7 @@ import org.apache.lucene.search.Sort; import org.apache.lucene.search.TotalHits; import org.apache.lucene.tests.util.LuceneTestCase; -import org.opensearch.BaseExceptionsHelper; +import org.opensearch.ExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.action.ActionListener; import org.opensearch.action.DocWriteResponse; @@ -1611,7 +1611,7 @@ public void indexRandom(boolean forceRefresh, boolean dummyDocuments, boolean ma } final List actualErrors = new ArrayList<>(); for (Tuple tuple : errors) { - Throwable t = BaseExceptionsHelper.unwrapCause(tuple.v2()); + Throwable t = ExceptionsHelper.unwrapCause(tuple.v2()); if (t instanceof OpenSearchRejectedExecutionException) { logger.debug("Error indexing doc: " + t.getMessage() + ", reindexing."); tuple.v1().execute().actionGet(); // re-index if rejected diff --git a/test/framework/src/main/java/org/opensearch/test/hamcrest/OpenSearchAssertions.java b/test/framework/src/main/java/org/opensearch/test/hamcrest/OpenSearchAssertions.java index 0b1e119494a77..e52a6b48e219d 100644 --- a/test/framework/src/main/java/org/opensearch/test/hamcrest/OpenSearchAssertions.java +++ b/test/framework/src/main/java/org/opensearch/test/hamcrest/OpenSearchAssertions.java @@ -34,7 +34,6 @@ import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.TotalHits; -import org.opensearch.BaseExceptionsHelper; import org.opensearch.OpenSearchException; import org.opensearch.ExceptionsHelper; import org.opensearch.action.ActionFuture; @@ -627,7 +626,7 @@ public static void assertFutureThrows( } if (status != null) { - assertThat(extraInfo, BaseExceptionsHelper.status(expected), equalTo(status)); + assertThat(extraInfo, ExceptionsHelper.status(expected), equalTo(status)); } } @@ -648,7 +647,7 @@ public static void assertFutureThrows(ActionFuture future, RestStatus status, extraInfo += "expected a " + status + " status exception to be thrown"; Exception e = expectThrows(Exception.class, future::actionGet); - assertThat(extraInfo, BaseExceptionsHelper.status(e), equalTo(status)); + assertThat(extraInfo, ExceptionsHelper.status(e), equalTo(status)); } /** diff --git a/test/framework/src/main/java/org/opensearch/transport/AbstractSimpleTransportTestCase.java b/test/framework/src/main/java/org/opensearch/transport/AbstractSimpleTransportTestCase.java index 94e66a34d6cea..fed14d6bbc1ba 100644 --- a/test/framework/src/main/java/org/opensearch/transport/AbstractSimpleTransportTestCase.java +++ b/test/framework/src/main/java/org/opensearch/transport/AbstractSimpleTransportTestCase.java @@ -39,7 +39,6 @@ import org.apache.logging.log4j.util.Supplier; import org.apache.lucene.util.CollectionUtil; import org.apache.lucene.util.Constants; -import org.opensearch.BaseExceptionsHelper; import org.opensearch.LegacyESVersion; import org.opensearch.OpenSearchException; import org.opensearch.ExceptionsHelper; @@ -558,7 +557,7 @@ public void onRequestSent( serviceA.submitRequest(nodeB, ACTION, TransportRequest.Empty.INSTANCE, EmptyTransportResponseHandler.INSTANCE_SAME).get(); } catch (ExecutionException e) { assertThat(e.getCause(), instanceOf(OpenSearchException.class)); - assertThat(BaseExceptionsHelper.unwrapCause(e.getCause()).getMessage(), equalTo("simulated")); + assertThat(ExceptionsHelper.unwrapCause(e.getCause()).getMessage(), equalTo("simulated")); } // use assert busy as callbacks are called on a different thread @@ -577,7 +576,7 @@ public void onRequestSent( serviceB.submitRequest(nodeA, ACTION, TransportRequest.Empty.INSTANCE, EmptyTransportResponseHandler.INSTANCE_SAME).get(); } catch (ExecutionException e) { assertThat(e.getCause(), instanceOf(OpenSearchException.class)); - assertThat(BaseExceptionsHelper.unwrapCause(e.getCause()).getMessage(), equalTo("simulated")); + assertThat(ExceptionsHelper.unwrapCause(e.getCause()).getMessage(), equalTo("simulated")); } // use assert busy as callbacks are called on a different thread @@ -597,7 +596,7 @@ public void onRequestSent( serviceA.submitRequest(nodeA, ACTION, TransportRequest.Empty.INSTANCE, EmptyTransportResponseHandler.INSTANCE_SAME).get(); } catch (ExecutionException e) { assertThat(e.getCause(), instanceOf(OpenSearchException.class)); - assertThat(BaseExceptionsHelper.unwrapCause(e.getCause()).getMessage(), equalTo("simulated")); + assertThat(ExceptionsHelper.unwrapCause(e.getCause()).getMessage(), equalTo("simulated")); } // use assert busy as callbacks are called on a different thread @@ -1651,7 +1650,7 @@ public void handleResponse(StringMessageResponse response) { @Override public void handleException(TransportException exp) { - Throwable cause = BaseExceptionsHelper.unwrapCause(exp); + Throwable cause = ExceptionsHelper.unwrapCause(exp); assertThat(cause, instanceOf(ConnectTransportException.class)); assertThat(((ConnectTransportException) cause).node(), equalTo(nodeA)); } @@ -1662,7 +1661,7 @@ public void handleException(TransportException exp) { res.txGet(); fail("exception should be thrown"); } catch (Exception e) { - Throwable cause = BaseExceptionsHelper.unwrapCause(e); + Throwable cause = ExceptionsHelper.unwrapCause(e); assertThat(cause, instanceOf(ConnectTransportException.class)); assertThat(((ConnectTransportException) cause).node(), equalTo(nodeA)); }