From 3343ceeae44f3d28e3c1ba7861886848df74e390 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Mon, 4 Jul 2016 08:41:06 -0400 Subject: [PATCH] Do not catch throwable Today throughout the codebase, catch throwable is used with reckless abandon. This is dangerous because the throwable could be a fatal virtual machine error resulting from an internal error in the JVM, or an out of memory error or a stack overflow error that leaves the virtual machine in an unstable and unpredictable state. This commit removes catch throwable from the codebase and removes the temptation to use it by modifying listener APIs to receive instances of Exception instead of the top-level Throwable. Relates #19231 --- .../elasticsearch/ElasticsearchException.java | 12 +- .../ElasticsearchSecurityException.java | 2 +- .../org/elasticsearch/ExceptionsHelper.java | 24 ++-- .../elasticsearch/action/ActionListener.java | 2 +- .../elasticsearch/action/ActionRunnable.java | 10 +- .../action/LatchedActionListener.java | 2 +- .../action/TaskOperationFailure.java | 10 +- ...ansportClusterAllocationExplainAction.java | 4 +- .../health/TransportClusterHealthAction.java | 6 +- .../tasks/get/TransportGetTaskAction.java | 10 +- .../TransportDeleteRepositoryAction.java | 2 +- .../put/TransportPutRepositoryAction.java | 2 +- .../TransportVerifyRepositoryAction.java | 2 +- .../TransportClusterRerouteAction.java | 6 +- .../TransportClusterUpdateSettingsAction.java | 16 +-- .../create/TransportCreateSnapshotAction.java | 8 +- .../delete/TransportDeleteSnapshotAction.java | 4 +- .../get/TransportGetSnapshotsAction.java | 4 +- .../TransportRestoreSnapshotAction.java | 4 +- .../TransportSnapshotsStatusAction.java | 4 +- .../alias/TransportIndicesAliasesAction.java | 2 +- .../close/TransportCloseIndexAction.java | 2 +- .../create/TransportCreateIndexAction.java | 2 +- .../delete/TransportDeleteIndexAction.java | 2 +- .../get/TransportGetFieldMappingsAction.java | 2 +- .../put/TransportPutMappingAction.java | 2 +- .../open/TransportOpenIndexAction.java | 2 +- .../rollover/TransportRolloverAction.java | 7 +- .../put/TransportUpdateSettingsAction.java | 2 +- .../shards/IndicesShardStoresResponse.java | 8 +- .../indices/shrink/TransportShrinkAction.java | 4 +- .../TransportDeleteIndexTemplateAction.java | 6 +- .../put/TransportPutIndexTemplateAction.java | 6 +- .../upgrade/post/TransportUpgradeAction.java | 8 +- .../post/TransportUpgradeSettingsAction.java | 2 +- .../action/bulk/BulkItemResponse.java | 8 +- .../action/bulk/BulkRequestHandler.java | 14 +- .../org/elasticsearch/action/bulk/Retry.java | 6 +- .../action/bulk/TransportBulkAction.java | 15 ++- .../action/bulk/TransportShardBulkAction.java | 56 ++++---- .../action/delete/TransportDeleteAction.java | 2 +- .../action/get/MultiGetResponse.java | 18 +-- .../action/get/TransportMultiGetAction.java | 2 +- .../get/TransportShardMultiGetAction.java | 10 +- .../action/index/TransportIndexAction.java | 9 +- .../action/ingest/IngestActionFilter.java | 20 +-- .../ingest/PutPipelineTransportAction.java | 2 +- .../ingest/SimulateDocumentBaseResult.java | 4 +- .../ingest/SimulateProcessorResult.java | 4 +- .../search/AbstractSearchAsyncAction.java | 57 ++++---- .../action/search/MultiSearchResponse.java | 21 ++- .../SearchDfsQueryAndFetchAsyncAction.java | 14 +- .../SearchDfsQueryThenFetchAsyncAction.java | 22 +-- .../search/SearchPhaseExecutionException.java | 3 - .../SearchQueryAndFetchAsyncAction.java | 4 +- .../SearchQueryThenFetchAsyncAction.java | 12 +- .../SearchScrollQueryAndFetchAsyncAction.java | 12 +- ...SearchScrollQueryThenFetchAsyncAction.java | 23 ++-- .../action/search/ShardSearchFailure.java | 12 +- .../search/TransportClearScrollAction.java | 4 +- .../search/TransportMultiSearchAction.java | 3 +- .../search/TransportSearchScrollAction.java | 2 +- .../AbstractListenableActionFuture.java | 2 +- .../action/support/AdapterActionFuture.java | 2 +- .../DefaultShardOperationFailedException.java | 8 +- .../support/DelegatingActionListener.java | 2 +- .../support/HandledTransportAction.java | 4 +- .../support/PlainListenableActionFuture.java | 4 +- .../support/ThreadedActionListener.java | 10 +- .../action/support/TransportAction.java | 33 ++--- .../action/support/TransportActions.java | 21 +-- .../broadcast/TransportBroadcastAction.java | 36 ++--- .../node/TransportBroadcastByNodeAction.java | 31 ++--- .../master/TransportMasterNodeAction.java | 2 +- .../support/nodes/TransportNodesAction.java | 13 +- .../replication/ReplicationOperation.java | 32 ++--- .../replication/ReplicationResponse.java | 6 +- .../TransportBroadcastReplicationAction.java | 2 +- .../TransportReplicationAction.java | 78 +++++------ ...ransportInstanceSingleOperationAction.java | 21 +-- .../shard/TransportSingleShardAction.java | 14 +- .../support/tasks/TransportTasksAction.java | 16 +-- .../termvectors/MultiTermVectorsResponse.java | 10 +- .../TransportMultiTermVectorsAction.java | 2 +- .../TransportShardMultiTermsVectorAction.java | 2 +- .../action/update/TransportUpdateAction.java | 38 +++--- .../elasticsearch/bootstrap/Bootstrap.java | 6 +- .../elasticsearch/bootstrap/JNANatives.java | 6 +- .../org/elasticsearch/bootstrap/Seccomp.java | 2 +- .../TransportClientNodesService.java | 19 +-- .../AckedClusterStateTaskListener.java | 4 +- .../cluster/AckedClusterStateUpdateTask.java | 8 +- .../cluster/ClusterStateTaskConfig.java | 2 +- .../cluster/ClusterStateTaskExecutor.java | 18 +-- .../cluster/ClusterStateTaskListener.java | 2 +- .../cluster/ClusterStateUpdateTask.java | 6 +- .../cluster/InternalClusterInfoService.java | 6 +- .../cluster/NodeConnectionsService.java | 6 +- .../action/shard/ShardStateAction.java | 48 +++---- .../cluster/metadata/AliasValidator.java | 6 +- .../MetaDataIndexTemplateService.java | 14 +- .../metadata/MetaDataMappingService.java | 16 +-- .../MetaDataUpdateSettingsService.java | 2 +- .../routing/DelayedAllocationService.java | 8 +- .../cluster/routing/RoutingService.java | 8 +- .../cluster/routing/UnassignedInfo.java | 11 +- .../allocation/FailedRerouteAllocation.java | 4 +- .../cluster/service/ClusterService.java | 42 +++--- .../common/MacAddressProvider.java | 2 +- .../org/elasticsearch/common/Randomness.java | 2 +- .../common/geo/ShapesAvailability.java | 4 +- .../common/io/stream/StreamInput.java | 50 ++++--- .../common/io/stream/StreamOutput.java | 17 +-- .../common/lease/Releasables.java | 5 +- .../common/logging/LoggerMessageFormat.java | 2 +- .../elasticsearch/common/network/Cidrs.java | 4 +- .../common/util/CancellableThreads.java | 7 +- .../util/concurrent/AbstractRunnable.java | 10 +- .../common/util/concurrent/ThreadBarrier.java | 24 ++-- .../common/util/concurrent/ThreadContext.java | 8 +- ...AckClusterStatePublishResponseHandler.java | 15 ++- ...ingClusterStatePublishResponseHandler.java | 2 +- .../elasticsearch/discovery/Discovery.java | 2 +- .../discovery/local/LocalDiscovery.java | 18 +-- .../discovery/zen/NodeJoinController.java | 18 +-- .../discovery/zen/ZenDiscovery.java | 65 ++++----- .../zen/fd/MasterFaultDetection.java | 13 +- .../zen/membership/MembershipAction.java | 15 ++- .../zen/ping/unicast/UnicastZenPing.java | 11 +- .../publish/PendingClusterStatesQueue.java | 9 +- .../publish/PublishClusterStateAction.java | 39 +++--- .../org/elasticsearch/env/ESFileStore.java | 4 +- .../elasticsearch/env/NodeEnvironment.java | 22 ++- .../gateway/AsyncShardFetch.java | 2 +- .../gateway/DanglingIndicesState.java | 2 +- .../gateway/GatewayMetaState.java | 9 +- .../elasticsearch/gateway/GatewayService.java | 10 +- .../gateway/LocalAllocateDangledIndices.java | 11 +- .../gateway/MetaDataStateFormat.java | 2 +- .../gateway/MetaStateService.java | 4 +- ...ransportNodesListGatewayStartedShards.java | 8 +- .../org/elasticsearch/http/HttpServer.java | 14 +- .../index/CompositeIndexEventListener.java | 106 +++++++-------- .../org/elasticsearch/index/IndexService.java | 14 +- .../org/elasticsearch/index/IndexWarmer.java | 4 +- .../index/cache/bitset/BitsetFilterCache.java | 8 +- .../elasticsearch/index/engine/Engine.java | 25 ++-- .../index/engine/InternalEngine.java | 125 +++++++++++------- .../index/engine/ShadowEngine.java | 18 ++- .../fielddata/IndexFieldDataService.java | 30 +---- .../plain/AbstractIndexFieldData.java | 4 +- .../plain/AbstractIndexOrdinalsFieldData.java | 2 +- .../plain/ParentChildIndexFieldData.java | 2 +- .../SortedSetDVOrdinalsIndexFieldData.java | 4 +- .../index/mapper/DocumentParser.java | 6 +- .../index/mapper/MapperService.java | 2 +- .../elasticsearch/index/mapper/Mapping.java | 3 +- .../index/query/QueryParseContext.java | 2 +- .../elasticsearch/index/shard/IndexShard.java | 67 +++++----- .../shard/IndexingOperationListener.java | 34 ++--- .../index/shard/InternalIndexingStats.java | 4 +- .../index/shard/RefreshListeners.java | 4 +- .../index/shard/SearchOperationListener.java | 40 +++--- .../index/shard/StoreRecovery.java | 13 +- .../shard/TranslogRecoveryPerformer.java | 4 +- .../BlobStoreIndexShardRepository.java | 23 ++-- .../org/elasticsearch/index/store/Store.java | 20 +-- .../index/termvectors/TermVectorsService.java | 12 +- .../index/translog/Translog.java | 42 ++++-- .../index/translog/TranslogWriter.java | 58 +++++--- .../indices/IndexingMemoryController.java | 4 +- .../elasticsearch/indices/IndicesService.java | 14 +- .../indices/analysis/HunspellService.java | 4 +- .../cluster/IndicesClusterStateService.java | 47 ++++--- .../cache/IndicesFieldDataCache.java | 8 +- .../indices/flush/SyncedFlushService.java | 16 +-- .../recovery/RecoveriesCollection.java | 5 +- .../recovery/RecoverySourceHandler.java | 22 +-- .../indices/recovery/RecoveryTarget.java | 6 +- .../recovery/RecoveryTargetService.java | 13 +- .../SharedFSRecoverySourceHandler.java | 8 +- .../indices/store/IndicesStore.java | 6 +- .../indices/ttl/IndicesTTLService.java | 4 +- .../ingest/ConfigurationUtils.java | 2 +- .../ingest/PipelineExecutionService.java | 16 +-- .../org/elasticsearch/monitor/Probes.java | 2 +- .../monitor/jvm/JvmGcMonitorService.java | 10 +- .../elasticsearch/monitor/jvm/JvmInfo.java | 2 +- .../elasticsearch/monitor/jvm/JvmStats.java | 6 +- .../org/elasticsearch/monitor/os/OsProbe.java | 12 +- .../monitor/process/ProcessProbe.java | 14 +- .../elasticsearch/plugins/PluginsService.java | 2 +- .../repositories/RepositoriesService.java | 39 +++--- .../repositories/VerificationFailure.java | 6 +- .../VerifyNodeRepositoryAction.java | 6 +- .../blobstore/BlobStoreRepository.java | 2 +- .../elasticsearch/rest/BytesRestResponse.java | 26 ++-- .../elasticsearch/rest/RestController.java | 7 +- .../node/tasks/RestListTasksAction.java | 2 +- .../alias/head/RestAliasesExistAction.java | 9 +- .../action/support/RestActionListener.java | 11 +- .../elasticsearch/script/ScriptService.java | 2 +- .../elasticsearch/search/MultiValueMode.java | 2 +- .../elasticsearch/search/SearchService.java | 48 ++++--- .../search/action/SearchTransportService.java | 2 +- .../support/AggregationContext.java | 8 +- .../search/query/QueryPhase.java | 2 +- .../snapshots/RestoreService.java | 16 +-- .../snapshots/SnapshotShardsService.java | 24 ++-- .../snapshots/SnapshotsService.java | 105 ++++++++------- .../tasks/PersistedTaskInfo.java | 6 +- .../java/org/elasticsearch/tasks/Task.java | 2 +- .../org/elasticsearch/tasks/TaskManager.java | 6 +- .../tasks/TaskPersistenceService.java | 11 +- .../elasticsearch/threadpool/ThreadPool.java | 6 +- .../transport/DelegatingTransportChannel.java | 4 +- .../transport/PlainTransportFuture.java | 4 +- .../transport/RequestHandlerRegistry.java | 4 +- ...ponseHandlerFailureTransportException.java | 2 - .../elasticsearch/transport/TcpTransport.java | 58 ++++---- .../transport/TcpTransportChannel.java | 4 +- .../transport/TransportChannel.java | 2 +- .../transport/TransportService.java | 59 ++++----- .../transport/TransportServiceAdapter.java | 2 +- .../transport/local/LocalTransport.java | 44 +++--- .../local/LocalTransportChannel.java | 6 +- .../transport/netty/NettyTransport.java | 10 +- .../org/elasticsearch/tribe/TribeService.java | 17 +-- .../elasticsearch/watcher/FileWatcher.java | 20 +-- .../org/elasticsearch/ESExceptionTests.java | 48 ++++--- .../ExceptionSerializationTests.java | 18 ++- .../action/ListenerActionIT.java | 2 +- .../action/RejectionActionIT.java | 4 +- .../action/admin/HotThreadsIT.java | 2 +- .../node/tasks/CancellableTasksTests.java | 4 +- .../admin/cluster/node/tasks/TasksIT.java | 4 +- .../node/tasks/TransportTasksActionTests.java | 4 +- .../cluster/reroute/ClusterRerouteTests.java | 2 +- .../admin/indices/create/CreateIndexIT.java | 5 +- .../MetaDataIndexTemplateServiceTests.java | 9 +- .../elasticsearch/action/bulk/RetryTests.java | 2 +- .../bulk/TransportBulkActionTookTests.java | 2 +- .../ingest/BulkRequestModifierTests.java | 4 +- .../action/main/MainActionTests.java | 2 +- .../support/ListenableActionFutureTests.java | 6 +- .../TransportActionFilterChainTests.java | 14 +- .../TransportBroadcastByNodeActionTests.java | 2 +- .../TransportMasterNodeActionTests.java | 4 +- .../ReplicationOperationTests.java | 26 ++-- .../TransportReplicationActionTests.java | 8 +- .../TransportWriteActionTests.java | 2 +- ...ortInstanceSingleOperationActionTests.java | 12 +- .../action/termvectors/GetTermVectorsIT.java | 20 ++- .../termvectors/MultiTermVectorsIT.java | 21 ++- .../client/AbstractClientHeadersTestCase.java | 2 +- .../TransportClientNodesServiceTests.java | 3 +- .../cluster/MinimumMasterNodesIT.java | 4 +- .../action/shard/ShardStateActionTests.java | 18 +-- .../health/ClusterStateHealthTests.java | 4 +- .../cluster/service/ClusterServiceIT.java | 32 ++--- .../cluster/service/ClusterServiceTests.java | 56 ++++---- .../breaker/MemoryCircuitBreakerTests.java | 14 +- .../common/util/CancellableThreadsTests.java | 16 +-- .../AbstractLifecycleRunnableTests.java | 8 +- .../concurrent/AbstractRunnableTests.java | 33 ++--- .../util/concurrent/EsExecutorsTests.java | 8 +- .../util/concurrent/RefCountedTests.java | 4 +- .../util/concurrent/ThreadContextTests.java | 4 +- .../ConstructingObjectParserTests.java | 2 +- ...usterStatePublishResponseHandlerTests.java | 4 +- .../DiscoveryWithServiceDisruptionsIT.java | 10 +- .../zen/NodeJoinControllerTests.java | 30 ++--- .../discovery/zen/ZenDiscoveryIT.java | 8 +- .../PendingClusterStatesQueueTests.java | 4 +- .../PublishClusterStateActionTests.java | 10 +- .../env/NodeEnvironmentTests.java | 9 +- .../gateway/AsyncShardFetchTests.java | 2 +- .../gateway/MetaDataWriteDataNodesIT.java | 4 +- .../gateway/PrimaryShardAllocatorTests.java | 4 +- .../index/IndexWithShadowReplicasIT.java | 8 +- .../index/engine/InternalEngineTests.java | 12 +- .../index/engine/ShadowEngineTests.java | 2 +- .../mapper/DynamicMappingDisabledTests.java | 3 +- .../mapper/DynamicMappingIntegrationIT.java | 4 +- .../index/mapper/MapperServiceTests.java | 2 +- .../mapper/merge/TestMergeMapperTests.java | 6 +- .../ESIndexLevelReplicationTestCase.java | 8 +- .../index/shard/IndexShardTests.java | 18 +-- .../shard/IndexingOperationListenerTests.java | 8 +- .../index/shard/RefreshListenersTests.java | 10 +- .../index/store/CorruptedFileIT.java | 6 +- .../index/translog/TranslogTests.java | 33 +++-- .../elasticsearch/indexing/IndexActionIT.java | 14 +- .../indices/analyze/AnalyzeActionIT.java | 6 +- .../elasticsearch/indices/flush/FlushIT.java | 4 +- .../indices/flush/SyncedFlushUtil.java | 4 +- .../mapping/ConcurrentDynamicTemplateIT.java | 4 +- .../mapping/UpdateMappingIntegrationIT.java | 11 +- .../indices/recovery/RecoveryTargetTests.java | 8 +- .../indices/state/RareClusterStateIT.java | 12 +- .../store/IndicesStoreIntegrationIT.java | 2 +- .../ingest/PipelineExecutionServiceTests.java | 38 +++--- .../jvm/JvmGcMonitorServiceSettingsTests.java | 40 +++--- .../monitor/jvm/JvmMonitorTests.java | 12 +- .../rest/BytesRestResponseTests.java | 31 +++-- .../search/SearchWithRejectionsIT.java | 2 +- .../search/aggregations/bucket/FilterIT.java | 3 - .../search/aggregations/bucket/FiltersIT.java | 3 - .../search/basic/SearchWhileRelocatingIT.java | 6 +- .../AbstractSnapshotIntegTestCase.java | 4 +- .../DedicatedClusterSnapshotRestoreIT.java | 2 +- .../SharedClusterSnapshotRestoreIT.java | 2 +- .../test/geo/RandomShapeGenerator.java | 21 ++- .../threadpool/SimpleThreadPoolIT.java | 15 +-- .../org/elasticsearch/update/UpdateIT.java | 13 +- .../ConcurrentDocumentOperationIT.java | 2 +- .../groovy/GroovyScriptEngineService.java | 4 +- .../messy/tests/MinDocCountTests.java | 4 +- .../script/groovy/GroovyScriptTests.java | 6 +- .../template/MultiSearchTemplateResponse.java | 20 +-- .../TransportMultiSearchTemplateAction.java | 2 +- .../TransportSearchTemplateAction.java | 9 +- .../percolator/MultiPercolateResponse.java | 20 +-- .../TransportMultiPercolateAction.java | 4 +- .../percolator/TransportPercolateAction.java | 4 +- .../AbstractAsyncBulkByScrollAction.java | 25 ++-- .../index/reindex/BulkByScrollTask.java | 8 +- .../reindex/AsyncBulkByScrollActionTests.java | 2 +- .../index/reindex/BulkByScrollTaskTests.java | 6 +- .../UpdateByQueryWhileModifyingTests.java | 6 +- .../index/analysis/IcuTokenizerFactory.java | 7 +- .../gce/GceUnicastHostsProvider.java | 4 +- .../attachment/AttachmentProcessor.java | 2 +- .../ingest/attachment/TikaDocTests.java | 2 +- .../plugin/example/ExampleCatAction.java | 7 +- .../JavaScriptScriptMultiThreadedTests.java | 15 +-- .../PythonScriptMultiThreadedTests.java | 12 +- .../mapper/attachments/AttachmentMapper.java | 6 +- .../mapper/attachments/TikaDocTests.java | 2 +- .../cloud/aws/blobstore/S3BlobContainer.java | 5 +- .../s3/AbstractS3SnapshotRestoreTest.java | 2 +- .../elasticsearch/bootstrap/SeccompTests.java | 2 +- .../bootstrap/ESElasticsearchCliTestCase.java | 4 +- .../elasticsearch/test/BackgroundIndexer.java | 4 +- .../test/ClusterServiceUtils.java | 5 +- .../elasticsearch/test/ESIntegTestCase.java | 20 +-- .../test/InternalTestCluster.java | 2 +- .../org/elasticsearch/test/VersionUtils.java | 2 +- .../elasticsearch/test/client/NoOpClient.java | 4 +- .../BlockClusterStateProcessing.java | 4 +- .../SlowClusterStateProcessing.java | 2 +- .../hamcrest/ElasticsearchAssertions.java | 35 +++-- .../test/rest/spec/RestSpec.java | 2 +- .../test/tasks/MockTaskManager.java | 12 +- .../test/transport/MockTransportService.java | 11 +- 355 files changed, 2146 insertions(+), 2142 deletions(-) diff --git a/core/src/main/java/org/elasticsearch/ElasticsearchException.java b/core/src/main/java/org/elasticsearch/ElasticsearchException.java index aa92fc176cf..1a695490585 100644 --- a/core/src/main/java/org/elasticsearch/ElasticsearchException.java +++ b/core/src/main/java/org/elasticsearch/ElasticsearchException.java @@ -100,7 +100,7 @@ public class ElasticsearchException extends RuntimeException implements ToXConte } public ElasticsearchException(StreamInput in) throws IOException { - super(in.readOptionalString(), in.readThrowable()); + super(in.readOptionalString(), in.readException()); readStackTrace(this, in); int numKeys = in.readVInt(); for (int i = 0; i < numKeys; i++) { @@ -162,7 +162,7 @@ public class ElasticsearchException extends RuntimeException implements ToXConte * Unwraps the actual cause from the exception for cases when the exception is a * {@link ElasticsearchWrapperException}. * - * @see org.elasticsearch.ExceptionsHelper#unwrapCause(Throwable) + * @see ExceptionsHelper#unwrapCause(Throwable) */ public Throwable unwrapCause() { return ExceptionsHelper.unwrapCause(this); @@ -415,7 +415,7 @@ public class ElasticsearchException extends RuntimeException implements ToXConte int numSuppressed = in.readVInt(); for (int i = 0; i < numSuppressed; i++) { - throwable.addSuppressed(in.readThrowable()); + throwable.addSuppressed(in.readException()); } return throwable; } @@ -794,9 +794,9 @@ public class ElasticsearchException extends RuntimeException implements ToXConte return null; } - public static void renderThrowable(XContentBuilder builder, Params params, Throwable t) throws IOException { + public static void renderException(XContentBuilder builder, Params params, Exception e) throws IOException { builder.startObject("error"); - final ElasticsearchException[] rootCauses = ElasticsearchException.guessRootCauses(t); + final ElasticsearchException[] rootCauses = ElasticsearchException.guessRootCauses(e); builder.field("root_cause"); builder.startArray(); for (ElasticsearchException rootCause : rootCauses) { @@ -806,7 +806,7 @@ public class ElasticsearchException extends RuntimeException implements ToXConte builder.endObject(); } builder.endArray(); - ElasticsearchException.toXContent(builder, params, t); + ElasticsearchException.toXContent(builder, params, e); builder.endObject(); } diff --git a/core/src/main/java/org/elasticsearch/ElasticsearchSecurityException.java b/core/src/main/java/org/elasticsearch/ElasticsearchSecurityException.java index f4878fe6f9b..b6cd420c856 100644 --- a/core/src/main/java/org/elasticsearch/ElasticsearchSecurityException.java +++ b/core/src/main/java/org/elasticsearch/ElasticsearchSecurityException.java @@ -36,7 +36,7 @@ public class ElasticsearchSecurityException extends ElasticsearchException { this.status = status ; } - public ElasticsearchSecurityException(String msg, Throwable cause, Object... args) { + public ElasticsearchSecurityException(String msg, Exception cause, Object... args) { this(msg, ExceptionsHelper.status(cause), cause, args); } diff --git a/core/src/main/java/org/elasticsearch/ExceptionsHelper.java b/core/src/main/java/org/elasticsearch/ExceptionsHelper.java index 28f8d4391ec..e2af52ccd2c 100644 --- a/core/src/main/java/org/elasticsearch/ExceptionsHelper.java +++ b/core/src/main/java/org/elasticsearch/ExceptionsHelper.java @@ -37,25 +37,22 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -/** - * - */ public final class ExceptionsHelper { private static final ESLogger logger = Loggers.getLogger(ExceptionsHelper.class); - public static RuntimeException convertToRuntime(Throwable t) { - if (t instanceof RuntimeException) { - return (RuntimeException) t; + public static RuntimeException convertToRuntime(Exception e) { + if (e instanceof RuntimeException) { + return (RuntimeException) e; } - return new ElasticsearchException(t); + return new ElasticsearchException(e); } - public static ElasticsearchException convertToElastic(Throwable t) { - if (t instanceof ElasticsearchException) { - return (ElasticsearchException) t; + public static ElasticsearchException convertToElastic(Exception e) { + if (e instanceof ElasticsearchException) { + return (ElasticsearchException) e; } - return new ElasticsearchException(t); + return new ElasticsearchException(e); } public static RestStatus status(Throwable t) { @@ -164,8 +161,8 @@ public final class ExceptionsHelper { } public static IOException unwrapCorruption(Throwable t) { - return (IOException) unwrap(t, CorruptIndexException.class, - IndexFormatTooOldException.class, + return (IOException) unwrap(t, CorruptIndexException.class, + IndexFormatTooOldException.class, IndexFormatTooNewException.class); } @@ -209,7 +206,6 @@ public final class ExceptionsHelper { return true; } - /** * Deduplicate the failures by exception message and index. */ diff --git a/core/src/main/java/org/elasticsearch/action/ActionListener.java b/core/src/main/java/org/elasticsearch/action/ActionListener.java index 8447d6cef08..e7d5ecd8d64 100644 --- a/core/src/main/java/org/elasticsearch/action/ActionListener.java +++ b/core/src/main/java/org/elasticsearch/action/ActionListener.java @@ -32,5 +32,5 @@ public interface ActionListener { /** * A failure caused by an exception at some phase of the task. */ - void onFailure(Throwable e); + void onFailure(Exception e); } diff --git a/core/src/main/java/org/elasticsearch/action/ActionRunnable.java b/core/src/main/java/org/elasticsearch/action/ActionRunnable.java index 36c3f4f17fa..78e2249d6f4 100644 --- a/core/src/main/java/org/elasticsearch/action/ActionRunnable.java +++ b/core/src/main/java/org/elasticsearch/action/ActionRunnable.java @@ -22,11 +22,11 @@ package org.elasticsearch.action; import org.elasticsearch.common.util.concurrent.AbstractRunnable; /** - * Base class for {@link Runnable}s that need to call {@link ActionListener#onFailure(Throwable)} in case an uncaught + * Base class for {@link Runnable}s that need to call {@link ActionListener#onFailure(Exception)} in case an uncaught * exception or error is thrown while the actual action is run. */ public abstract class ActionRunnable extends AbstractRunnable { - + protected final ActionListener listener; public ActionRunnable(ActionListener listener) { @@ -34,11 +34,11 @@ public abstract class ActionRunnable extends AbstractRunnable { } /** - * Calls the action listeners {@link ActionListener#onFailure(Throwable)} method with the given exception. + * Calls the action listeners {@link ActionListener#onFailure(Exception)} method with the given exception. * This method is invoked for all exception thrown by {@link #doRun()} */ @Override - public void onFailure(Throwable t) { - listener.onFailure(t); + public void onFailure(Exception e) { + listener.onFailure(e); } } diff --git a/core/src/main/java/org/elasticsearch/action/LatchedActionListener.java b/core/src/main/java/org/elasticsearch/action/LatchedActionListener.java index fb0fd81a7be..e5e0af93072 100644 --- a/core/src/main/java/org/elasticsearch/action/LatchedActionListener.java +++ b/core/src/main/java/org/elasticsearch/action/LatchedActionListener.java @@ -45,7 +45,7 @@ public class LatchedActionListener implements ActionListener { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { try { delegate.onFailure(e); } finally { diff --git a/core/src/main/java/org/elasticsearch/action/TaskOperationFailure.java b/core/src/main/java/org/elasticsearch/action/TaskOperationFailure.java index 67436f31772..f14b0606c71 100644 --- a/core/src/main/java/org/elasticsearch/action/TaskOperationFailure.java +++ b/core/src/main/java/org/elasticsearch/action/TaskOperationFailure.java @@ -43,15 +43,15 @@ public final class TaskOperationFailure implements Writeable, ToXContent { private final long taskId; - private final Throwable reason; + private final Exception reason; private final RestStatus status; - public TaskOperationFailure(String nodeId, long taskId, Throwable t) { + public TaskOperationFailure(String nodeId, long taskId, Exception e) { this.nodeId = nodeId; this.taskId = taskId; - this.reason = t; - status = ExceptionsHelper.status(t); + this.reason = e; + status = ExceptionsHelper.status(e); } /** @@ -60,7 +60,7 @@ public final class TaskOperationFailure implements Writeable, ToXContent { public TaskOperationFailure(StreamInput in) throws IOException { nodeId = in.readString(); taskId = in.readLong(); - reason = in.readThrowable(); + reason = in.readException(); status = RestStatus.readFrom(in); } diff --git a/core/src/main/java/org/elasticsearch/action/admin/cluster/allocation/TransportClusterAllocationExplainAction.java b/core/src/main/java/org/elasticsearch/action/admin/cluster/allocation/TransportClusterAllocationExplainAction.java index 121dfe6f682..d63a7ff8968 100644 --- a/core/src/main/java/org/elasticsearch/action/admin/cluster/allocation/TransportClusterAllocationExplainAction.java +++ b/core/src/main/java/org/elasticsearch/action/admin/cluster/allocation/TransportClusterAllocationExplainAction.java @@ -145,7 +145,7 @@ public class TransportClusterAllocationExplainAction // No copies of the data storeCopy = ClusterAllocationExplanation.StoreCopy.NONE; } else { - final Throwable storeErr = storeStatus.getStoreException(); + final Exception storeErr = storeStatus.getStoreException(); if (storeErr != null) { if (ExceptionsHelper.unwrapCause(storeErr) instanceof CorruptIndexException) { storeCopy = ClusterAllocationExplanation.StoreCopy.CORRUPT; @@ -323,7 +323,7 @@ public class TransportClusterAllocationExplainAction } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { listener.onFailure(e); } }); diff --git a/core/src/main/java/org/elasticsearch/action/admin/cluster/health/TransportClusterHealthAction.java b/core/src/main/java/org/elasticsearch/action/admin/cluster/health/TransportClusterHealthAction.java index de616c61907..7d0a6288922 100644 --- a/core/src/main/java/org/elasticsearch/action/admin/cluster/health/TransportClusterHealthAction.java +++ b/core/src/main/java/org/elasticsearch/action/admin/cluster/health/TransportClusterHealthAction.java @@ -104,9 +104,9 @@ public class TransportClusterHealthAction extends TransportMasterNodeReadAction< } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); - listener.onFailure(t); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); + listener.onFailure(e); } @Override diff --git a/core/src/main/java/org/elasticsearch/action/admin/cluster/node/tasks/get/TransportGetTaskAction.java b/core/src/main/java/org/elasticsearch/action/admin/cluster/node/tasks/get/TransportGetTaskAction.java index 477f646fe39..318ea031792 100644 --- a/core/src/main/java/org/elasticsearch/action/admin/cluster/node/tasks/get/TransportGetTaskAction.java +++ b/core/src/main/java/org/elasticsearch/action/admin/cluster/node/tasks/get/TransportGetTaskAction.java @@ -154,8 +154,8 @@ public class TransportGetTaskAction extends HandledTransportAction(toResolve), request.ignoreUnavailable())); } listener.onResponse(new GetSnapshotsResponse(snapshotInfoBuilder)); - } catch (Throwable t) { - listener.onFailure(t); + } catch (Exception e) { + listener.onFailure(e); } } diff --git a/core/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/restore/TransportRestoreSnapshotAction.java b/core/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/restore/TransportRestoreSnapshotAction.java index a38fbce46c2..070db6c5248 100644 --- a/core/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/restore/TransportRestoreSnapshotAction.java +++ b/core/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/restore/TransportRestoreSnapshotAction.java @@ -94,7 +94,7 @@ public class TransportRestoreSnapshotAction extends TransportMasterNodeAction currentSnapshots = snapshotsService.currentSnapshots(request.repository(), Arrays.asList(request.snapshots())); listener.onResponse(buildResponse(request, currentSnapshots, nodeSnapshotStatuses)); - } catch (Throwable e) { + } catch (Exception e) { listener.onFailure(e); } } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { listener.onFailure(e); } }); diff --git a/core/src/main/java/org/elasticsearch/action/admin/indices/alias/TransportIndicesAliasesAction.java b/core/src/main/java/org/elasticsearch/action/admin/indices/alias/TransportIndicesAliasesAction.java index 218b84e68ae..3ae7d7ebb7c 100644 --- a/core/src/main/java/org/elasticsearch/action/admin/indices/alias/TransportIndicesAliasesAction.java +++ b/core/src/main/java/org/elasticsearch/action/admin/indices/alias/TransportIndicesAliasesAction.java @@ -119,7 +119,7 @@ public class TransportIndicesAliasesAction extends TransportMasterNodeAction responses, int idx, ActionRequest request, String index, Throwable e) { + private boolean setResponseFailureIfIndexMatches(AtomicArray responses, int idx, ActionRequest request, String index, Exception e) { if (request instanceof IndexRequest) { IndexRequest indexRequest = (IndexRequest) request; if (index.equals(indexRequest.index())) { @@ -367,7 +368,7 @@ public class TransportBulkAction extends HandledTransportAction> void logFailure(Throwable e, String operation, ShardId shardId, ReplicationRequest request) { - if (ExceptionsHelper.status(e) == RestStatus.CONFLICT) { - logger.trace("{} failed to execute bulk item ({}) {}", e, shardId, operation, request); + private > void logFailure(Throwable t, String operation, ShardId shardId, ReplicationRequest request) { + if (ExceptionsHelper.status(t) == RestStatus.CONFLICT) { + logger.trace("{} failed to execute bulk item ({}) {}", t, shardId, operation, request); } else { - logger.debug("{} failed to execute bulk item ({}) {}", e, shardId, operation, request); + logger.debug("{} failed to execute bulk item ({}) {}", t, shardId, operation, request); } } @@ -200,7 +200,7 @@ public class TransportShardBulkAction extends TransportWriteAction= updateRequest.retryOnConflict()) { setResponse(item, new BulkItemResponse(item.id(), OP_TYPE_UPDATE, - new BulkItemResponse.Failure(request.index(), updateRequest.type(), updateRequest.id(), t))); + new BulkItemResponse.Failure(request.index(), updateRequest.type(), updateRequest.id(), e))); } } else { // rethrow the failure if we are going to retry on primary and let parent failure to handle it - if (retryPrimaryException(t)) { + if (retryPrimaryException(e)) { // restore updated versions... for (int j = 0; j < requestIndex; j++) { applyVersion(request.items()[j], preVersions[j], preVersionTypes[j]); } - throw (ElasticsearchException) t; + throw (ElasticsearchException) e; } // if its a conflict failure, and we already executed the request on a primary (and we execute it // again, due to primary relocation and only processing up to N bulk items when the shard gets closed) // then just use the response we got from the successful execution - if (item.getPrimaryResponse() != null && isConflictException(t)) { + if (item.getPrimaryResponse() != null && isConflictException(e)) { setResponse(item, item.getPrimaryResponse()); } else if (updateResult.result == null) { - setResponse(item, new BulkItemResponse(item.id(), OP_TYPE_UPDATE, new BulkItemResponse.Failure(request.index(), updateRequest.type(), updateRequest.id(), t))); + setResponse(item, new BulkItemResponse(item.id(), OP_TYPE_UPDATE, new BulkItemResponse.Failure(request.index(), updateRequest.type(), updateRequest.id(), e))); } else { switch (updateResult.result.operation()) { case UPSERT: case INDEX: IndexRequest indexRequest = updateResult.request(); - logFailure(t, "index", request.shardId(), indexRequest); + logFailure(e, "index", request.shardId(), indexRequest); setResponse(item, new BulkItemResponse(item.id(), OP_TYPE_UPDATE, - new BulkItemResponse.Failure(request.index(), indexRequest.type(), indexRequest.id(), t))); + new BulkItemResponse.Failure(request.index(), indexRequest.type(), indexRequest.id(), e))); break; case DELETE: DeleteRequest deleteRequest = updateResult.request(); - logFailure(t, "delete", request.shardId(), deleteRequest); + logFailure(e, "delete", request.shardId(), deleteRequest); setResponse(item, new BulkItemResponse(item.id(), OP_TYPE_DELETE, - new BulkItemResponse.Failure(request.index(), deleteRequest.type(), deleteRequest.id(), t))); + new BulkItemResponse.Failure(request.index(), deleteRequest.type(), deleteRequest.id(), e))); break; } } @@ -335,7 +335,7 @@ public class TransportShardBulkAction extends TransportWriteAction shardIndexOperation(BulkShardRequest request, IndexRequest indexRequest, IndexMetaData metaData, - IndexShard indexShard, boolean processed) throws Throwable { + IndexShard indexShard, boolean processed) throws Exception { MappingMetaData mappingMd = metaData.mappingOrDefault(indexRequest.type()); if (!processed) { @@ -406,26 +406,26 @@ public class TransportShardBulkAction extends TransportWriteAction result = TransportDeleteAction.executeDeleteRequestOnPrimary(deleteRequest, indexShard); return new UpdateResult(translate, deleteRequest, result); - } catch (Throwable t) { - t = ExceptionsHelper.unwrapCause(t); + } catch (Exception e) { + final Throwable cause = ExceptionsHelper.unwrapCause(e); boolean retry = false; - if (t instanceof VersionConflictEngineException) { + if (cause instanceof VersionConflictEngineException) { retry = true; } - return new UpdateResult(translate, deleteRequest, retry, t, null); + return new UpdateResult(translate, deleteRequest, retry, cause, null); } case NONE: UpdateResponse updateResponse = translate.action(); @@ -449,7 +449,7 @@ public class TransportShardBulkAction extends TransportWriteAction(response, operation.getTranslogLocation()); } } diff --git a/core/src/main/java/org/elasticsearch/action/ingest/IngestActionFilter.java b/core/src/main/java/org/elasticsearch/action/ingest/IngestActionFilter.java index 31c5ec43bd3..87d45f6ccd1 100644 --- a/core/src/main/java/org/elasticsearch/action/ingest/IngestActionFilter.java +++ b/core/src/main/java/org/elasticsearch/action/ingest/IngestActionFilter.java @@ -104,13 +104,13 @@ public final class IngestActionFilter extends AbstractComponent implements Actio void processBulkIndexRequest(Task task, BulkRequest original, String action, ActionFilterChain chain, ActionListener listener) { long ingestStartTimeInNanos = System.nanoTime(); BulkRequestModifier bulkRequestModifier = new BulkRequestModifier(original); - executionService.executeBulkRequest(() -> bulkRequestModifier, (indexRequest, throwable) -> { - logger.debug("failed to execute pipeline [{}] for document [{}/{}/{}]", throwable, indexRequest.getPipeline(), indexRequest.index(), indexRequest.type(), indexRequest.id()); - bulkRequestModifier.markCurrentItemAsFailed(throwable); - }, (throwable) -> { - if (throwable != null) { - logger.error("failed to execute pipeline for a bulk request", throwable); - listener.onFailure(throwable); + executionService.executeBulkRequest(() -> bulkRequestModifier, (indexRequest, exception) -> { + logger.debug("failed to execute pipeline [{}] for document [{}/{}/{}]", exception, indexRequest.getPipeline(), indexRequest.index(), indexRequest.type(), indexRequest.id()); + bulkRequestModifier.markCurrentItemAsFailed(exception); + }, (exception) -> { + if (exception != null) { + logger.error("failed to execute pipeline for a bulk request", exception); + listener.onFailure(exception); } else { long ingestTookInMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - ingestStartTimeInNanos); BulkRequest bulkRequest = bulkRequestModifier.getBulkRequest(); @@ -188,7 +188,7 @@ public final class IngestActionFilter extends AbstractComponent implements Actio } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { actionListener.onFailure(e); } }; @@ -197,7 +197,7 @@ public final class IngestActionFilter extends AbstractComponent implements Actio } } - void markCurrentItemAsFailed(Throwable e) { + void markCurrentItemAsFailed(Exception e) { IndexRequest indexRequest = (IndexRequest) bulkRequest.requests().get(currentSlot); // We hit a error during preprocessing a request, so we: // 1) Remember the request item slot from the bulk, so that we're done processing all requests we know what failed @@ -233,7 +233,7 @@ public final class IngestActionFilter extends AbstractComponent implements Actio } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { actionListener.onFailure(e); } } diff --git a/core/src/main/java/org/elasticsearch/action/ingest/PutPipelineTransportAction.java b/core/src/main/java/org/elasticsearch/action/ingest/PutPipelineTransportAction.java index df92567b98d..82cd8d8eb7b 100644 --- a/core/src/main/java/org/elasticsearch/action/ingest/PutPipelineTransportAction.java +++ b/core/src/main/java/org/elasticsearch/action/ingest/PutPipelineTransportAction.java @@ -90,7 +90,7 @@ public class PutPipelineTransportAction extends TransportMasterNodeAction } @Override - public void onFailure(Throwable t) { + public void onFailure(Exception t) { onFirstPhaseResult(shardIndex, shard, node.getId(), shardIt, t); } }); @@ -188,7 +188,7 @@ abstract class AbstractSearchAsyncAction if (xTotalOps == expectedTotalOps) { try { innerMoveToSecondPhase(); - } catch (Throwable e) { + } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("{}: Failed to execute [{}] while moving to second phase", e, shardIt.shardId(), request); } @@ -201,33 +201,34 @@ abstract class AbstractSearchAsyncAction } void onFirstPhaseResult(final int shardIndex, @Nullable ShardRouting shard, @Nullable String nodeId, - final ShardIterator shardIt, Throwable t) { + final ShardIterator shardIt, Exception e) { // we always add the shard failure for a specific shard instance // we do make sure to clean it on a successful response from a shard SearchShardTarget shardTarget = new SearchShardTarget(nodeId, shardIt.shardId().getIndex(), shardIt.shardId().getId()); - addShardFailure(shardIndex, shardTarget, t); + addShardFailure(shardIndex, shardTarget, e); if (totalOps.incrementAndGet() == expectedTotalOps) { if (logger.isDebugEnabled()) { - if (t != null && !TransportActions.isShardNotAvailableException(t)) { - logger.debug("{}: Failed to execute [{}]", t, shard != null ? shard.shortSummary() : shardIt.shardId(), request); + if (e != null && !TransportActions.isShardNotAvailableException(e)) { + logger.debug("{}: Failed to execute [{}]", e, shard != null ? shard.shortSummary() : shardIt.shardId(), request); } else if (logger.isTraceEnabled()) { - logger.trace("{}: Failed to execute [{}]", t, shard, request); + logger.trace("{}: Failed to execute [{}]", e, shard, request); } } final ShardSearchFailure[] shardSearchFailures = buildShardFailures(); if (successfulOps.get() == 0) { if (logger.isDebugEnabled()) { - logger.debug("All shards failed for phase: [{}]", t, firstPhaseName()); + logger.debug("All shards failed for phase: [{}]", e, firstPhaseName()); } // no successful ops, raise an exception - raiseEarlyFailure(new SearchPhaseExecutionException(firstPhaseName(), "all shards failed", t, shardSearchFailures)); + raiseEarlyFailure(new SearchPhaseExecutionException(firstPhaseName(), "all shards failed", e, shardSearchFailures)); } else { try { innerMoveToSecondPhase(); - } catch (Throwable e) { - raiseEarlyFailure(new ReduceSearchPhaseException(firstPhaseName(), "", e, shardSearchFailures)); + } catch (Exception inner) { + inner.addSuppressed(e); + raiseEarlyFailure(new ReduceSearchPhaseException(firstPhaseName(), "", inner, shardSearchFailures)); } } } else { @@ -235,20 +236,21 @@ abstract class AbstractSearchAsyncAction final boolean lastShard = nextShard == null; // trace log this exception if (logger.isTraceEnabled()) { - logger.trace("{}: Failed to execute [{}] lastShard [{}]", t, shard != null ? shard.shortSummary() : shardIt.shardId(), + logger.trace("{}: Failed to execute [{}] lastShard [{}]", e, shard != null ? shard.shortSummary() : shardIt.shardId(), request, lastShard); } if (!lastShard) { try { performFirstPhase(shardIndex, shardIt, nextShard); - } catch (Throwable t1) { - onFirstPhaseResult(shardIndex, shard, shard.currentNodeId(), shardIt, t1); + } catch (Exception inner) { + inner.addSuppressed(e); + onFirstPhaseResult(shardIndex, shard, shard.currentNodeId(), shardIt, inner); } } else { // no more shards active, add a failure if (logger.isDebugEnabled() && !logger.isTraceEnabled()) { // do not double log this exception - if (t != null && !TransportActions.isShardNotAvailableException(t)) { - logger.debug("{}: Failed to execute [{}] lastShard [{}]", t, + if (e != null && !TransportActions.isShardNotAvailableException(e)) { + logger.debug("{}: Failed to execute [{}] lastShard [{}]", e, shard != null ? shard.shortSummary() : shardIt.shardId(), request, lastShard); } } @@ -269,9 +271,9 @@ abstract class AbstractSearchAsyncAction return failures; } - protected final void addShardFailure(final int shardIndex, @Nullable SearchShardTarget shardTarget, Throwable t) { + protected final void addShardFailure(final int shardIndex, @Nullable SearchShardTarget shardTarget, Exception e) { // we don't aggregate shard failures on non active shards (but do keep the header counts right) - if (TransportActions.isShardNotAvailableException(t)) { + if (TransportActions.isShardNotAvailableException(e)) { return; } @@ -285,26 +287,27 @@ abstract class AbstractSearchAsyncAction } ShardSearchFailure failure = shardFailures.get(shardIndex); if (failure == null) { - shardFailures.set(shardIndex, new ShardSearchFailure(t, shardTarget)); + shardFailures.set(shardIndex, new ShardSearchFailure(e, shardTarget)); } else { // the failure is already present, try and not override it with an exception that is less meaningless // for example, getting illegal shard state - if (TransportActions.isReadOverrideException(t)) { - shardFailures.set(shardIndex, new ShardSearchFailure(t, shardTarget)); + if (TransportActions.isReadOverrideException(e)) { + shardFailures.set(shardIndex, new ShardSearchFailure(e, shardTarget)); } } } - private void raiseEarlyFailure(Throwable t) { + private void raiseEarlyFailure(Exception e) { for (AtomicArray.Entry entry : firstResults.asList()) { try { DiscoveryNode node = nodes.get(entry.value.shardTarget().nodeId()); sendReleaseSearchContext(entry.value.id(), node); - } catch (Throwable t1) { - logger.trace("failed to release context", t1); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.trace("failed to release context", inner); } } - listener.onFailure(t); + listener.onFailure(e); } /** @@ -324,8 +327,8 @@ abstract class AbstractSearchAsyncAction try { DiscoveryNode node = nodes.get(entry.value.queryResult().shardTarget().nodeId()); sendReleaseSearchContext(entry.value.queryResult().id(), node); - } catch (Throwable t1) { - logger.trace("failed to release context", t1); + } catch (Exception e) { + logger.trace("failed to release context", e); } } } diff --git a/core/src/main/java/org/elasticsearch/action/search/MultiSearchResponse.java b/core/src/main/java/org/elasticsearch/action/search/MultiSearchResponse.java index bc23c11ceac..f1b84812019 100644 --- a/core/src/main/java/org/elasticsearch/action/search/MultiSearchResponse.java +++ b/core/src/main/java/org/elasticsearch/action/search/MultiSearchResponse.java @@ -29,7 +29,6 @@ import org.elasticsearch.common.io.stream.Streamable; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.rest.RestStatus; import java.io.IOException; import java.util.Arrays; @@ -45,22 +44,22 @@ public class MultiSearchResponse extends ActionResponse implements Iterable extends AdapterAction // we use a timeout of 0 to by pass assertion forbidding to call actionGet() (blocking) on a network thread. // here we know we will never block listener.onResponse(actionGet(0)); - } catch (Throwable e) { + } catch (Exception e) { listener.onFailure(e); } } diff --git a/core/src/main/java/org/elasticsearch/action/support/AdapterActionFuture.java b/core/src/main/java/org/elasticsearch/action/support/AdapterActionFuture.java index ec2db7a22b2..eab486f4929 100644 --- a/core/src/main/java/org/elasticsearch/action/support/AdapterActionFuture.java +++ b/core/src/main/java/org/elasticsearch/action/support/AdapterActionFuture.java @@ -98,7 +98,7 @@ public abstract class AdapterActionFuture extends BaseFuture implements } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { setException(e); } diff --git a/core/src/main/java/org/elasticsearch/action/support/DefaultShardOperationFailedException.java b/core/src/main/java/org/elasticsearch/action/support/DefaultShardOperationFailedException.java index 676949e367d..e584b2d8037 100644 --- a/core/src/main/java/org/elasticsearch/action/support/DefaultShardOperationFailedException.java +++ b/core/src/main/java/org/elasticsearch/action/support/DefaultShardOperationFailedException.java @@ -54,11 +54,11 @@ public class DefaultShardOperationFailedException implements ShardOperationFaile this.status = e.status(); } - public DefaultShardOperationFailedException(String index, int shardId, Throwable t) { + public DefaultShardOperationFailedException(String index, int shardId, Throwable reason) { this.index = index; this.shardId = shardId; - this.reason = t; - status = ExceptionsHelper.status(t); + this.reason = reason; + this.status = ExceptionsHelper.status(reason); } @Override @@ -98,7 +98,7 @@ public class DefaultShardOperationFailedException implements ShardOperationFaile index = in.readString(); } shardId = in.readVInt(); - reason = in.readThrowable(); + reason = in.readException(); status = RestStatus.readFrom(in); } diff --git a/core/src/main/java/org/elasticsearch/action/support/DelegatingActionListener.java b/core/src/main/java/org/elasticsearch/action/support/DelegatingActionListener.java index 9e7c2205270..c02de8410cf 100644 --- a/core/src/main/java/org/elasticsearch/action/support/DelegatingActionListener.java +++ b/core/src/main/java/org/elasticsearch/action/support/DelegatingActionListener.java @@ -41,7 +41,7 @@ public abstract class DelegatingActionListener extends AbstractListenableActionFuture { public PlainListenableActionFuture(ThreadPool threadPool) { @@ -34,4 +31,5 @@ public class PlainListenableActionFuture extends AbstractListenableActionFutu protected T convert(T response) { return response; } + } diff --git a/core/src/main/java/org/elasticsearch/action/support/ThreadedActionListener.java b/core/src/main/java/org/elasticsearch/action/support/ThreadedActionListener.java index e7ab536387e..4ff7cdaa7bd 100644 --- a/core/src/main/java/org/elasticsearch/action/support/ThreadedActionListener.java +++ b/core/src/main/java/org/elasticsearch/action/support/ThreadedActionListener.java @@ -97,14 +97,14 @@ public final class ThreadedActionListener implements ActionListener implements ActionListener, Re } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { taskManager.unregister(task); listener.onFailure(e); } @@ -113,7 +113,7 @@ public abstract class TransportAction, Re } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { if (task != null) { taskManager.unregister(task); } @@ -140,9 +140,9 @@ public abstract class TransportAction, Re if (filters.length == 0) { try { doExecute(task, request, listener); - } catch(Throwable t) { - logger.trace("Error during transport action execution.", t); - listener.onFailure(t); + } catch(Exception e) { + logger.trace("Error during transport action execution.", e); + listener.onFailure(e); } } else { RequestFilterChain requestFilterChain = new RequestFilterChain<>(this, logger); @@ -180,9 +180,9 @@ public abstract class TransportAction, Re } else { listener.onFailure(new IllegalStateException("proceed was called too many times")); } - } catch(Throwable t) { - logger.trace("Error during transport action execution.", t); - listener.onFailure(t); + } catch(Exception e) { + logger.trace("Error during transport action execution.", e); + listener.onFailure(e); } } @@ -221,9 +221,9 @@ public abstract class TransportAction, Re } else { listener.onFailure(new IllegalStateException("proceed was called too many times")); } - } catch (Throwable t) { - logger.trace("Error during transport action execution.", t); - listener.onFailure(t); + } catch (Exception e) { + logger.trace("Error during transport action execution.", e); + listener.onFailure(e); } } } @@ -246,7 +246,7 @@ public abstract class TransportAction, Re } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { listener.onFailure(e); } } @@ -269,17 +269,18 @@ public abstract class TransportAction, Re public void onResponse(Response response) { try { taskManager.persistResult(task, response, delegate); - } catch (Throwable e) { + } catch (Exception e) { delegate.onFailure(e); } } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { try { taskManager.persistResult(task, e, delegate); - } catch (Throwable e1) { - delegate.onFailure(e1); + } catch (Exception inner) { + inner.addSuppressed(e); + delegate.onFailure(inner); } } } diff --git a/core/src/main/java/org/elasticsearch/action/support/TransportActions.java b/core/src/main/java/org/elasticsearch/action/support/TransportActions.java index 950596cb0b6..d27fbaf04f6 100644 --- a/core/src/main/java/org/elasticsearch/action/support/TransportActions.java +++ b/core/src/main/java/org/elasticsearch/action/support/TransportActions.java @@ -27,30 +27,23 @@ import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.index.shard.IllegalIndexShardStateException; import org.elasticsearch.index.shard.ShardNotFoundException; -/** - */ public class TransportActions { - public static boolean isShardNotAvailableException(Throwable t) { - Throwable actual = ExceptionsHelper.unwrapCause(t); - if (actual instanceof ShardNotFoundException || + public static boolean isShardNotAvailableException(final Throwable e) { + final Throwable actual = ExceptionsHelper.unwrapCause(e); + return (actual instanceof ShardNotFoundException || actual instanceof IndexNotFoundException || actual instanceof IllegalIndexShardStateException || actual instanceof NoShardAvailableActionException || actual instanceof UnavailableShardsException || - actual instanceof AlreadyClosedException) { - return true; - } - return false; + actual instanceof AlreadyClosedException); } /** * If a failure is already present, should this failure override it or not for read operations. */ - public static boolean isReadOverrideException(Throwable t) { - if (isShardNotAvailableException(t)) { - return false; - } - return true; + public static boolean isReadOverrideException(Exception e) { + return !isShardNotAvailableException(e); } + } diff --git a/core/src/main/java/org/elasticsearch/action/support/broadcast/TransportBroadcastAction.java b/core/src/main/java/org/elasticsearch/action/support/broadcast/TransportBroadcastAction.java index 182d922fc39..f31e7f74eb8 100644 --- a/core/src/main/java/org/elasticsearch/action/support/broadcast/TransportBroadcastAction.java +++ b/core/src/main/java/org/elasticsearch/action/support/broadcast/TransportBroadcastAction.java @@ -144,7 +144,7 @@ public abstract class TransportBroadcastAction, NodesResponse extends BaseNodesResponse, NodeRequest extends BaseNodeRequest, @@ -226,8 +223,8 @@ public abstract class TransportNodesAction onPrimaryDemoted, Consumer onIgnoredFailure); + void failShard(ShardRouting replica, ShardRouting primary, String message, Exception exception, Runnable onSuccess, + Consumer onPrimaryDemoted, Consumer onIgnoredFailure); } public static class RetryOnPrimaryException extends ElasticsearchException { diff --git a/core/src/main/java/org/elasticsearch/action/support/replication/ReplicationResponse.java b/core/src/main/java/org/elasticsearch/action/support/replication/ReplicationResponse.java index b75cde3f765..c79f8bb7302 100644 --- a/core/src/main/java/org/elasticsearch/action/support/replication/ReplicationResponse.java +++ b/core/src/main/java/org/elasticsearch/action/support/replication/ReplicationResponse.java @@ -175,11 +175,11 @@ public class ReplicationResponse extends ActionResponse { private ShardId shardId; private String nodeId; - private Throwable cause; + private Exception cause; private RestStatus status; private boolean primary; - public Failure(ShardId shardId, @Nullable String nodeId, Throwable cause, RestStatus status, boolean primary) { + public Failure(ShardId shardId, @Nullable String nodeId, Exception cause, RestStatus status, boolean primary) { this.shardId = shardId; this.nodeId = nodeId; this.cause = cause; @@ -251,7 +251,7 @@ public class ReplicationResponse extends ActionResponse { public void readFrom(StreamInput in) throws IOException { shardId = ShardId.readShardId(in); nodeId = in.readOptionalString(); - cause = in.readThrowable(); + cause = in.readException(); status = RestStatus.readFrom(in); primary = in.readBoolean(); } diff --git a/core/src/main/java/org/elasticsearch/action/support/replication/TransportBroadcastReplicationAction.java b/core/src/main/java/org/elasticsearch/action/support/replication/TransportBroadcastReplicationAction.java index 2cab7d78317..e33d10eaa25 100644 --- a/core/src/main/java/org/elasticsearch/action/support/replication/TransportBroadcastReplicationAction.java +++ b/core/src/main/java/org/elasticsearch/action/support/replication/TransportBroadcastReplicationAction.java @@ -93,7 +93,7 @@ public abstract class TransportBroadcastReplicationAction onFailure, Consumer onIgnoredFailure) { + public void failShard(ShardRouting replica, ShardRouting primary, String message, Exception exception, + Runnable onSuccess, Consumer onFailure, Consumer onIgnoredFailure) { shardStateAction.shardFailed( - replica, primary, message, throwable, + replica, primary, message, exception, new ShardStateAction.Listener() { @Override public void onSuccess() { @@ -882,7 +884,7 @@ public abstract class TransportReplicationAction< } @Override - public void onFailure(Throwable shardFailedError) { + public void onFailure(Exception shardFailedError) { if (shardFailedError instanceof ShardStateAction.NoLongerPrimaryShardException) { onFailure.accept(shardFailedError); } else { diff --git a/core/src/main/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationAction.java b/core/src/main/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationAction.java index 760b77469d2..db786cad63f 100644 --- a/core/src/main/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationAction.java +++ b/core/src/main/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationAction.java @@ -95,7 +95,7 @@ public abstract class TransportInstanceSingleOperationAction listener) { this.listener = listener; @@ -185,22 +185,22 @@ public abstract class TransportSingleShardAction { @@ -97,7 +100,7 @@ public class TransportUpdateAction extends TransportInstanceSingleOperationActio } @Override - protected boolean retryOnFailure(Throwable e) { + protected boolean retryOnFailure(Exception e) { return TransportActions.isShardNotAvailableException(e); } @@ -125,13 +128,14 @@ public class TransportUpdateAction extends TransportInstanceSingleOperationActio } @Override - public void onFailure(Throwable e) { - if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) { + public void onFailure(Exception e) { + if (unwrapCause(e) instanceof IndexAlreadyExistsException) { // we have the index, do it try { innerExecute(request, listener); - } catch (Throwable e1) { - listener.onFailure(e1); + } catch (Exception inner) { + inner.addSuppressed(e); + listener.onFailure(inner); } } else { listener.onFailure(e); @@ -193,9 +197,9 @@ public class TransportUpdateAction extends TransportInstanceSingleOperationActio } @Override - public void onFailure(Throwable e) { - e = ExceptionsHelper.unwrapCause(e); - if (e instanceof VersionConflictEngineException) { + public void onFailure(Exception e) { + final Throwable cause = ExceptionsHelper.unwrapCause(e); + if (cause instanceof VersionConflictEngineException) { if (retryCount < request.retryOnConflict()) { logger.trace("Retry attempt [{}] of [{}] on version conflict on [{}][{}][{}]", retryCount + 1, request.retryOnConflict(), request.index(), request.getShardId(), request.id()); @@ -208,7 +212,7 @@ public class TransportUpdateAction extends TransportInstanceSingleOperationActio return; } } - listener.onFailure(e); + listener.onFailure(cause instanceof Exception ? (Exception) cause : new NotSerializableExceptionWrapper(cause)); } }); break; @@ -226,9 +230,9 @@ public class TransportUpdateAction extends TransportInstanceSingleOperationActio } @Override - public void onFailure(Throwable e) { - e = ExceptionsHelper.unwrapCause(e); - if (e instanceof VersionConflictEngineException) { + public void onFailure(Exception e) { + final Throwable cause = unwrapCause(e); + if (cause instanceof VersionConflictEngineException) { if (retryCount < request.retryOnConflict()) { threadPool.executor(executor()).execute(new ActionRunnable(listener) { @Override @@ -239,7 +243,7 @@ public class TransportUpdateAction extends TransportInstanceSingleOperationActio return; } } - listener.onFailure(e); + listener.onFailure(cause instanceof Exception ? (Exception) cause : new NotSerializableExceptionWrapper(cause)); } }); break; @@ -255,9 +259,9 @@ public class TransportUpdateAction extends TransportInstanceSingleOperationActio } @Override - public void onFailure(Throwable e) { - e = ExceptionsHelper.unwrapCause(e); - if (e instanceof VersionConflictEngineException) { + public void onFailure(Exception e) { + final Throwable cause = unwrapCause(e); + if (cause instanceof VersionConflictEngineException) { if (retryCount < request.retryOnConflict()) { threadPool.executor(executor()).execute(new ActionRunnable(listener) { @Override @@ -268,7 +272,7 @@ public class TransportUpdateAction extends TransportInstanceSingleOperationActio return; } } - listener.onFailure(e); + listener.onFailure(cause instanceof Exception ? (Exception) cause : new NotSerializableExceptionWrapper(cause)); } }); break; diff --git a/core/src/main/java/org/elasticsearch/bootstrap/Bootstrap.java b/core/src/main/java/org/elasticsearch/bootstrap/Bootstrap.java index 54cea62e12e..4168e34a74b 100644 --- a/core/src/main/java/org/elasticsearch/bootstrap/Bootstrap.java +++ b/core/src/main/java/org/elasticsearch/bootstrap/Bootstrap.java @@ -125,7 +125,7 @@ final class Bootstrap { // force remainder of JNA to be loaded (if available). try { JNAKernel32Library.getInstance(); - } catch (Throwable ignored) { + } catch (Exception ignored) { // we've already logged this. } @@ -216,7 +216,7 @@ final class Bootstrap { static void init( final boolean foreground, final String pidFile, - final Map esSettings) throws Throwable { + final Map esSettings) throws Exception { // Set the system property before anything has a chance to trigger its use initLoggerPrefix(); @@ -254,7 +254,7 @@ final class Bootstrap { if (!foreground) { closeSysError(); } - } catch (Throwable e) { + } catch (Exception e) { // disable console logging, so user does not see the exception twice (jvm will show it already) if (foreground) { Loggers.disableConsoleLogging(); diff --git a/core/src/main/java/org/elasticsearch/bootstrap/JNANatives.java b/core/src/main/java/org/elasticsearch/bootstrap/JNANatives.java index e55d38a0f72..5a8693b3137 100644 --- a/core/src/main/java/org/elasticsearch/bootstrap/JNANatives.java +++ b/core/src/main/java/org/elasticsearch/bootstrap/JNANatives.java @@ -217,13 +217,13 @@ class JNANatives { if (ret == 1) { LOCAL_SECCOMP_ALL = true; } - } catch (Throwable t) { + } catch (Exception e) { // this is likely to happen unless the kernel is newish, its a best effort at the moment // so we log stacktrace at debug for now... if (logger.isDebugEnabled()) { - logger.debug("unable to install syscall filter", t); + logger.debug("unable to install syscall filter", e); } - logger.warn("unable to install syscall filter: ", t); + logger.warn("unable to install syscall filter: ", e); } } } diff --git a/core/src/main/java/org/elasticsearch/bootstrap/Seccomp.java b/core/src/main/java/org/elasticsearch/bootstrap/Seccomp.java index 46908e60642..2ea6179e200 100644 --- a/core/src/main/java/org/elasticsearch/bootstrap/Seccomp.java +++ b/core/src/main/java/org/elasticsearch/bootstrap/Seccomp.java @@ -611,7 +611,7 @@ final class Seccomp { * This is best effort and OS and architecture dependent. It may throw any Throwable. * @return 0 if we can do this for application threads, 1 for the entire process */ - static int init(Path tmpFile) throws Throwable { + static int init(Path tmpFile) throws Exception { if (Constants.LINUX) { return linuxImpl(); } else if (Constants.MAC_OS_X) { diff --git a/core/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java b/core/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java index 120a4711217..c751b9c43c1 100644 --- a/core/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java +++ b/core/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java @@ -230,9 +230,9 @@ public class TransportClientNodesService extends AbstractComponent implements Cl DiscoveryNode node = nodes.get((index) % nodes.size()); try { callback.doWithNode(node, retryListener); - } catch (Throwable t) { + } catch (Exception e) { //this exception can't come from the TransportService as it doesn't throw exception at all - listener.onFailure(t); + listener.onFailure(e); } } @@ -258,7 +258,7 @@ public class TransportClientNodesService extends AbstractComponent implements Cl } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { if (ExceptionsHelper.unwrapCause(e) instanceof ConnectTransportException) { int i = ++this.i; if (i >= nodes.size()) { @@ -266,9 +266,10 @@ public class TransportClientNodesService extends AbstractComponent implements Cl } else { try { callback.doWithNode(nodes.get((index + i) % nodes.size()), this); - } catch(final Throwable t) { + } catch(final Exception inner) { + inner.addSuppressed(e); // this exception can't come from the TransportService as it doesn't throw exceptions at all - listener.onFailure(t); + listener.onFailure(inner); } } } else { @@ -335,7 +336,7 @@ public class TransportClientNodesService extends AbstractComponent implements Cl try { logger.trace("connecting to node [{}]", node); transportService.connectToNode(node); - } catch (Throwable e) { + } catch (Exception e) { it.remove(); logger.debug("failed to connect to discovered node [{}]", e, node); } @@ -373,7 +374,7 @@ public class TransportClientNodesService extends AbstractComponent implements Cl // its a listed node, light connect to it... logger.trace("connecting to listed node (light) [{}]", listedNode); transportService.connectToNodeLight(listedNode); - } catch (Throwable e) { + } catch (Exception e) { logger.debug("failed to connect to node [{}], removed from nodes list", e, listedNode); newFilteredNodes.add(listedNode); continue; @@ -405,7 +406,7 @@ public class TransportClientNodesService extends AbstractComponent implements Cl logger.debug("node {} didn't return any discovery info, temporarily using transport discovery node", listedNode); newNodes.add(listedNode); } - } catch (Throwable e) { + } catch (Exception e) { logger.info("failed to get node info for {}, disconnecting...", e, listedNode); transportService.disconnectFromNode(listedNode); } @@ -484,7 +485,7 @@ public class TransportClientNodesService extends AbstractComponent implements Cl latch.countDown(); } }); - } catch (Throwable e) { + } catch (Exception e) { logger.info("failed to get local cluster state info for {}, disconnecting...", e, listedNode); transportService.disconnectFromNode(listedNode); latch.countDown(); diff --git a/core/src/main/java/org/elasticsearch/cluster/AckedClusterStateTaskListener.java b/core/src/main/java/org/elasticsearch/cluster/AckedClusterStateTaskListener.java index cdd9b2204ff..148a1dea309 100644 --- a/core/src/main/java/org/elasticsearch/cluster/AckedClusterStateTaskListener.java +++ b/core/src/main/java/org/elasticsearch/cluster/AckedClusterStateTaskListener.java @@ -36,9 +36,9 @@ public interface AckedClusterStateTaskListener extends ClusterStateTaskListener * Called once all the nodes have acknowledged the cluster state update request. Must be * very lightweight execution, since it gets executed on the cluster service thread. * - * @param t optional error that might have been thrown + * @param e optional error that might have been thrown */ - void onAllNodesAcked(@Nullable Throwable t); + void onAllNodesAcked(@Nullable Exception e); /** * Called once the acknowledgement timeout defined by diff --git a/core/src/main/java/org/elasticsearch/cluster/AckedClusterStateUpdateTask.java b/core/src/main/java/org/elasticsearch/cluster/AckedClusterStateUpdateTask.java index b833f6e1879..faf2f30bb3e 100644 --- a/core/src/main/java/org/elasticsearch/cluster/AckedClusterStateUpdateTask.java +++ b/core/src/main/java/org/elasticsearch/cluster/AckedClusterStateUpdateTask.java @@ -58,9 +58,9 @@ public abstract class AckedClusterStateUpdateTask extends ClusterState * Called once all the nodes have acknowledged the cluster state update request. Must be * very lightweight execution, since it gets executed on the cluster service thread. * - * @param t optional error that might have been thrown + * @param e optional error that might have been thrown */ - public void onAllNodesAcked(@Nullable Throwable t) { + public void onAllNodesAcked(@Nullable Exception e) { listener.onResponse(newResponse(true)); } @@ -75,8 +75,8 @@ public abstract class AckedClusterStateUpdateTask extends ClusterState } @Override - public void onFailure(String source, Throwable t) { - listener.onFailure(t); + public void onFailure(String source, Exception e) { + listener.onFailure(e); } /** diff --git a/core/src/main/java/org/elasticsearch/cluster/ClusterStateTaskConfig.java b/core/src/main/java/org/elasticsearch/cluster/ClusterStateTaskConfig.java index 2ef2438991e..0724c05ac21 100644 --- a/core/src/main/java/org/elasticsearch/cluster/ClusterStateTaskConfig.java +++ b/core/src/main/java/org/elasticsearch/cluster/ClusterStateTaskConfig.java @@ -29,7 +29,7 @@ public interface ClusterStateTaskConfig { /** * The timeout for this cluster state update task configuration. If * the cluster state update task isn't processed within this - * timeout, the associated {@link ClusterStateTaskListener#onFailure(String, Throwable)} + * timeout, the associated {@link ClusterStateTaskListener#onFailure(String, Exception)} * is invoked. * * @return the timeout, or null if one is not set diff --git a/core/src/main/java/org/elasticsearch/cluster/ClusterStateTaskExecutor.java b/core/src/main/java/org/elasticsearch/cluster/ClusterStateTaskExecutor.java index 633fce1ac96..c801ff9e95f 100644 --- a/core/src/main/java/org/elasticsearch/cluster/ClusterStateTaskExecutor.java +++ b/core/src/main/java/org/elasticsearch/cluster/ClusterStateTaskExecutor.java @@ -82,13 +82,13 @@ public interface ClusterStateTaskExecutor { return this; } - public Builder failure(T task, Throwable t) { - return result(task, TaskResult.failure(t)); + public Builder failure(T task, Exception e) { + return result(task, TaskResult.failure(e)); } - public Builder failures(Iterable tasks, Throwable t) { + public Builder failures(Iterable tasks, Exception e) { for (T task : tasks) { - failure(task, t); + failure(task, e); } return this; } @@ -106,7 +106,7 @@ public interface ClusterStateTaskExecutor { } final class TaskResult { - private final Throwable failure; + private final Exception failure; private static final TaskResult SUCCESS = new TaskResult(null); @@ -114,11 +114,11 @@ public interface ClusterStateTaskExecutor { return SUCCESS; } - public static TaskResult failure(Throwable failure) { + public static TaskResult failure(Exception failure) { return new TaskResult(failure); } - private TaskResult(Throwable failure) { + private TaskResult(Exception failure) { this.failure = failure; } @@ -126,7 +126,7 @@ public interface ClusterStateTaskExecutor { return this == SUCCESS; } - public Throwable getFailure() { + public Exception getFailure() { assert !isSuccess(); return failure; } @@ -136,7 +136,7 @@ public interface ClusterStateTaskExecutor { * @param onSuccess handler to invoke on success * @param onFailure handler to invoke on failure; the throwable passed through will not be null */ - public void handle(Runnable onSuccess, Consumer onFailure) { + public void handle(Runnable onSuccess, Consumer onFailure) { if (failure == null) { onSuccess.run(); } else { diff --git a/core/src/main/java/org/elasticsearch/cluster/ClusterStateTaskListener.java b/core/src/main/java/org/elasticsearch/cluster/ClusterStateTaskListener.java index 3bf7887cd1c..757c8b0c82e 100644 --- a/core/src/main/java/org/elasticsearch/cluster/ClusterStateTaskListener.java +++ b/core/src/main/java/org/elasticsearch/cluster/ClusterStateTaskListener.java @@ -25,7 +25,7 @@ public interface ClusterStateTaskListener { /** * A callback called when execute fails. */ - void onFailure(String source, Throwable t); + void onFailure(String source, Exception e); /** * called when the task was rejected because the local node is no longer master diff --git a/core/src/main/java/org/elasticsearch/cluster/ClusterStateUpdateTask.java b/core/src/main/java/org/elasticsearch/cluster/ClusterStateUpdateTask.java index c6988bbb8c8..52e4b8dcff1 100644 --- a/core/src/main/java/org/elasticsearch/cluster/ClusterStateUpdateTask.java +++ b/core/src/main/java/org/elasticsearch/cluster/ClusterStateUpdateTask.java @@ -50,16 +50,16 @@ public abstract class ClusterStateUpdateTask implements ClusterStateTaskConfig, * Update the cluster state based on the current state. Return the *same instance* if no state * should be changed. */ - public abstract ClusterState execute(ClusterState currentState) throws Exception; + public abstract ClusterState execute(ClusterState currentState) throws Exception; /** * A callback called when execute fails. */ - public abstract void onFailure(String source, Throwable t); + public abstract void onFailure(String source, Exception e); /** * If the cluster state update task wasn't processed by the provided timeout, call - * {@link #onFailure(String, Throwable)}. May return null to indicate no timeout is needed (default). + * {@link ClusterStateTaskListener#onFailure(String, Exception)}. May return null to indicate no timeout is needed (default). */ @Nullable public TimeValue timeout() { diff --git a/core/src/main/java/org/elasticsearch/cluster/InternalClusterInfoService.java b/core/src/main/java/org/elasticsearch/cluster/InternalClusterInfoService.java index 3101e700327..2e26bad4684 100644 --- a/core/src/main/java/org/elasticsearch/cluster/InternalClusterInfoService.java +++ b/core/src/main/java/org/elasticsearch/cluster/InternalClusterInfoService.java @@ -19,7 +19,6 @@ package org.elasticsearch.cluster; -import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.LatchedActionListener; import org.elasticsearch.action.admin.cluster.node.stats.NodeStats; @@ -30,7 +29,6 @@ import org.elasticsearch.action.admin.indices.stats.IndicesStatsRequest; import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse; import org.elasticsearch.action.admin.indices.stats.ShardStats; import org.elasticsearch.action.admin.indices.stats.TransportIndicesStatsAction; -import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MetaData; @@ -309,7 +307,7 @@ public class InternalClusterInfoService extends AbstractComponent implements Clu } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { if (e instanceof ReceiveTimeoutTransportException) { logger.error("NodeStatsAction timed out for ClusterInfoUpdateJob", e); } else { @@ -339,7 +337,7 @@ public class InternalClusterInfoService extends AbstractComponent implements Clu } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { if (e instanceof ReceiveTimeoutTransportException) { logger.error("IndicesStatsAction timed out for ClusterInfoUpdateJob", e); } else { diff --git a/core/src/main/java/org/elasticsearch/cluster/NodeConnectionsService.java b/core/src/main/java/org/elasticsearch/cluster/NodeConnectionsService.java index 79c4db9dcad..a487bda0db4 100644 --- a/core/src/main/java/org/elasticsearch/cluster/NodeConnectionsService.java +++ b/core/src/main/java/org/elasticsearch/cluster/NodeConnectionsService.java @@ -90,7 +90,7 @@ public class NodeConnectionsService extends AbstractLifecycleComponent { assert current != null : "node " + node + " was removed in event but not in internal nodes"; try { transportService.disconnectFromNode(node); - } catch (Throwable e) { + } catch (Exception e) { logger.warn("failed to disconnect to node [{}]", e, node); } } @@ -123,8 +123,8 @@ public class NodeConnectionsService extends AbstractLifecycleComponent { class ConnectionChecker extends AbstractRunnable { @Override - public void onFailure(Throwable t) { - logger.warn("unexpected error while checking for node reconnects", t); + public void onFailure(Exception e) { + logger.warn("unexpected error while checking for node reconnects", e); } protected void doRun() { diff --git a/core/src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java b/core/src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java index 630852361b4..1668f3f57ed 100644 --- a/core/src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java +++ b/core/src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java @@ -111,7 +111,7 @@ public class ShardStateAction extends AbstractComponent { waitForNewMasterAndRetry(actionName, observer, shardRoutingEntry, listener); } else { logger.warn("{} unexpected failure while sending request [{}] to [{}] for shard [{}]", exp, shardRoutingEntry.getShardRouting().shardId(), actionName, masterNode, shardRoutingEntry); - listener.onFailure(exp instanceof RemoteTransportException ? exp.getCause() : exp); + listener.onFailure(exp instanceof RemoteTransportException ? (Exception) (exp.getCause() instanceof Exception ? exp.getCause() : new ElasticsearchException(exp.getCause())) : exp); } } }); @@ -131,14 +131,13 @@ public class ShardStateAction extends AbstractComponent { /** * Send a shard failed request to the master node to update the * cluster state. - * - * @param shardRouting the shard to fail + * @param shardRouting the shard to fail * @param sourceShardRouting the source shard requesting the failure (must be the shard itself, or the primary shard) * @param message the reason for the failure * @param failure the underlying cause of the failure * @param listener callback upon completion of the request */ - public void shardFailed(final ShardRouting shardRouting, ShardRouting sourceShardRouting, final String message, @Nullable final Throwable failure, Listener listener) { + public void shardFailed(final ShardRouting shardRouting, ShardRouting sourceShardRouting, final String message, @Nullable final Exception failure, Listener listener) { ClusterStateObserver observer = new ClusterStateObserver(clusterService, null, logger, threadPool.getThreadContext()); ShardRoutingEntry shardRoutingEntry = new ShardRoutingEntry(shardRouting, sourceShardRouting, message, failure); sendShardAction(SHARD_FAILED_ACTION_NAME, observer, shardRoutingEntry, listener); @@ -190,12 +189,13 @@ public class ShardStateAction extends AbstractComponent { shardFailedClusterStateTaskExecutor, new ClusterStateTaskListener() { @Override - public void onFailure(String source, Throwable t) { - logger.error("{} unexpected failure while failing shard [{}]", t, request.shardRouting.shardId(), request.shardRouting); + public void onFailure(String source, Exception e) { + logger.error("{} unexpected failure while failing shard [{}]", e, request.shardRouting.shardId(), request.shardRouting); try { - channel.sendResponse(t); - } catch (Throwable channelThrowable) { - logger.warn("{} failed to send failure [{}] while failing shard [{}]", channelThrowable, request.shardRouting.shardId(), t, request.shardRouting); + channel.sendResponse(e); + } catch (Exception channelException) { + channelException.addSuppressed(e); + logger.warn("{} failed to send failure [{}] while failing shard [{}]", channelException, request.shardRouting.shardId(), e, request.shardRouting); } } @@ -204,8 +204,8 @@ public class ShardStateAction extends AbstractComponent { logger.error("{} no longer master while failing shard [{}]", request.shardRouting.shardId(), request.shardRouting); try { channel.sendResponse(new NotMasterException(source)); - } catch (Throwable channelThrowable) { - logger.warn("{} failed to send no longer master while failing shard [{}]", channelThrowable, request.shardRouting.shardId(), request.shardRouting); + } catch (Exception channelException) { + logger.warn("{} failed to send no longer master while failing shard [{}]", channelException, request.shardRouting.shardId(), request.shardRouting); } } @@ -213,8 +213,8 @@ public class ShardStateAction extends AbstractComponent { public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { try { channel.sendResponse(TransportResponse.Empty.INSTANCE); - } catch (Throwable channelThrowable) { - logger.warn("{} failed to send response while failing shard [{}]", channelThrowable, request.shardRouting.shardId(), request.shardRouting); + } catch (Exception channelException) { + logger.warn("{} failed to send response while failing shard [{}]", channelException, request.shardRouting.shardId(), request.shardRouting); } } } @@ -259,10 +259,10 @@ public class ShardStateAction extends AbstractComponent { maybeUpdatedState = ClusterState.builder(currentState).routingResult(result).build(); } batchResultBuilder.successes(tasksToFail); - } catch (Throwable t) { + } catch (Exception e) { // failures are communicated back to the requester // cluster state will not be updated in this case - batchResultBuilder.failures(tasksToFail, t); + batchResultBuilder.failures(tasksToFail, e); } partition @@ -379,16 +379,16 @@ public class ShardStateAction extends AbstractComponent { maybeUpdatedState = ClusterState.builder(currentState).routingResult(result).build(); } builder.successes(tasks); - } catch (Throwable t) { - builder.failures(tasks, t); + } catch (Exception e) { + builder.failures(tasks, e); } return builder.build(maybeUpdatedState); } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); } } @@ -396,12 +396,12 @@ public class ShardStateAction extends AbstractComponent { ShardRouting shardRouting; ShardRouting sourceShardRouting; String message; - Throwable failure; + Exception failure; public ShardRoutingEntry() { } - ShardRoutingEntry(ShardRouting shardRouting, ShardRouting sourceShardRouting, String message, @Nullable Throwable failure) { + ShardRoutingEntry(ShardRouting shardRouting, ShardRouting sourceShardRouting, String message, @Nullable Exception failure) { this.shardRouting = shardRouting; this.sourceShardRouting = sourceShardRouting; this.message = message; @@ -418,7 +418,7 @@ public class ShardStateAction extends AbstractComponent { shardRouting = new ShardRouting(in); sourceShardRouting = new ShardRouting(in); message = in.readString(); - failure = in.readThrowable(); + failure = in.readException(); } @Override @@ -461,9 +461,9 @@ public class ShardStateAction extends AbstractComponent { * Any other exception is communicated to the requester via * this notification. * - * @param t the unexpected cause of the failure on the master + * @param e the unexpected cause of the failure on the master */ - default void onFailure(final Throwable t) { + default void onFailure(final Exception e) { } } diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/AliasValidator.java b/core/src/main/java/org/elasticsearch/cluster/metadata/AliasValidator.java index 647e30cd85c..d98187cc6c1 100644 --- a/core/src/main/java/org/elasticsearch/cluster/metadata/AliasValidator.java +++ b/core/src/main/java/org/elasticsearch/cluster/metadata/AliasValidator.java @@ -84,7 +84,7 @@ public class AliasValidator extends AbstractComponent { if (Strings.hasLength(alias.filter())) { try (XContentParser parser = XContentFactory.xContent(alias.filter()).createParser(alias.filter())) { parser.map(); - } catch (Throwable e) { + } catch (Exception e) { throw new IllegalArgumentException("failed to parse filter for alias [" + alias.name() + "]", e); } } @@ -121,7 +121,7 @@ public class AliasValidator extends AbstractComponent { assert queryShardContext != null; try (XContentParser parser = XContentFactory.xContent(filter).createParser(filter)) { validateAliasFilter(parser, queryShardContext); - } catch (Throwable e) { + } catch (Exception e) { throw new IllegalArgumentException("failed to parse filter for alias [" + alias + "]", e); } } @@ -135,7 +135,7 @@ public class AliasValidator extends AbstractComponent { assert queryShardContext != null; try (XContentParser parser = XContentFactory.xContent(filter).createParser(filter)) { validateAliasFilter(parser, queryShardContext); - } catch (Throwable e) { + } catch (Exception e) { throw new IllegalArgumentException("failed to parse filter for alias [" + alias + "]", e); } } diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataIndexTemplateService.java b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataIndexTemplateService.java index 625f1a0bb56..101f59f3aec 100644 --- a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataIndexTemplateService.java +++ b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataIndexTemplateService.java @@ -83,8 +83,8 @@ public class MetaDataIndexTemplateService extends AbstractComponent { } @Override - public void onFailure(String source, Throwable t) { - listener.onFailure(t); + public void onFailure(String source, Exception e) { + listener.onFailure(e); } @Override @@ -134,7 +134,7 @@ public class MetaDataIndexTemplateService extends AbstractComponent { try { validate(request); - } catch (Throwable e) { + } catch (Exception e) { listener.onFailure(e); return; } @@ -150,8 +150,8 @@ public class MetaDataIndexTemplateService extends AbstractComponent { } @Override - public void onFailure(String source, Throwable t) { - listener.onFailure(t); + public void onFailure(String source, Exception e) { + listener.onFailure(e); } @Override @@ -280,7 +280,7 @@ public class MetaDataIndexTemplateService extends AbstractComponent { void onResponse(PutResponse response); - void onFailure(Throwable t); + void onFailure(Exception e); } public static class PutRequest { @@ -395,6 +395,6 @@ public class MetaDataIndexTemplateService extends AbstractComponent { void onResponse(RemoveResponse response); - void onFailure(Throwable t); + void onFailure(Exception e); } } diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataMappingService.java b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataMappingService.java index a98f2148da8..f22ac75ef67 100644 --- a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataMappingService.java +++ b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataMappingService.java @@ -187,8 +187,8 @@ public class MetaDataMappingService extends AbstractComponent { builder.putMapping(new MappingMetaData(mapper)); } } - } catch (Throwable t) { - logger.warn("[{}] failed to refresh-mapping in cluster state", t, index); + } catch (Exception e) { + logger.warn("[{}] failed to refresh-mapping in cluster state", e, index); } return dirty; } @@ -202,7 +202,7 @@ public class MetaDataMappingService extends AbstractComponent { refreshTask, ClusterStateTaskConfig.build(Priority.HIGH), refreshExecutor, - (source, t) -> logger.warn("failure during [{}]", t, source) + (source, e) -> logger.warn("failure during [{}]", e, source) ); } @@ -233,8 +233,8 @@ public class MetaDataMappingService extends AbstractComponent { } currentState = applyRequest(currentState, request); builder.success(request); - } catch (Throwable t) { - builder.failure(request, t); + } catch (Exception e) { + builder.failure(request, e); } } return builder.build(currentState); @@ -357,8 +357,8 @@ public class MetaDataMappingService extends AbstractComponent { new AckedClusterStateTaskListener() { @Override - public void onFailure(String source, Throwable t) { - listener.onFailure(t); + public void onFailure(String source, Exception e) { + listener.onFailure(e); } @Override @@ -367,7 +367,7 @@ public class MetaDataMappingService extends AbstractComponent { } @Override - public void onAllNodesAcked(@Nullable Throwable t) { + public void onAllNodesAcked(@Nullable Exception e) { listener.onResponse(new ClusterStateUpdateResponse(true)); } diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataUpdateSettingsService.java b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataUpdateSettingsService.java index 8bf7b5edd94..9db777a4794 100644 --- a/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataUpdateSettingsService.java +++ b/core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataUpdateSettingsService.java @@ -146,7 +146,7 @@ public class MetaDataUpdateSettingsService extends AbstractComponent implements } @Override - public void onFailure(Throwable t) { + public void onFailure(Exception t) { for (Index index : indices) { logger.warn("{} fail to auto expand replicas to [{}]", index, fNumberOfReplicas); } diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/DelayedAllocationService.java b/core/src/main/java/org/elasticsearch/cluster/routing/DelayedAllocationService.java index ea0b7e3094c..29d74dd8933 100644 --- a/core/src/main/java/org/elasticsearch/cluster/routing/DelayedAllocationService.java +++ b/core/src/main/java/org/elasticsearch/cluster/routing/DelayedAllocationService.java @@ -96,8 +96,8 @@ public class DelayedAllocationService extends AbstractLifecycleComponent impleme } @Override - public void onFailure(Throwable t) { - logger.warn("failed to submit schedule/execute reroute post unassigned shard", t); + public void onFailure(Exception e) { + logger.warn("failed to submit schedule/execute reroute post unassigned shard", e); removeIfSameTask(DelayedRerouteTask.this); } }); @@ -125,9 +125,9 @@ public class DelayedAllocationService extends AbstractLifecycleComponent impleme } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { removeIfSameTask(this); - logger.warn("failed to schedule/execute reroute post unassigned shard", t); + logger.warn("failed to schedule/execute reroute post unassigned shard", e); } } diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/RoutingService.java b/core/src/main/java/org/elasticsearch/cluster/routing/RoutingService.java index 163057b9b46..cfe48dd711e 100644 --- a/core/src/main/java/org/elasticsearch/cluster/routing/RoutingService.java +++ b/core/src/main/java/org/elasticsearch/cluster/routing/RoutingService.java @@ -109,17 +109,17 @@ public class RoutingService extends AbstractLifecycleComponent { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { rerouting.set(false); ClusterState state = clusterService.state(); if (logger.isTraceEnabled()) { - logger.error("unexpected failure during [{}], current state:\n{}", t, source, state.prettyPrint()); + logger.error("unexpected failure during [{}], current state:\n{}", e, source, state.prettyPrint()); } else { - logger.error("unexpected failure during [{}], current state version [{}]", t, source, state.version()); + logger.error("unexpected failure during [{}], current state version [{}]", e, source, state.version()); } } }); - } catch (Throwable e) { + } catch (Exception e) { rerouting.set(false); ClusterState state = clusterService.state(); logger.warn("failed to reroute routing table, current state:\n{}", e, state.prettyPrint()); diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java b/core/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java index 5d6333972b3..cfa7c771d50 100644 --- a/core/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java +++ b/core/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java @@ -21,7 +21,6 @@ package org.elasticsearch.cluster.routing; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.cluster.ClusterState; -import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.io.stream.StreamInput; @@ -114,7 +113,7 @@ public final class UnassignedInfo implements ToXContent, Writeable { private final long unassignedTimeNanos; // in nanoseconds, used to calculate delay for delayed shard allocation private final boolean delayed; // if allocation of this shard is delayed due to INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING private final String message; - private final Throwable failure; + private final Exception failure; private final int failedAllocations; /** @@ -135,8 +134,8 @@ public final class UnassignedInfo implements ToXContent, Writeable { * @param unassignedTimeMillis the time of unassignment used to display to in our reporting. * @param delayed if allocation of this shard is delayed due to INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING. */ - public UnassignedInfo(Reason reason, @Nullable String message, @Nullable Throwable failure, int failedAllocations, - long unassignedTimeNanos, long unassignedTimeMillis, boolean delayed) { + public UnassignedInfo(Reason reason, @Nullable String message, @Nullable Exception failure, int failedAllocations, + long unassignedTimeNanos, long unassignedTimeMillis, boolean delayed) { this.reason = reason; this.unassignedTimeMillis = unassignedTimeMillis; this.unassignedTimeNanos = unassignedTimeNanos; @@ -158,7 +157,7 @@ public final class UnassignedInfo implements ToXContent, Writeable { this.unassignedTimeNanos = System.nanoTime(); this.delayed = in.readBoolean(); this.message = in.readOptionalString(); - this.failure = in.readThrowable(); + this.failure = in.readException(); this.failedAllocations = in.readVInt(); } @@ -226,7 +225,7 @@ public final class UnassignedInfo implements ToXContent, Writeable { * Returns additional failure exception details if exists. */ @Nullable - public Throwable getFailure() { + public Exception getFailure() { return failure; } diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/FailedRerouteAllocation.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/FailedRerouteAllocation.java index b1b0dfce1fe..c3a397a785b 100644 --- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/FailedRerouteAllocation.java +++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/FailedRerouteAllocation.java @@ -41,9 +41,9 @@ public class FailedRerouteAllocation extends RoutingAllocation { public static class FailedShard { public final ShardRouting shard; public final String message; - public final Throwable failure; + public final Exception failure; - public FailedShard(ShardRouting shard, String message, Throwable failure) { + public FailedShard(ShardRouting shard, String message, Exception failure) { this.shard = shard; this.message = message; this.failure = failure; diff --git a/core/src/main/java/org/elasticsearch/cluster/service/ClusterService.java b/core/src/main/java/org/elasticsearch/cluster/service/ClusterService.java index accb9304d25..10cf6216a86 100644 --- a/core/src/main/java/org/elasticsearch/cluster/service/ClusterService.java +++ b/core/src/main/java/org/elasticsearch/cluster/service/ClusterService.java @@ -547,7 +547,7 @@ public class ClusterService extends AbstractLifecycleComponent { try { List inputs = toExecute.stream().map(tUpdateTask -> tUpdateTask.task).collect(Collectors.toList()); batchResult = executor.execute(previousClusterState, inputs); - } catch (Throwable e) { + } catch (Exception e) { TimeValue executionTime = TimeValue.timeValueMillis(Math.max(0, TimeValue.nsecToMSec(currentTimeInNanos() - startTimeNS))); if (logger.isTraceEnabled()) { logger.trace("failed to execute cluster state update in [{}], state:\nversion [{}], source [{}]\n{}{}{}", e, executionTime, @@ -707,8 +707,8 @@ public class ClusterService extends AbstractLifecycleComponent { if (newClusterState.nodes().isLocalNodeElectedMaster()) { try { ackListener.onNodeAck(newClusterState.nodes().getLocalNode(), null); - } catch (Throwable t) { - logger.debug("error while processing ack for master node [{}]", t, newClusterState.nodes().getLocalNode()); + } catch (Exception e) { + logger.debug("error while processing ack for master node [{}]", e, newClusterState.nodes().getLocalNode()); } } @@ -726,9 +726,9 @@ public class ClusterService extends AbstractLifecycleComponent { logger.debug("processing [{}]: took [{}] done applying updated cluster_state (version: {}, uuid: {})", source, executionTime, newClusterState.version(), newClusterState.stateUUID()); warnAboutSlowTaskIfNeeded(executionTime, source); - } catch (Throwable t) { + } catch (Exception e) { TimeValue executionTime = TimeValue.timeValueMillis(Math.max(0, TimeValue.nsecToMSec(currentTimeInNanos() - startTimeNS))); - logger.warn("failed to apply updated cluster state in [{}]:\nversion [{}], uuid [{}], source [{}]\n{}", t, executionTime, + logger.warn("failed to apply updated cluster state in [{}]:\nversion [{}], uuid [{}], source [{}]\n{}", e, executionTime, newClusterState.version(), newClusterState.stateUUID(), source, newClusterState.prettyPrint()); // TODO: do we want to call updateTask.onFailure here? } @@ -756,11 +756,12 @@ public class ClusterService extends AbstractLifecycleComponent { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { try { - listener.onFailure(source, t); - } catch (Exception e) { - logger.error("exception thrown by listener notifying of failure [{}] from [{}]", e, t, source); + listener.onFailure(source, e); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.error("exception thrown by listener notifying of failure from [{}]", inner, source); } } @@ -805,11 +806,12 @@ public class ClusterService extends AbstractLifecycleComponent { } @Override - public void onAllNodesAcked(@Nullable Throwable t) { + public void onAllNodesAcked(@Nullable Exception e) { try { - listener.onAllNodesAcked(t); - } catch (Exception e) { - logger.error("exception thrown by listener while notifying on all nodes acked [{}]", e, t); + listener.onAllNodesAcked(e); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.error("exception thrown by listener while notifying on all nodes acked", inner); } } @@ -966,9 +968,9 @@ public class ClusterService extends AbstractLifecycleComponent { } @Override - public void onNodeAck(DiscoveryNode node, @Nullable Throwable t) { + public void onNodeAck(DiscoveryNode node, @Nullable Exception e) { for (Discovery.AckListener listener : listeners) { - listener.onNodeAck(node, t); + listener.onNodeAck(node, e); } } @@ -987,7 +989,7 @@ public class ClusterService extends AbstractLifecycleComponent { private final DiscoveryNodes nodes; private final long clusterStateVersion; private final Future ackTimeoutCallback; - private Throwable lastFailure; + private Exception lastFailure; AckCountDownListener(AckedClusterStateTaskListener ackedTaskListener, long clusterStateVersion, DiscoveryNodes nodes, ThreadPool threadPool) { @@ -1013,18 +1015,18 @@ public class ClusterService extends AbstractLifecycleComponent { } @Override - public void onNodeAck(DiscoveryNode node, @Nullable Throwable t) { + public void onNodeAck(DiscoveryNode node, @Nullable Exception e) { if (!ackedTaskListener.mustAck(node)) { //we always wait for the master ack anyway if (!node.equals(nodes.getMasterNode())) { return; } } - if (t == null) { + if (e == null) { logger.trace("ack received from node [{}], cluster_state update (version: {})", node, clusterStateVersion); } else { - this.lastFailure = t; - logger.debug("ack received from node [{}], cluster_state update (version: {})", t, node, clusterStateVersion); + this.lastFailure = e; + logger.debug("ack received from node [{}], cluster_state update (version: {})", e, node, clusterStateVersion); } if (countDown.countDown()) { diff --git a/core/src/main/java/org/elasticsearch/common/MacAddressProvider.java b/core/src/main/java/org/elasticsearch/common/MacAddressProvider.java index 52ebc283f3c..1c6d7b3945b 100644 --- a/core/src/main/java/org/elasticsearch/common/MacAddressProvider.java +++ b/core/src/main/java/org/elasticsearch/common/MacAddressProvider.java @@ -59,7 +59,7 @@ public class MacAddressProvider { byte[] address = null; try { address = getMacAddress(); - } catch (Throwable t) { + } catch (SocketException e) { // address will be set below } diff --git a/core/src/main/java/org/elasticsearch/common/Randomness.java b/core/src/main/java/org/elasticsearch/common/Randomness.java index ddcd3ea90f7..295d7a6bcda 100644 --- a/core/src/main/java/org/elasticsearch/common/Randomness.java +++ b/core/src/main/java/org/elasticsearch/common/Randomness.java @@ -54,7 +54,7 @@ public final class Randomness { Class clazz = Class.forName("com.carrotsearch.randomizedtesting.RandomizedContext"); maybeCurrentMethod = clazz.getMethod("current"); maybeGetRandomMethod = clazz.getMethod("getRandom"); - } catch (Throwable t) { + } catch (Exception e) { maybeCurrentMethod = null; maybeGetRandomMethod = null; } diff --git a/core/src/main/java/org/elasticsearch/common/geo/ShapesAvailability.java b/core/src/main/java/org/elasticsearch/common/geo/ShapesAvailability.java index dff4277e96f..fe33fadb857 100644 --- a/core/src/main/java/org/elasticsearch/common/geo/ShapesAvailability.java +++ b/core/src/main/java/org/elasticsearch/common/geo/ShapesAvailability.java @@ -31,7 +31,7 @@ public class ShapesAvailability { try { Class.forName("org.locationtech.spatial4j.shape.impl.PointImpl"); xSPATIAL4J_AVAILABLE = true; - } catch (Throwable t) { + } catch (ClassNotFoundException ignored) { xSPATIAL4J_AVAILABLE = false; } SPATIAL4J_AVAILABLE = xSPATIAL4J_AVAILABLE; @@ -40,7 +40,7 @@ public class ShapesAvailability { try { Class.forName("com.vividsolutions.jts.geom.GeometryFactory"); xJTS_AVAILABLE = true; - } catch (Throwable t) { + } catch (ClassNotFoundException ignored) { xJTS_AVAILABLE = false; } JTS_AVAILABLE = xJTS_AVAILABLE; diff --git a/core/src/main/java/org/elasticsearch/common/io/stream/StreamInput.java b/core/src/main/java/org/elasticsearch/common/io/stream/StreamInput.java index ab22df57920..1b28adb1cb1 100644 --- a/core/src/main/java/org/elasticsearch/common/io/stream/StreamInput.java +++ b/core/src/main/java/org/elasticsearch/common/io/stream/StreamInput.java @@ -27,6 +27,7 @@ import org.apache.lucene.store.LockObtainFailedException; import org.apache.lucene.util.BitUtil; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.CharsRefBuilder; +import org.elasticsearch.ElasticsearchException; import org.elasticsearch.Version; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; @@ -60,7 +61,6 @@ import java.util.Map; import java.util.function.IntFunction; import java.util.function.Supplier; -import static org.elasticsearch.ElasticsearchException.readException; import static org.elasticsearch.ElasticsearchException.readStackTrace; /** @@ -648,17 +648,17 @@ public abstract class StreamInput extends InputStream { } } - public T readThrowable() throws IOException { + public T readException() throws IOException { if (readBoolean()) { int key = readVInt(); switch (key) { case 0: final int ord = readVInt(); - return (T) readException(this, ord); + return (T) ElasticsearchException.readException(this, ord); case 1: String msg1 = readOptionalString(); String resource1 = readOptionalString(); - return (T) readStackTrace(new CorruptIndexException(msg1, resource1, readThrowable()), this); + return (T) readStackTrace(new CorruptIndexException(msg1, resource1, readException()), this); case 2: String resource2 = readOptionalString(); int version2 = readInt(); @@ -681,67 +681,63 @@ public abstract class StreamInput extends InputStream { case 5: return (T) readStackTrace(new NumberFormatException(readOptionalString()), this); case 6: - return (T) readStackTrace(new IllegalArgumentException(readOptionalString(), readThrowable()), this); + return (T) readStackTrace(new IllegalArgumentException(readOptionalString(), readException()), this); case 7: - return (T) readStackTrace(new AlreadyClosedException(readOptionalString(), readThrowable()), this); + return (T) readStackTrace(new AlreadyClosedException(readOptionalString(), readException()), this); case 8: return (T) readStackTrace(new EOFException(readOptionalString()), this); case 9: - return (T) readStackTrace(new SecurityException(readOptionalString(), readThrowable()), this); + return (T) readStackTrace(new SecurityException(readOptionalString(), readException()), this); case 10: return (T) readStackTrace(new StringIndexOutOfBoundsException(readOptionalString()), this); case 11: return (T) readStackTrace(new ArrayIndexOutOfBoundsException(readOptionalString()), this); case 12: - return (T) readStackTrace(new AssertionError(readOptionalString(), readThrowable()), this); - case 13: return (T) readStackTrace(new FileNotFoundException(readOptionalString()), this); - case 14: + case 13: final int subclass = readVInt(); final String file = readOptionalString(); final String other = readOptionalString(); final String reason = readOptionalString(); readOptionalString(); // skip the msg - it's composed from file, other and reason - final Throwable throwable; + final Exception exception; switch (subclass) { case 0: - throwable = new NoSuchFileException(file, other, reason); + exception = new NoSuchFileException(file, other, reason); break; case 1: - throwable = new NotDirectoryException(file); + exception = new NotDirectoryException(file); break; case 2: - throwable = new DirectoryNotEmptyException(file); + exception = new DirectoryNotEmptyException(file); break; case 3: - throwable = new AtomicMoveNotSupportedException(file, other, reason); + exception = new AtomicMoveNotSupportedException(file, other, reason); break; case 4: - throwable = new FileAlreadyExistsException(file, other, reason); + exception = new FileAlreadyExistsException(file, other, reason); break; case 5: - throwable = new AccessDeniedException(file, other, reason); + exception = new AccessDeniedException(file, other, reason); break; case 6: - throwable = new FileSystemLoopException(file); + exception = new FileSystemLoopException(file); break; case 7: - throwable = new FileSystemException(file, other, reason); + exception = new FileSystemException(file, other, reason); break; default: throw new IllegalStateException("unknown FileSystemException with index " + subclass); } - return (T) readStackTrace(throwable, this); + return (T) readStackTrace(exception, this); + case 14: + return (T) readStackTrace(new IllegalStateException(readOptionalString(), readException()), this); case 15: - return (T) readStackTrace(new OutOfMemoryError(readOptionalString()), this); + return (T) readStackTrace(new LockObtainFailedException(readOptionalString(), readException()), this); case 16: - return (T) readStackTrace(new IllegalStateException(readOptionalString(), readThrowable()), this); - case 17: - return (T) readStackTrace(new LockObtainFailedException(readOptionalString(), readThrowable()), this); - case 18: return (T) readStackTrace(new InterruptedException(readOptionalString()), this); - case 19: - return (T) readStackTrace(new IOException(readOptionalString(), readThrowable()), this); + case 17: + return (T) readStackTrace(new IOException(readOptionalString(), readException()), this); default: assert false : "no such exception for id: " + key; } diff --git a/core/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java b/core/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java index 4ee9c80b891..653dd9676b3 100644 --- a/core/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java +++ b/core/src/main/java/org/elasticsearch/common/io/stream/StreamOutput.java @@ -687,13 +687,11 @@ public abstract class StreamOutput extends OutputStream { } else if (throwable instanceof ArrayIndexOutOfBoundsException) { writeVInt(11); writeCause = false; - } else if (throwable instanceof AssertionError) { - writeVInt(12); } else if (throwable instanceof FileNotFoundException) { - writeVInt(13); + writeVInt(12); writeCause = false; } else if (throwable instanceof FileSystemException) { - writeVInt(14); + writeVInt(13); if (throwable instanceof NoSuchFileException) { writeVInt(0); } else if (throwable instanceof NotDirectoryException) { @@ -715,18 +713,15 @@ public abstract class StreamOutput extends OutputStream { writeOptionalString(((FileSystemException) throwable).getOtherFile()); writeOptionalString(((FileSystemException) throwable).getReason()); writeCause = false; - } else if (throwable instanceof OutOfMemoryError) { - writeVInt(15); - writeCause = false; } else if (throwable instanceof IllegalStateException) { - writeVInt(16); + writeVInt(14); } else if (throwable instanceof LockObtainFailedException) { - writeVInt(17); + writeVInt(15); } else if (throwable instanceof InterruptedException) { - writeVInt(18); + writeVInt(16); writeCause = false; } else if (throwable instanceof IOException) { - writeVInt(19); + writeVInt(17); } else { ElasticsearchException ex; if (throwable instanceof ElasticsearchException && ElasticsearchException.isRegistered(throwable.getClass())) { diff --git a/core/src/main/java/org/elasticsearch/common/lease/Releasables.java b/core/src/main/java/org/elasticsearch/common/lease/Releasables.java index 5e2d5af522d..bfabd20976d 100644 --- a/core/src/main/java/org/elasticsearch/common/lease/Releasables.java +++ b/core/src/main/java/org/elasticsearch/common/lease/Releasables.java @@ -22,6 +22,7 @@ package org.elasticsearch.common.lease; import org.apache.lucene.util.IOUtils; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.Arrays; /** Utility methods to work with {@link Releasable}s. */ @@ -32,9 +33,9 @@ public enum Releasables { try { // this does the right thing with respect to add suppressed and not wrapping errors etc. IOUtils.close(releasables); - } catch (Throwable t) { + } catch (IOException e) { if (ignoreException == false) { - IOUtils.reThrowUnchecked(t); + throw new UncheckedIOException(e); } } } diff --git a/core/src/main/java/org/elasticsearch/common/logging/LoggerMessageFormat.java b/core/src/main/java/org/elasticsearch/common/logging/LoggerMessageFormat.java index f1e135d645c..3b85a42ce96 100644 --- a/core/src/main/java/org/elasticsearch/common/logging/LoggerMessageFormat.java +++ b/core/src/main/java/org/elasticsearch/common/logging/LoggerMessageFormat.java @@ -153,7 +153,7 @@ public class LoggerMessageFormat { try { String oAsString = o.toString(); sbuf.append(oAsString); - } catch (Throwable t) { + } catch (Exception e) { sbuf.append("[FAILED toString()]"); } diff --git a/core/src/main/java/org/elasticsearch/common/network/Cidrs.java b/core/src/main/java/org/elasticsearch/common/network/Cidrs.java index f0bd4fb74c8..1bdd7bf562b 100644 --- a/core/src/main/java/org/elasticsearch/common/network/Cidrs.java +++ b/core/src/main/java/org/elasticsearch/common/network/Cidrs.java @@ -52,9 +52,9 @@ public final class Cidrs { byte[] addressBytes; try { addressBytes = InetAddresses.forString(fields[0]).getAddress(); - } catch (Throwable t) { + } catch (Exception e) { throw new IllegalArgumentException( - String.format(Locale.ROOT, "invalid IPv4/CIDR; unable to parse [%s] as an IP address literal", fields[0]), t + String.format(Locale.ROOT, "invalid IPv4/CIDR; unable to parse [%s] as an IP address literal", fields[0]), e ); } long accumulator = diff --git a/core/src/main/java/org/elasticsearch/common/util/CancellableThreads.java b/core/src/main/java/org/elasticsearch/common/util/CancellableThreads.java index b6edb2db8da..2e5ee110d60 100644 --- a/core/src/main/java/org/elasticsearch/common/util/CancellableThreads.java +++ b/core/src/main/java/org/elasticsearch/common/util/CancellableThreads.java @@ -42,7 +42,7 @@ public class CancellableThreads { } - /** call this will throw an exception if operation was cancelled. Override {@link #onCancel(String, java.lang.Throwable)} for custom failure logic */ + /** call this will throw an exception if operation was cancelled. Override {@link #onCancel(String, Exception)} for custom failure logic */ public synchronized void checkForCancel() { if (isCancelled()) { onCancel(reason, null); @@ -53,11 +53,10 @@ public class CancellableThreads { * called if {@link #checkForCancel()} was invoked after the operation was cancelled. * the default implementation always throws an {@link ExecutionCancelledException}, suppressing * any other exception that occurred before cancellation - * - * @param reason reason for failure supplied by the caller of {@link #cancel} + * @param reason reason for failure supplied by the caller of {@link #cancel} * @param suppressedException any error that was encountered during the execution before the operation was cancelled. */ - protected void onCancel(String reason, @Nullable Throwable suppressedException) { + protected void onCancel(String reason, @Nullable Exception suppressedException) { RuntimeException e = new ExecutionCancelledException("operation was cancelled reason [" + reason + "]"); if (suppressedException != null) { e.addSuppressed(suppressedException); diff --git a/core/src/main/java/org/elasticsearch/common/util/concurrent/AbstractRunnable.java b/core/src/main/java/org/elasticsearch/common/util/concurrent/AbstractRunnable.java index b63cc2e31ca..e2bde346f6f 100644 --- a/core/src/main/java/org/elasticsearch/common/util/concurrent/AbstractRunnable.java +++ b/core/src/main/java/org/elasticsearch/common/util/concurrent/AbstractRunnable.java @@ -35,7 +35,7 @@ public abstract class AbstractRunnable implements Runnable { public final void run() { try { doRun(); - } catch (Throwable t) { + } catch (Exception t) { onFailure(t); } finally { onAfter(); @@ -53,14 +53,14 @@ public abstract class AbstractRunnable implements Runnable { /** * This method is invoked for all exception thrown by {@link #doRun()} */ - public abstract void onFailure(Throwable t); + public abstract void onFailure(Exception e); /** * This should be executed if the thread-pool executing this action rejected the execution. - * The default implementation forwards to {@link #onFailure(Throwable)} + * The default implementation forwards to {@link #onFailure(Exception)} */ - public void onRejection(Throwable t) { - onFailure(t); + public void onRejection(Exception e) { + onFailure(e); } /** diff --git a/core/src/main/java/org/elasticsearch/common/util/concurrent/ThreadBarrier.java b/core/src/main/java/org/elasticsearch/common/util/concurrent/ThreadBarrier.java index a3d10ff825f..967f0c890d2 100644 --- a/core/src/main/java/org/elasticsearch/common/util/concurrent/ThreadBarrier.java +++ b/core/src/main/java/org/elasticsearch/common/util/concurrent/ThreadBarrier.java @@ -24,7 +24,6 @@ import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; - /** * A synchronization aid that allows a set of threads to all wait for each other * to reach a common barrier point. Barriers are useful in programs involving a @@ -55,9 +54,9 @@ import java.util.concurrent.TimeoutException; * process(); * barrier.await(); //wait for all threads to process * } - * catch(Throwable t){ - * log("Worker thread caught exception", t); - * barrier.reset(t); + * catch(Exception e){ + * log("Worker thread caught exception", e); + * barrier.reset(e); * } * } * } @@ -88,9 +87,9 @@ import java.util.concurrent.TimeoutException; * Assert.assertFalse("Exceeded notification count", * actualNotificationCount > EXPECTED_COUNT); * } - * catch(Throwable t) { - * log("Worker thread caught exception", t); - * barrier.reset(t); + * catch(Exception e) { + * log("Worker thread caught exception", e); + * barrier.reset(e); * } * } * @@ -118,9 +117,9 @@ import java.util.concurrent.TimeoutException; public class ThreadBarrier extends CyclicBarrier { /** * The cause of a {@link BrokenBarrierException} and {@link TimeoutException} - * thrown from an await() when {@link #reset(Throwable)} was invoked. + * thrown from an await() when {@link #reset(Exception)} was invoked. */ - private Throwable cause; + private Exception cause; public ThreadBarrier(int parties) { super(parties); @@ -166,7 +165,7 @@ public class ThreadBarrier extends CyclicBarrier { * * @param cause The cause of the BrokenBarrierException */ - public synchronized void reset(Throwable cause) { + public synchronized void reset(Exception cause) { if (!isBroken()) { super.reset(); } @@ -178,7 +177,7 @@ public class ThreadBarrier extends CyclicBarrier { /** * Queries if this barrier is in a broken state. Note that if - * {@link #reset(Throwable)} is invoked the barrier will remain broken, while + * {@link #reset(Exception)} is invoked the barrier will remain broken, while * {@link #reset()} will reset the barrier to its initial state and * {@link #isBroken()} will return false. * @@ -229,7 +228,7 @@ public class ThreadBarrier extends CyclicBarrier { /** * Initializes the cause of this throwable to the specified value. The cause - * is the throwable that was initialized by {@link #reset(Throwable)}. + * is the throwable that was initialized by {@link #reset(Exception)}. * * @param t throwable. */ @@ -301,4 +300,5 @@ public class ThreadBarrier extends CyclicBarrier { return (time) / 1000000000.0; } } + } diff --git a/core/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java b/core/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java index c715fceb84a..457dcad07cf 100644 --- a/core/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java +++ b/core/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java @@ -433,13 +433,13 @@ public final class ThreadContext implements Closeable, Writeable { } @Override - public void onFailure(Throwable t) { - in.onFailure(t); + public void onFailure(Exception e) { + in.onFailure(e); } @Override - public void onRejection(Throwable t) { - in.onRejection(t); + public void onRejection(Exception e) { + in.onRejection(e); } @Override diff --git a/core/src/main/java/org/elasticsearch/discovery/AckClusterStatePublishResponseHandler.java b/core/src/main/java/org/elasticsearch/discovery/AckClusterStatePublishResponseHandler.java index 24657981c43..26e78989591 100644 --- a/core/src/main/java/org/elasticsearch/discovery/AckClusterStatePublishResponseHandler.java +++ b/core/src/main/java/org/elasticsearch/discovery/AckClusterStatePublishResponseHandler.java @@ -55,19 +55,20 @@ public class AckClusterStatePublishResponseHandler extends BlockingClusterStateP } @Override - public void onFailure(DiscoveryNode node, Throwable t) { + public void onFailure(DiscoveryNode node, Exception e) { try { - super.onFailure(node, t); + super.onFailure(node, e); } finally { - onNodeAck(ackListener, node, t); + onNodeAck(ackListener, node, e); } } - private void onNodeAck(final Discovery.AckListener ackListener, DiscoveryNode node, Throwable t) { + private void onNodeAck(final Discovery.AckListener ackListener, DiscoveryNode node, Exception e) { try { - ackListener.onNodeAck(node, t); - } catch (Throwable t1) { - logger.debug("error while processing ack for node [{}]", t1, node); + ackListener.onNodeAck(node, e); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.debug("error while processing ack for node [{}]", inner, node); } } } diff --git a/core/src/main/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandler.java b/core/src/main/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandler.java index 3fe99face52..72e59675c1b 100644 --- a/core/src/main/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandler.java +++ b/core/src/main/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandler.java @@ -61,7 +61,7 @@ public class BlockingClusterStatePublishResponseHandler { * Called for each failure obtained from non master nodes * @param node the node that replied to the publish event */ - public void onFailure(DiscoveryNode node, Throwable t) { + public void onFailure(DiscoveryNode node, Exception e) { boolean found = pendingNodes.remove(node); assert found : "node [" + node + "] already responded or failed"; latch.countDown(); diff --git a/core/src/main/java/org/elasticsearch/discovery/Discovery.java b/core/src/main/java/org/elasticsearch/discovery/Discovery.java index d7cfb2eeae6..e4addfdd02f 100644 --- a/core/src/main/java/org/elasticsearch/discovery/Discovery.java +++ b/core/src/main/java/org/elasticsearch/discovery/Discovery.java @@ -59,7 +59,7 @@ public interface Discovery extends LifecycleComponent { void publish(ClusterChangedEvent clusterChangedEvent, AckListener ackListener); interface AckListener { - void onNodeAck(DiscoveryNode node, @Nullable Throwable t); + void onNodeAck(DiscoveryNode node, @Nullable Exception e); void onTimeout(); } diff --git a/core/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java b/core/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java index 65767e5e86d..5f8a81ec994 100644 --- a/core/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java +++ b/core/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java @@ -134,8 +134,8 @@ public class LocalDiscovery extends AbstractLifecycleComponent implements Discov } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); } }); } else if (firstMaster != null) { @@ -163,8 +163,8 @@ public class LocalDiscovery extends AbstractLifecycleComponent implements Discov } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); } }); @@ -228,8 +228,8 @@ public class LocalDiscovery extends AbstractLifecycleComponent implements Discov } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); } }); } @@ -370,9 +370,9 @@ public class LocalDiscovery extends AbstractLifecycleComponent implements Discov } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); - publishResponseHandler.onFailure(discovery.localNode(), t); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); + publishResponseHandler.onFailure(discovery.localNode(), e); } @Override diff --git a/core/src/main/java/org/elasticsearch/discovery/zen/NodeJoinController.java b/core/src/main/java/org/elasticsearch/discovery/zen/NodeJoinController.java index 57cfe7e1da5..f0b192d01d0 100644 --- a/core/src/main/java/org/elasticsearch/discovery/zen/NodeJoinController.java +++ b/core/src/main/java/org/elasticsearch/discovery/zen/NodeJoinController.java @@ -131,10 +131,10 @@ public class NodeJoinController extends AbstractComponent { logger.trace("timed out waiting to be elected. waited [{}]. pending master node joins [{}]", timeValue, pendingNodes); } failContextIfNeeded(myElectionContext, "timed out waiting to be elected"); - } catch (Throwable t) { - logger.error("unexpected failure while waiting for incoming joins", t); + } catch (Exception e) { + logger.error("unexpected failure while waiting for incoming joins", e); if (myElectionContext != null) { - failContextIfNeeded(myElectionContext, "unexpected failure while waiting for pending joins [" + t.getMessage() + "]"); + failContextIfNeeded(myElectionContext, "unexpected failure while waiting for pending joins [" + e.getMessage() + "]"); } } } @@ -336,8 +336,8 @@ public class NodeJoinController extends AbstractComponent { } @Override - public void onFailure(String source, Throwable t) { - ElectionContext.this.onFailure(t); + public void onFailure(String source, Exception e) { + ElectionContext.this.onFailure(e); } }; @@ -357,12 +357,12 @@ public class NodeJoinController extends AbstractComponent { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { for (MembershipAction.JoinCallback callback : callbacks) { try { - callback.onFailure(t); - } catch (Exception e) { - logger.error("error during task failure", e); + callback.onFailure(e); + } catch (Exception inner) { + logger.error("error handling task failure [{}]", inner, e); } } } diff --git a/core/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java b/core/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java index 598eb2d6875..e052362b5e2 100644 --- a/core/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java +++ b/core/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java @@ -236,8 +236,8 @@ public class ZenDiscovery extends AbstractLifecycleComponent implements Discover } @Override - public void onFailure(String source, @org.elasticsearch.common.Nullable Throwable t) { - logger.warn("failed to start initial join process", t); + public void onFailure(String source, @org.elasticsearch.common.Nullable Exception e) { + logger.warn("failed to start initial join process", e); } }); } @@ -326,8 +326,8 @@ public class ZenDiscovery extends AbstractLifecycleComponent implements Discover } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); } }); @@ -446,8 +446,8 @@ public class ZenDiscovery extends AbstractLifecycleComponent implements Discover } @Override - public void onFailure(String source, @Nullable Throwable t) { - logger.error("unexpected error while trying to finalize cluster join", t); + public void onFailure(String source, @Nullable Exception e) { + logger.error("unexpected error while trying to finalize cluster join", e); joinThreadControl.markThreadAsDoneAndStartNew(currentThread); } }); @@ -473,20 +473,20 @@ public class ZenDiscovery extends AbstractLifecycleComponent implements Discover logger.trace("joining master {}", masterNode); membership.sendJoinRequestBlocking(masterNode, clusterService.localNode(), joinTimeout); return true; - } catch (Throwable t) { - Throwable unwrap = ExceptionsHelper.unwrapCause(t); + } catch (Exception e) { + final Throwable unwrap = ExceptionsHelper.unwrapCause(e); if (unwrap instanceof NotMasterException) { if (++joinAttempt == this.joinRetryAttempts) { - logger.info("failed to send join request to master [{}], reason [{}], tried [{}] times", masterNode, ExceptionsHelper.detailedMessage(t), joinAttempt); + logger.info("failed to send join request to master [{}], reason [{}], tried [{}] times", masterNode, ExceptionsHelper.detailedMessage(e), joinAttempt); return false; } else { - logger.trace("master {} failed with [{}]. retrying... (attempts done: [{}])", masterNode, ExceptionsHelper.detailedMessage(t), joinAttempt); + logger.trace("master {} failed with [{}]. retrying... (attempts done: [{}])", masterNode, ExceptionsHelper.detailedMessage(e), joinAttempt); } } else { if (logger.isTraceEnabled()) { - logger.trace("failed to send join request to master [{}]", t, masterNode); + logger.trace("failed to send join request to master [{}]", e, masterNode); } else { - logger.info("failed to send join request to master [{}], reason [{}]", masterNode, ExceptionsHelper.detailedMessage(t)); + logger.info("failed to send join request to master [{}], reason [{}]", masterNode, ExceptionsHelper.detailedMessage(e)); } return false; } @@ -527,8 +527,8 @@ public class ZenDiscovery extends AbstractLifecycleComponent implements Discover } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); } }); } else if (node.equals(nodes().getMasterNode())) { @@ -572,8 +572,8 @@ public class ZenDiscovery extends AbstractLifecycleComponent implements Discover } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); } @Override @@ -610,8 +610,8 @@ public class ZenDiscovery extends AbstractLifecycleComponent implements Discover } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); } @Override @@ -659,8 +659,8 @@ public class ZenDiscovery extends AbstractLifecycleComponent implements Discover } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); } @Override @@ -744,13 +744,14 @@ public class ZenDiscovery extends AbstractLifecycleComponent implements Discover } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); if (newClusterState != null) { try { - publishClusterState.pendingStatesQueue().markAsFailed(newClusterState, t); - } catch (Throwable unexpected) { - logger.error("unexpected exception while failing [{}]", unexpected, source); + publishClusterState.pendingStatesQueue().markAsFailed(newClusterState, e); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.error("unexpected exception while failing [{}]", inner, source); } } } @@ -761,8 +762,8 @@ public class ZenDiscovery extends AbstractLifecycleComponent implements Discover if (newClusterState != null) { publishClusterState.pendingStatesQueue().markAsProcessed(newClusterState); } - } catch (Throwable t) { - onFailure(source, t); + } catch (Exception e) { + onFailure(source, e); } } }); @@ -832,7 +833,7 @@ public class ZenDiscovery extends AbstractLifecycleComponent implements Discover // node calling the join request try { membership.sendValidateJoinRequestBlocking(node, state, joinTimeout); - } catch (Throwable e) { + } catch (Exception e) { logger.warn("failed to validate incoming join request from node [{}]", e, node); callback.onFailure(new IllegalStateException("failure when sending a validation request to node", e)); return; @@ -1049,8 +1050,8 @@ public class ZenDiscovery extends AbstractLifecycleComponent implements Discover } @Override - public void onFailure(String source, Throwable t) { - logger.debug("unexpected error during cluster state update task after pings from another master", t); + public void onFailure(String source, Exception e) { + logger.debug("unexpected error during cluster state update task after pings from another master", e); } }); } @@ -1109,8 +1110,8 @@ public class ZenDiscovery extends AbstractLifecycleComponent implements Discover } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); } }); } diff --git a/core/src/main/java/org/elasticsearch/discovery/zen/fd/MasterFaultDetection.java b/core/src/main/java/org/elasticsearch/discovery/zen/fd/MasterFaultDetection.java index 86c9ea86a80..36a9bd426e8 100644 --- a/core/src/main/java/org/elasticsearch/discovery/zen/fd/MasterFaultDetection.java +++ b/core/src/main/java/org/elasticsearch/discovery/zen/fd/MasterFaultDetection.java @@ -369,14 +369,15 @@ public class MasterFaultDetection extends FaultDetection { } @Override - public void onFailure(String source, @Nullable Throwable t) { - if (t == null) { - t = new ElasticsearchException("unknown error while processing ping"); + public void onFailure(String source, @Nullable Exception e) { + if (e == null) { + e = new ElasticsearchException("unknown error while processing ping"); } try { - channel.sendResponse(t); - } catch (IOException e) { - logger.warn("error while sending ping response", e); + channel.sendResponse(e); + } catch (IOException inner) { + inner.addSuppressed(e); + logger.warn("error while sending ping response", inner); } } diff --git a/core/src/main/java/org/elasticsearch/discovery/zen/membership/MembershipAction.java b/core/src/main/java/org/elasticsearch/discovery/zen/membership/MembershipAction.java index 1de3805d67e..961b8d79728 100644 --- a/core/src/main/java/org/elasticsearch/discovery/zen/membership/MembershipAction.java +++ b/core/src/main/java/org/elasticsearch/discovery/zen/membership/MembershipAction.java @@ -50,7 +50,7 @@ public class MembershipAction extends AbstractComponent { public interface JoinCallback { void onSuccess(); - void onFailure(Throwable t); + void onFailure(Exception e); } public interface MembershipListener { @@ -137,17 +137,18 @@ public class MembershipAction extends AbstractComponent { public void onSuccess() { try { channel.sendResponse(TransportResponse.Empty.INSTANCE); - } catch (Throwable t) { - onFailure(t); + } catch (Exception e) { + onFailure(e); } } @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { try { - channel.sendResponse(t); - } catch (Throwable e) { - logger.warn("failed to send back failure on join request", e); + channel.sendResponse(e); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.warn("failed to send back failure on join request", inner); } } }); diff --git a/core/src/main/java/org/elasticsearch/discovery/zen/ping/unicast/UnicastZenPing.java b/core/src/main/java/org/elasticsearch/discovery/zen/ping/unicast/UnicastZenPing.java index d010587dda4..98ccf137b13 100644 --- a/core/src/main/java/org/elasticsearch/discovery/zen/ping/unicast/UnicastZenPing.java +++ b/core/src/main/java/org/elasticsearch/discovery/zen/ping/unicast/UnicastZenPing.java @@ -20,7 +20,6 @@ package org.elasticsearch.discovery.zen.ping.unicast; import com.carrotsearch.hppc.cursors.ObjectCursor; - import org.apache.lucene.util.IOUtils; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.Version; @@ -262,16 +261,16 @@ public class UnicastZenPing extends AbstractLifecycleComponent implements ZenPin } @Override - public void onFailure(Throwable t) { - logger.debug("Ping execution failed", t); + public void onFailure(Exception e) { + logger.debug("Ping execution failed", e); sendPingsHandler.close(); } }); } @Override - public void onFailure(Throwable t) { - logger.debug("Ping execution failed", t); + public void onFailure(Exception e) { + logger.debug("Ping execution failed", e); sendPingsHandler.close(); } }); @@ -418,7 +417,7 @@ public class UnicastZenPing extends AbstractLifecycleComponent implements ZenPin // something went wrong on the other side logger.debug("[{}] received a remote error as a response to ping {}", e, sendPingsHandler.id(), finalNodeToSend); - } catch (Throwable e) { + } catch (Exception e) { logger.warn("[{}] failed send ping to {}", e, sendPingsHandler.id(), finalNodeToSend); } finally { if (!success) { diff --git a/core/src/main/java/org/elasticsearch/discovery/zen/publish/PendingClusterStatesQueue.java b/core/src/main/java/org/elasticsearch/discovery/zen/publish/PendingClusterStatesQueue.java index e591f44d309..24b093627b6 100644 --- a/core/src/main/java/org/elasticsearch/discovery/zen/publish/PendingClusterStatesQueue.java +++ b/core/src/main/java/org/elasticsearch/discovery/zen/publish/PendingClusterStatesQueue.java @@ -51,7 +51,7 @@ public class PendingClusterStatesQueue { void onNewClusterStateProcessed(); - void onNewClusterStateFailed(Throwable t); + void onNewClusterStateFailed(Exception e); } final ArrayList pendingStates = new ArrayList<>(); @@ -97,7 +97,7 @@ public class PendingClusterStatesQueue { * mark that the processing of the given state has failed. All committed states that are {@link ClusterState#supersedes(ClusterState)}-ed * by this failed state, will be failed as well */ - public synchronized void markAsFailed(ClusterState state, Throwable reason) { + public synchronized void markAsFailed(ClusterState state, Exception reason) { final ClusterStateContext failedContext = findState(state.stateUUID()); if (failedContext == null) { throw new IllegalArgumentException("can't resolve failed cluster state with uuid [" + state.stateUUID() + "], version [" + state.version() + "]"); @@ -194,8 +194,9 @@ public class PendingClusterStatesQueue { return null; } - /** clear the incoming queue. any committed state will be failed */ - public synchronized void failAllStatesAndClear(Throwable reason) { + /** clear the incoming queue. any committed state will be failed + */ + public synchronized void failAllStatesAndClear(Exception reason) { for (ClusterStateContext pendingState : pendingStates) { if (pendingState.committed()) { pendingState.listener.onNewClusterStateFailed(reason); diff --git a/core/src/main/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateAction.java b/core/src/main/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateAction.java index 7714f34d0e2..bcdd2f25d4d 100644 --- a/core/src/main/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateAction.java +++ b/core/src/main/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateAction.java @@ -152,21 +152,21 @@ public class PublishClusterStateAction extends AbstractComponent { final BlockingClusterStatePublishResponseHandler publishResponseHandler = new AckClusterStatePublishResponseHandler(nodesToPublishTo, ackListener); sendingController = new SendingController(clusterChangedEvent.state(), minMasterNodes, totalMasterNodes, publishResponseHandler); - } catch (Throwable t) { - throw new Discovery.FailedToCommitClusterStateException("unexpected error while preparing to publish", t); + } catch (Exception e) { + throw new Discovery.FailedToCommitClusterStateException("unexpected error while preparing to publish", e); } try { innerPublish(clusterChangedEvent, nodesToPublishTo, sendingController, sendFullVersion, serializedStates, serializedDiffs); } catch (Discovery.FailedToCommitClusterStateException t) { throw t; - } catch (Throwable t) { + } catch (Exception e) { // try to fail committing, in cause it's still on going - if (sendingController.markAsFailed("unexpected error", t)) { + if (sendingController.markAsFailed("unexpected error", e)) { // signal the change should be rejected - throw new Discovery.FailedToCommitClusterStateException("unexpected error", t); + throw new Discovery.FailedToCommitClusterStateException("unexpected error", e); } else { - throw t; + throw e; } } } @@ -243,7 +243,7 @@ public class PublishClusterStateAction extends AbstractComponent { try { bytes = serializeFullClusterState(clusterState, node.getVersion()); serializedStates.put(node.getVersion(), bytes); - } catch (Throwable e) { + } catch (Exception e) { logger.warn("failed to serialize cluster_state before publishing it to node {}", e, node); sendingController.onNodeSendFailed(node, e); return; @@ -295,9 +295,9 @@ public class PublishClusterStateAction extends AbstractComponent { } } }); - } catch (Throwable t) { - logger.warn("error sending cluster state to {}", t, node); - sendingController.onNodeSendFailed(node, t); + } catch (Exception e) { + logger.warn("error sending cluster state to {}", e, node); + sendingController.onNodeSendFailed(node, e); } } @@ -326,7 +326,7 @@ public class PublishClusterStateAction extends AbstractComponent { sendingController.getPublishResponseHandler().onFailure(node, exp); } }); - } catch (Throwable t) { + } catch (Exception t) { logger.warn("error sending cluster state commit (uuid [{}], version [{}]) to {}", t, clusterState.stateUUID(), clusterState.version(), node); sendingController.getPublishResponseHandler().onFailure(node, t); } @@ -428,18 +428,19 @@ public class PublishClusterStateAction extends AbstractComponent { try { // send a response to the master to indicate that this cluster state has been processed post committing it. channel.sendResponse(TransportResponse.Empty.INSTANCE); - } catch (Throwable e) { + } catch (Exception e) { logger.debug("failed to send response on cluster state processed", e); onNewClusterStateFailed(e); } } @Override - public void onNewClusterStateFailed(Throwable t) { + public void onNewClusterStateFailed(Exception e) { try { - channel.sendResponse(t); - } catch (Throwable e) { - logger.debug("failed to send response on cluster state processed", e); + channel.sendResponse(e); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.debug("failed to send response on cluster state processed", inner); } } }); @@ -592,13 +593,13 @@ public class PublishClusterStateAction extends AbstractComponent { } } - public synchronized void onNodeSendFailed(DiscoveryNode node, Throwable t) { + public synchronized void onNodeSendFailed(DiscoveryNode node, Exception e) { if (node.isMasterNode()) { logger.trace("master node {} failed to ack cluster state version [{}]. processing ... (current pending [{}], needed [{}])", node, clusterState.version(), pendingMasterNodes, neededMastersToCommit); decrementPendingMasterAcksAndChangeForFailure(); } - publishResponseHandler.onFailure(node, t); + publishResponseHandler.onFailure(node, e); } /** @@ -621,7 +622,7 @@ public class PublishClusterStateAction extends AbstractComponent { * * @return true if the publishing was failed and the cluster state is *not* committed **/ - private synchronized boolean markAsFailed(String details, Throwable reason) { + private synchronized boolean markAsFailed(String details, Exception reason) { if (committedOrFailed()) { return committed == false; } diff --git a/core/src/main/java/org/elasticsearch/env/ESFileStore.java b/core/src/main/java/org/elasticsearch/env/ESFileStore.java index 6df242f7ce1..8051c522d03 100644 --- a/core/src/main/java/org/elasticsearch/env/ESFileStore.java +++ b/core/src/main/java/org/elasticsearch/env/ESFileStore.java @@ -169,7 +169,7 @@ class ESFileStore extends FileStore { if (Character.isAlphabetic(driveLetter) == false || root.charAt(1) != ':') { throw new RuntimeException("root isn't a drive letter: " + root); } - } catch (Throwable checkFailed) { + } catch (Exception checkFailed) { // something went wrong, possibleBug.addSuppressed(checkFailed); throw possibleBug; @@ -188,7 +188,7 @@ class ESFileStore extends FileStore { } } throw new RuntimeException("no filestores matched"); - } catch (Throwable weTried) { + } catch (Exception weTried) { IOException newException = new IOException("Unable to retrieve filestore for '" + path + "', tried matching against " + Arrays.toString(fileStores), weTried); newException.addSuppressed(possibleBug); throw newException; diff --git a/core/src/main/java/org/elasticsearch/env/NodeEnvironment.java b/core/src/main/java/org/elasticsearch/env/NodeEnvironment.java index 8815d18769d..6a805584f5c 100644 --- a/core/src/main/java/org/elasticsearch/env/NodeEnvironment.java +++ b/core/src/main/java/org/elasticsearch/env/NodeEnvironment.java @@ -670,10 +670,7 @@ public final class NodeEnvironment extends AbstractComponent implements Closeabl * @throws IllegalStateException if the node is not configured to store local locations */ public Path[] nodeDataPaths() { - assert assertEnvIsLocked(); - if (nodePaths == null || locks == null) { - throw new IllegalStateException("node is not configured to store local location"); - } + assertEnvIsLocked(); Path[] paths = new Path[nodePaths.length]; for(int i=0;i indexFolders = new HashSet<>(); for (NodePath nodePath : nodePaths) { Path indicesLocation = nodePath.indicesPath; @@ -754,7 +751,7 @@ public final class NodeEnvironment extends AbstractComponent implements Closeabl if (nodePaths == null || locks == null) { throw new IllegalStateException("node is not configured to store local location"); } - assert assertEnvIsLocked(); + assertEnvIsLocked(); List paths = new ArrayList<>(nodePaths.length); for (NodePath nodePath : nodePaths) { Path indexFolder = nodePath.indicesPath.resolve(indexFolderName); @@ -778,7 +775,7 @@ public final class NodeEnvironment extends AbstractComponent implements Closeabl if (nodePaths == null || locks == null) { throw new IllegalStateException("node is not configured to store local location"); } - assert assertEnvIsLocked(); + assertEnvIsLocked(); final Set shardIds = new HashSet<>(); final String indexUniquePathId = index.getUUID(); for (final NodePath nodePath : nodePaths) { @@ -829,18 +826,17 @@ public final class NodeEnvironment extends AbstractComponent implements Closeabl } - private boolean assertEnvIsLocked() { + private void assertEnvIsLocked() { if (!closed.get() && locks != null) { for (Lock lock : locks) { try { lock.ensureValid(); } catch (IOException e) { logger.warn("lock assertion failed", e); - return false; + throw new IllegalStateException("environment is not locked", e); } } } - return true; } /** diff --git a/core/src/main/java/org/elasticsearch/gateway/AsyncShardFetch.java b/core/src/main/java/org/elasticsearch/gateway/AsyncShardFetch.java index 737ed7d591c..dc7194b949c 100644 --- a/core/src/main/java/org/elasticsearch/gateway/AsyncShardFetch.java +++ b/core/src/main/java/org/elasticsearch/gateway/AsyncShardFetch.java @@ -274,7 +274,7 @@ public abstract class AsyncShardFetch implements Rel } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { List failures = new ArrayList<>(nodes.length); for (final DiscoveryNode node: nodes) { failures.add(new FailedNodeException(node.getId(), "total failure in fetching", e)); diff --git a/core/src/main/java/org/elasticsearch/gateway/DanglingIndicesState.java b/core/src/main/java/org/elasticsearch/gateway/DanglingIndicesState.java index 2c652fc1481..370778898fc 100644 --- a/core/src/main/java/org/elasticsearch/gateway/DanglingIndicesState.java +++ b/core/src/main/java/org/elasticsearch/gateway/DanglingIndicesState.java @@ -170,7 +170,7 @@ public class DanglingIndicesState extends AbstractComponent { } } ); - } catch (Throwable e) { + } catch (Exception e) { logger.warn("failed to send allocate dangled", e); } } diff --git a/core/src/main/java/org/elasticsearch/gateway/GatewayMetaState.java b/core/src/main/java/org/elasticsearch/gateway/GatewayMetaState.java index 534a73355af..a96b03ee560 100644 --- a/core/src/main/java/org/elasticsearch/gateway/GatewayMetaState.java +++ b/core/src/main/java/org/elasticsearch/gateway/GatewayMetaState.java @@ -50,9 +50,6 @@ import java.util.Set; import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableSet; -/** - * - */ public class GatewayMetaState extends AbstractComponent implements ClusterStateListener { private final NodeEnvironment nodeEnv; @@ -141,7 +138,7 @@ public class GatewayMetaState extends AbstractComponent implements ClusterStateL newPreviouslyWrittenIndices.addAll(previouslyWrittenIndices); previouslyWrittenIndices = unmodifiableSet(newPreviouslyWrittenIndices); } - } catch (Throwable e) { + } catch (Exception e) { success = false; } } @@ -149,7 +146,7 @@ public class GatewayMetaState extends AbstractComponent implements ClusterStateL if (previousMetaData == null || !MetaData.isGlobalStateEquals(previousMetaData, newMetaData)) { try { metaStateService.writeGlobalState("changed", newMetaData); - } catch (Throwable e) { + } catch (Exception e) { success = false; } } @@ -161,7 +158,7 @@ public class GatewayMetaState extends AbstractComponent implements ClusterStateL for (IndexMetaWriteInfo indexMetaWrite : writeInfo) { try { metaStateService.writeIndex(indexMetaWrite.reason, indexMetaWrite.newMetaData); - } catch (Throwable e) { + } catch (Exception e) { success = false; } } diff --git a/core/src/main/java/org/elasticsearch/gateway/GatewayService.java b/core/src/main/java/org/elasticsearch/gateway/GatewayService.java index 746d70db009..3282a8f2a4e 100644 --- a/core/src/main/java/org/elasticsearch/gateway/GatewayService.java +++ b/core/src/main/java/org/elasticsearch/gateway/GatewayService.java @@ -216,11 +216,11 @@ public class GatewayService extends AbstractLifecycleComponent implements Cluste if (recovered.compareAndSet(false, true)) { threadPool.generic().execute(new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - logger.warn("Recovery failed", t); + public void onFailure(Exception e) { + logger.warn("Recovery failed", e); // we reset `recovered` in the listener don't reset it here otherwise there might be a race // that resets it to false while a new recover is already running? - recoveryListener.onFailure("state recovery failed: " + t.getMessage()); + recoveryListener.onFailure("state recovery failed: " + e.getMessage()); } @Override @@ -288,8 +288,8 @@ public class GatewayService extends AbstractLifecycleComponent implements Cluste } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); GatewayRecoveryListener.this.onFailure("failed to updated cluster state"); } diff --git a/core/src/main/java/org/elasticsearch/gateway/LocalAllocateDangledIndices.java b/core/src/main/java/org/elasticsearch/gateway/LocalAllocateDangledIndices.java index 3ee6851f8a5..af8709ccd96 100644 --- a/core/src/main/java/org/elasticsearch/gateway/LocalAllocateDangledIndices.java +++ b/core/src/main/java/org/elasticsearch/gateway/LocalAllocateDangledIndices.java @@ -175,12 +175,13 @@ public class LocalAllocateDangledIndices extends AbstractComponent { } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure during [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure during [{}]", e, source); try { - channel.sendResponse(t); - } catch (Exception e) { - logger.warn("failed send response for allocating dangled", e); + channel.sendResponse(e); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.warn("failed send response for allocating dangled", inner); } } diff --git a/core/src/main/java/org/elasticsearch/gateway/MetaDataStateFormat.java b/core/src/main/java/org/elasticsearch/gateway/MetaDataStateFormat.java index 9a78925368e..9c2d6c80011 100644 --- a/core/src/main/java/org/elasticsearch/gateway/MetaDataStateFormat.java +++ b/core/src/main/java/org/elasticsearch/gateway/MetaDataStateFormat.java @@ -312,7 +312,7 @@ public abstract class MetaDataStateFormat { logger.trace("state id [{}] read from [{}]", id, stateFile.getFileName()); } return state; - } catch (Throwable e) { + } catch (Exception e) { exceptions.add(new IOException("failed to read " + pathAndStateId.toString(), e)); logger.debug("{}: failed to read [{}], ignoring...", e, pathAndStateId.file.toAbsolutePath(), prefix); } diff --git a/core/src/main/java/org/elasticsearch/gateway/MetaStateService.java b/core/src/main/java/org/elasticsearch/gateway/MetaStateService.java index b6f415a9049..b6166c9d545 100644 --- a/core/src/main/java/org/elasticsearch/gateway/MetaStateService.java +++ b/core/src/main/java/org/elasticsearch/gateway/MetaStateService.java @@ -127,7 +127,7 @@ public class MetaStateService extends AbstractComponent { try { IndexMetaData.FORMAT.write(indexMetaData, indexMetaData.getVersion(), nodeEnv.indexPaths(indexMetaData.getIndex())); - } catch (Throwable ex) { + } catch (Exception ex) { logger.warn("[{}]: failed to write index state", ex, index); throw new IOException("failed to write state for [" + index + "]", ex); } @@ -140,7 +140,7 @@ public class MetaStateService extends AbstractComponent { logger.trace("[_global] writing state, reason [{}]", reason); try { MetaData.FORMAT.write(metaData, metaData.version(), nodeEnv.nodeDataPaths()); - } catch (Throwable ex) { + } catch (Exception ex) { logger.warn("[_global]: failed to write global state", ex); throw new IOException("failed to write global state", ex); } diff --git a/core/src/main/java/org/elasticsearch/gateway/TransportNodesListGatewayStartedShards.java b/core/src/main/java/org/elasticsearch/gateway/TransportNodesListGatewayStartedShards.java index 42fc8163706..2ecabf778c7 100644 --- a/core/src/main/java/org/elasticsearch/gateway/TransportNodesListGatewayStartedShards.java +++ b/core/src/main/java/org/elasticsearch/gateway/TransportNodesListGatewayStartedShards.java @@ -245,7 +245,7 @@ public class TransportNodesListGatewayStartedShards extends private long legacyVersion = ShardStateMetaData.NO_VERSION; // for pre-3.0 shards that have not yet been active private String allocationId = null; private boolean primary = false; - private Throwable storeException = null; + private Exception storeException = null; public NodeGatewayStartedShards() { } @@ -255,7 +255,7 @@ public class TransportNodesListGatewayStartedShards extends } public NodeGatewayStartedShards(DiscoveryNode node, long legacyVersion, String allocationId, boolean primary, - Throwable storeException) { + Exception storeException) { super(node); this.legacyVersion = legacyVersion; this.allocationId = allocationId; @@ -275,7 +275,7 @@ public class TransportNodesListGatewayStartedShards extends return this.primary; } - public Throwable storeException() { + public Exception storeException() { return this.storeException; } @@ -286,7 +286,7 @@ public class TransportNodesListGatewayStartedShards extends allocationId = in.readOptionalString(); primary = in.readBoolean(); if (in.readBoolean()) { - storeException = in.readThrowable(); + storeException = in.readException(); } } diff --git a/core/src/main/java/org/elasticsearch/http/HttpServer.java b/core/src/main/java/org/elasticsearch/http/HttpServer.java index 8e3f15c5a24..ccf2d764c05 100644 --- a/core/src/main/java/org/elasticsearch/http/HttpServer.java +++ b/core/src/main/java/org/elasticsearch/http/HttpServer.java @@ -19,11 +19,6 @@ package org.elasticsearch.http; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.concurrent.atomic.AtomicBoolean; - import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.breaker.CircuitBreaker; @@ -45,6 +40,11 @@ import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.RestResponse; import org.elasticsearch.rest.RestStatus; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.concurrent.atomic.AtomicBoolean; + import static org.elasticsearch.rest.RestStatus.FORBIDDEN; import static org.elasticsearch.rest.RestStatus.INTERNAL_SERVER_ERROR; @@ -114,8 +114,8 @@ public class HttpServer extends AbstractLifecycleComponent implements HttpServer // iff we could reserve bytes for the request we need to send the response also over this channel responseChannel = new ResourceHandlingHttpChannel(channel, circuitBreakerService, contentLength); restController.dispatchRequest(request, responseChannel, client, threadContext); - } catch (Throwable t) { - restController.sendErrorResponse(request, responseChannel, t); + } catch (Exception e) { + restController.sendErrorResponse(request, responseChannel, e); } } diff --git a/core/src/main/java/org/elasticsearch/index/CompositeIndexEventListener.java b/core/src/main/java/org/elasticsearch/index/CompositeIndexEventListener.java index acc0d3f8370..97e00b98df9 100644 --- a/core/src/main/java/org/elasticsearch/index/CompositeIndexEventListener.java +++ b/core/src/main/java/org/elasticsearch/index/CompositeIndexEventListener.java @@ -57,8 +57,8 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.shardRoutingChanged(indexShard, oldRouting, newRouting); - } catch (Throwable t) { - logger.warn("[{}] failed to invoke shard touring changed callback", t, indexShard.shardId().getId()); + } catch (Exception e) { + logger.warn("[{}] failed to invoke shard touring changed callback", e, indexShard.shardId().getId()); } } } @@ -68,9 +68,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.afterIndexShardCreated(indexShard); - } catch (Throwable t) { - logger.warn("[{}] failed to invoke after shard created callback", t, indexShard.shardId().getId()); - throw t; + } catch (Exception e) { + logger.warn("[{}] failed to invoke after shard created callback", e, indexShard.shardId().getId()); + throw e; } } } @@ -80,9 +80,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.afterIndexShardStarted(indexShard); - } catch (Throwable t) { - logger.warn("[{}] failed to invoke after shard started callback", t, indexShard.shardId().getId()); - throw t; + } catch (Exception e) { + logger.warn("[{}] failed to invoke after shard started callback", e, indexShard.shardId().getId()); + throw e; } } } @@ -93,9 +93,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.beforeIndexShardClosed(shardId, indexShard, indexSettings); - } catch (Throwable t) { - logger.warn("[{}] failed to invoke before shard closed callback", t, shardId.getId()); - throw t; + } catch (Exception e) { + logger.warn("[{}] failed to invoke before shard closed callback", e, shardId.getId()); + throw e; } } } @@ -106,9 +106,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.afterIndexShardClosed(shardId, indexShard, indexSettings); - } catch (Throwable t) { - logger.warn("[{}] failed to invoke after shard closed callback", t, shardId.getId()); - throw t; + } catch (Exception e) { + logger.warn("[{}] failed to invoke after shard closed callback", e, shardId.getId()); + throw e; } } } @@ -118,9 +118,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.onShardInactive(indexShard); - } catch (Throwable t) { - logger.warn("[{}] failed to invoke on shard inactive callback", t, indexShard.shardId().getId()); - throw t; + } catch (Exception e) { + logger.warn("[{}] failed to invoke on shard inactive callback", e, indexShard.shardId().getId()); + throw e; } } } @@ -130,9 +130,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.indexShardStateChanged(indexShard, previousState, indexShard.state(), reason); - } catch (Throwable t) { - logger.warn("[{}] failed to invoke index shard state changed callback", t, indexShard.shardId().getId()); - throw t; + } catch (Exception e) { + logger.warn("[{}] failed to invoke index shard state changed callback", e, indexShard.shardId().getId()); + throw e; } } } @@ -142,9 +142,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.beforeIndexCreated(index, indexSettings); - } catch (Throwable t) { - logger.warn("failed to invoke before index created callback", t); - throw t; + } catch (Exception e) { + logger.warn("failed to invoke before index created callback", e); + throw e; } } } @@ -154,9 +154,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.afterIndexCreated(indexService); - } catch (Throwable t) { - logger.warn("failed to invoke after index created callback", t); - throw t; + } catch (Exception e) { + logger.warn("failed to invoke after index created callback", e); + throw e; } } } @@ -166,9 +166,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.beforeIndexShardCreated(shardId, indexSettings); - } catch (Throwable t) { - logger.warn("[{}] failed to invoke before shard created callback", t, shardId); - throw t; + } catch (Exception e) { + logger.warn("[{}] failed to invoke before shard created callback", e, shardId); + throw e; } } } @@ -178,9 +178,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.beforeIndexClosed(indexService); - } catch (Throwable t) { - logger.warn("failed to invoke before index closed callback", t); - throw t; + } catch (Exception e) { + logger.warn("failed to invoke before index closed callback", e); + throw e; } } } @@ -190,9 +190,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.beforeIndexDeleted(indexService); - } catch (Throwable t) { - logger.warn("failed to invoke before index deleted callback", t); - throw t; + } catch (Exception e) { + logger.warn("failed to invoke before index deleted callback", e); + throw e; } } } @@ -202,9 +202,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.afterIndexDeleted(index, indexSettings); - } catch (Throwable t) { - logger.warn("failed to invoke after index deleted callback", t); - throw t; + } catch (Exception e) { + logger.warn("failed to invoke after index deleted callback", e); + throw e; } } } @@ -214,9 +214,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.afterIndexClosed(index, indexSettings); - } catch (Throwable t) { - logger.warn("failed to invoke after index closed callback", t); - throw t; + } catch (Exception e) { + logger.warn("failed to invoke after index closed callback", e); + throw e; } } } @@ -227,9 +227,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.beforeIndexShardDeleted(shardId, indexSettings); - } catch (Throwable t) { - logger.warn("[{}] failed to invoke before shard deleted callback", t, shardId.getId()); - throw t; + } catch (Exception e) { + logger.warn("[{}] failed to invoke before shard deleted callback", e, shardId.getId()); + throw e; } } } @@ -240,9 +240,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.afterIndexShardDeleted(shardId, indexSettings); - } catch (Throwable t) { - logger.warn("[{}] failed to invoke after shard deleted callback", t, shardId.getId()); - throw t; + } catch (Exception e) { + logger.warn("[{}] failed to invoke after shard deleted callback", e, shardId.getId()); + throw e; } } } @@ -252,9 +252,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.beforeIndexAddedToCluster(index, indexSettings); - } catch (Throwable t) { - logger.warn("failed to invoke before index added to cluster callback", t); - throw t; + } catch (Exception e) { + logger.warn("failed to invoke before index added to cluster callback", e); + throw e; } } } @@ -264,9 +264,9 @@ final class CompositeIndexEventListener implements IndexEventListener { for (IndexEventListener listener : listeners) { try { listener.onStoreClosed(shardId); - } catch (Throwable t) { - logger.warn("failed to invoke on store closed", t); - throw t; + } catch (Exception e) { + logger.warn("failed to invoke on store closed", e); + throw e; } } } diff --git a/core/src/main/java/org/elasticsearch/index/IndexService.java b/core/src/main/java/org/elasticsearch/index/IndexService.java index 4e8caa7d5e9..0ba37418792 100644 --- a/core/src/main/java/org/elasticsearch/index/IndexService.java +++ b/core/src/main/java/org/elasticsearch/index/IndexService.java @@ -234,8 +234,8 @@ public class IndexService extends AbstractIndexComponent implements IndicesClust for (final int shardId : shardIds) { try { removeShard(shardId, reason); - } catch (Throwable t) { - logger.warn("failed to close shard", t); + } catch (Exception e) { + logger.warn("failed to close shard", e); } } } finally { @@ -290,9 +290,9 @@ public class IndexService extends AbstractIndexComponent implements IndicesClust try { ShardPath.deleteLeftoverShardDirectory(logger, nodeEnv, lock, this.indexSettings); path = ShardPath.loadShardPath(logger, nodeEnv, shardId, this.indexSettings); - } catch (Throwable t) { - t.addSuppressed(ex); - throw t; + } catch (Exception inner) { + ex.addSuppressed(inner); + throw ex; } } @@ -390,7 +390,7 @@ public class IndexService extends AbstractIndexComponent implements IndicesClust // only flush we are we closed (closed index or shutdown) and if we are not deleted final boolean flushEngine = deleted.get() == false && closed.get(); indexShard.close(reason, flushEngine); - } catch (Throwable e) { + } catch (Exception e) { logger.debug("[{}] failed to close index shard", e, shardId); // ignore } @@ -401,7 +401,7 @@ public class IndexService extends AbstractIndexComponent implements IndicesClust } finally { try { store.close(); - } catch (Throwable e) { + } catch (Exception e) { logger.warn("[{}] failed to close store on shard removal (reason: [{}])", e, shardId, reason); } } diff --git a/core/src/main/java/org/elasticsearch/index/IndexWarmer.java b/core/src/main/java/org/elasticsearch/index/IndexWarmer.java index 499031af970..ba48adb71a8 100644 --- a/core/src/main/java/org/elasticsearch/index/IndexWarmer.java +++ b/core/src/main/java/org/elasticsearch/index/IndexWarmer.java @@ -146,8 +146,8 @@ public final class IndexWarmer extends AbstractComponent { indexShard.warmerService().logger().trace("warmed global ordinals for [{}], took [{}]", fieldType.name(), TimeValue.timeValueNanos(System.nanoTime() - start)); } - } catch (Throwable t) { - indexShard.warmerService().logger().warn("failed to warm-up global ordinals for [{}]", t, fieldType.name()); + } catch (Exception e) { + indexShard.warmerService().logger().warn("failed to warm-up global ordinals for [{}]", e, fieldType.name()); } finally { latch.countDown(); } diff --git a/core/src/main/java/org/elasticsearch/index/cache/bitset/BitsetFilterCache.java b/core/src/main/java/org/elasticsearch/index/cache/bitset/BitsetFilterCache.java index 2452e8147c2..5eb2ec8ab70 100644 --- a/core/src/main/java/org/elasticsearch/index/cache/bitset/BitsetFilterCache.java +++ b/core/src/main/java/org/elasticsearch/index/cache/bitset/BitsetFilterCache.java @@ -42,6 +42,8 @@ import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.AbstractIndexComponent; import org.elasticsearch.index.IndexSettings; +import org.elasticsearch.index.IndexWarmer; +import org.elasticsearch.index.IndexWarmer.TerminationHandle; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.MapperService; @@ -49,8 +51,6 @@ import org.elasticsearch.index.mapper.object.ObjectMapper; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.shard.ShardUtils; -import org.elasticsearch.index.IndexWarmer; -import org.elasticsearch.index.IndexWarmer.TerminationHandle; import org.elasticsearch.threadpool.ThreadPool; import java.io.Closeable; @@ -257,8 +257,8 @@ public final class BitsetFilterCache extends AbstractIndexComponent implements L if (indexShard.warmerService().logger().isTraceEnabled()) { indexShard.warmerService().logger().trace("warmed bitset for [{}], took [{}]", filterToWarm, TimeValue.timeValueNanos(System.nanoTime() - start)); } - } catch (Throwable t) { - indexShard.warmerService().logger().warn("failed to load bitset for [{}]", t, filterToWarm); + } catch (Exception e) { + indexShard.warmerService().logger().warn("failed to load bitset for [{}]", e, filterToWarm); } finally { latch.countDown(); } diff --git a/core/src/main/java/org/elasticsearch/index/engine/Engine.java b/core/src/main/java/org/elasticsearch/index/engine/Engine.java index d169e495a3d..f9186185e61 100644 --- a/core/src/main/java/org/elasticsearch/index/engine/Engine.java +++ b/core/src/main/java/org/elasticsearch/index/engine/Engine.java @@ -102,7 +102,7 @@ public abstract class Engine implements Closeable { protected final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); protected final ReleasableLock readLock = new ReleasableLock(rwl.readLock()); protected final ReleasableLock writeLock = new ReleasableLock(rwl.writeLock()); - protected volatile Throwable failedEngine = null; + protected volatile Exception failedEngine = null; /* * on lastWriteNanos we use System.nanoTime() to initialize this since: * - we use the value for figuring out if the shard / engine is active so if we startup and no write has happened yet we still consider it active @@ -302,7 +302,7 @@ public abstract class Engine implements Closeable { final Versions.DocIdAndVersion docIdAndVersion; try { docIdAndVersion = Versions.loadDocIdAndVersion(searcher.reader(), get.uid()); - } catch (Throwable e) { + } catch (Exception e) { Releasables.closeWhileHandlingException(searcher); //TODO: A better exception goes here throw new EngineException(shardId, "Couldn't resolve version", e); @@ -362,7 +362,7 @@ public abstract class Engine implements Closeable { } } catch (EngineClosedException ex) { throw ex; - } catch (Throwable ex) { + } catch (Exception ex) { ensureOpen(); // throw EngineCloseException here if we are already closed logger.error("failed to acquire searcher, source {}", ex, source); throw new EngineException(shardId, "failed to acquire searcher, source " + source, ex); @@ -660,7 +660,7 @@ public abstract class Engine implements Closeable { * fail engine due to some error. the engine will also be closed. * The underlying store is marked corrupted iff failure is caused by index corruption */ - public void failEngine(String reason, @Nullable Throwable failure) { + public void failEngine(String reason, @Nullable Exception failure) { if (failEngineLock.tryLock()) { store.incRef(); try { @@ -688,9 +688,10 @@ public abstract class Engine implements Closeable { } eventListener.onFailedEngine(reason, failure); } - } catch (Throwable t) { + } catch (Exception inner) { + if (failure != null) inner.addSuppressed(failure); // don't bubble up these exceptions up - logger.warn("failEngine threw exception", t); + logger.warn("failEngine threw exception", inner); } finally { store.decRef(); } @@ -700,12 +701,12 @@ public abstract class Engine implements Closeable { } /** Check whether the engine should be failed */ - protected boolean maybeFailEngine(String source, Throwable t) { - if (Lucene.isCorruptionException(t)) { - failEngine("corrupt file (source: [" + source + "])", t); + protected boolean maybeFailEngine(String source, Exception e) { + if (Lucene.isCorruptionException(e)) { + failEngine("corrupt file (source: [" + source + "])", e); return true; - } else if (ExceptionsHelper.isOOM(t)) { - failEngine("out of memory (source: [" + source + "])", t); + } else if (ExceptionsHelper.isOOM(e)) { + failEngine("out of memory (source: [" + source + "])", e); return true; } return false; @@ -716,7 +717,7 @@ public abstract class Engine implements Closeable { /** * Called when a fatal exception occurred */ - default void onFailedEngine(String reason, @Nullable Throwable t) {} + default void onFailedEngine(String reason, @Nullable Exception e) {} } public static class Searcher implements Releasable { diff --git a/core/src/main/java/org/elasticsearch/index/engine/InternalEngine.java b/core/src/main/java/org/elasticsearch/index/engine/InternalEngine.java index 6052de7f586..779d7629686 100644 --- a/core/src/main/java/org/elasticsearch/index/engine/InternalEngine.java +++ b/core/src/main/java/org/elasticsearch/index/engine/InternalEngine.java @@ -185,10 +185,14 @@ public class InternalEngine extends Engine { } try { recoverFromTranslog(engineConfig.getTranslogRecoveryPerformer()); - } catch (Throwable t) { - allowCommits.set(false); // just play safe and never allow commits on this - failEngine("failed to recover from translog", t); - throw t; + } catch (Exception e) { + try { + allowCommits.set(false); // just play safe and never allow commits on this + failEngine("failed to recover from translog", e); + } catch (Exception inner) { + e.addSuppressed(inner); + } + throw e; } } finally { flushLock.unlock(); @@ -202,7 +206,7 @@ public class InternalEngine extends Engine { try { Translog.Snapshot snapshot = translog.newSnapshot(); opsRecovered = handler.recoveryFromSnapshot(this, snapshot); - } catch (Throwable e) { + } catch (Exception e) { throw new EngineException(shardId, "failed to recover from translog", e); } // flush if we recovered something or if we have references to older translogs @@ -297,8 +301,8 @@ public class InternalEngine extends Engine { maybeFailEngine("start", e); try { indexWriter.rollback(); - } catch (IOException e1) { // iw is closed below - e.addSuppressed(e1); + } catch (IOException inner) { // iw is closed below + e.addSuppressed(inner); } throw new EngineCreationFailureException(shardId, "failed to open reader on writer", e); } @@ -402,9 +406,13 @@ public class InternalEngine extends Engine { created = innerIndex(index); } } - } catch (OutOfMemoryError | IllegalStateException | IOException t) { - maybeFailEngine("index", t); - throw new IndexFailedEngineException(shardId, index.type(), index.id(), t); + } catch (IllegalStateException | IOException e) { + try { + maybeFailEngine("index", e); + } catch (Exception inner) { + e.addSuppressed(inner); + } + throw new IndexFailedEngineException(shardId, index.type(), index.id(), e); } return created; } @@ -483,9 +491,13 @@ public class InternalEngine extends Engine { ensureOpen(); // NOTE: we don't throttle this when merges fall behind because delete-by-id does not create new segments: innerDelete(delete); - } catch (OutOfMemoryError | IllegalStateException | IOException t) { - maybeFailEngine("delete", t); - throw new DeleteFailedEngineException(shardId, delete, t); + } catch (IllegalStateException | IOException e) { + try { + maybeFailEngine("delete", e); + } catch (Exception inner) { + e.addSuppressed(inner); + } + throw new DeleteFailedEngineException(shardId, delete, e); } maybePruneDeletedTombstones(); @@ -554,9 +566,13 @@ public class InternalEngine extends Engine { maybeFailEngine("refresh", e); } catch (EngineClosedException e) { throw e; - } catch (Throwable t) { - failEngine("refresh failed", t); - throw new RefreshFailedEngineException(shardId, t); + } catch (Exception e) { + try { + failEngine("refresh failed", e); + } catch (Exception inner) { + e.addSuppressed(inner); + } + throw new RefreshFailedEngineException(shardId, e); } // TODO: maybe we should just put a scheduled job in threadPool? @@ -598,9 +614,13 @@ public class InternalEngine extends Engine { maybeFailEngine("writeIndexingBuffer", e); } catch (EngineClosedException e) { throw e; - } catch (Throwable t) { - failEngine("writeIndexingBuffer failed", t); - throw new RefreshFailedEngineException(shardId, t); + } catch (Exception e) { + try { + failEngine("writeIndexingBuffer failed", e); + } catch (Exception inner) { + e.addSuppressed(inner); + } + throw new RefreshFailedEngineException(shardId, e); } } @@ -703,7 +723,7 @@ public class InternalEngine extends Engine { refresh("version_table_flush"); // after refresh documents can be retrieved from the index so we can now commit the translog translog.commit(); - } catch (Throwable e) { + } catch (Exception e) { throw new FlushFailedEngineException(shardId, e); } } @@ -717,9 +737,13 @@ public class InternalEngine extends Engine { try { // reread the last committed segment infos lastCommittedSegmentInfos = store.readLastCommittedSegmentsInfo(); - } catch (Throwable e) { + } catch (Exception e) { if (isClosed.get() == false) { - logger.warn("failed to read latest segment infos on flush", e); + try { + logger.warn("failed to read latest segment infos on flush", e); + } catch (Exception inner) { + e.addSuppressed(inner); + } if (Lucene.isCorruptionException(e)) { throw new FlushFailedEngineException(shardId, e); } @@ -811,9 +835,13 @@ public class InternalEngine extends Engine { } finally { store.decRef(); } - } catch (Throwable t) { - maybeFailEngine("force merge", t); - throw t; + } catch (Exception e) { + try { + maybeFailEngine("force merge", e); + } catch (Exception inner) { + e.addSuppressed(inner); + } + throw e; } finally { try { mp.setUpgradeInProgress(false, false); // reset it just to make sure we reset it in a case of an error @@ -842,29 +870,32 @@ public class InternalEngine extends Engine { } @Override - protected boolean maybeFailEngine(String source, Throwable t) { - boolean shouldFail = super.maybeFailEngine(source, t); + protected boolean maybeFailEngine(String source, Exception e) { + boolean shouldFail = super.maybeFailEngine(source, e); if (shouldFail) { return true; } // Check for AlreadyClosedException - if (t instanceof AlreadyClosedException) { + if (e instanceof AlreadyClosedException) { // if we are already closed due to some tragic exception // we need to fail the engine. it might have already been failed before // but we are double-checking it's failed and closed if (indexWriter.isOpen() == false && indexWriter.getTragicException() != null) { - failEngine("already closed by tragic event on the index writer", indexWriter.getTragicException()); + final Exception tragedy = indexWriter.getTragicException() instanceof Exception ? + (Exception) indexWriter.getTragicException() : + new Exception(indexWriter.getTragicException()); + failEngine("already closed by tragic event on the index writer", tragedy); } else if (translog.isOpen() == false && translog.getTragicException() != null) { failEngine("already closed by tragic event on the translog", translog.getTragicException()); } return true; - } else if (t != null && - ((indexWriter.isOpen() == false && indexWriter.getTragicException() == t) - || (translog.isOpen() == false && translog.getTragicException() == t))) { + } else if (e != null && + ((indexWriter.isOpen() == false && indexWriter.getTragicException() == e) + || (translog.isOpen() == false && translog.getTragicException() == e))) { // this spot on - we are handling the tragic event exception here so we have to fail the engine // right away - failEngine(source, t); + failEngine(source, e); return true; } return false; @@ -920,13 +951,13 @@ public class InternalEngine extends Engine { this.versionMap.clear(); try { IOUtils.close(searcherManager); - } catch (Throwable t) { - logger.warn("Failed to close SearcherManager", t); + } catch (Exception e) { + logger.warn("Failed to close SearcherManager", e); } try { IOUtils.close(translog); - } catch (Throwable t) { - logger.warn("Failed to close translog", t); + } catch (Exception e) { + logger.warn("Failed to close translog", e); } // no need to commit in this case!, we snapshot before we close the shard, so translog and all sync'ed logger.trace("rollback indexWriter"); @@ -936,7 +967,7 @@ public class InternalEngine extends Engine { // ignore } logger.trace("rollback indexWriter done"); - } catch (Throwable e) { + } catch (Exception e) { logger.warn("failed to rollback writer on close", e); } finally { store.decRef(); @@ -974,7 +1005,7 @@ public class InternalEngine extends Engine { boolean verbose = false; try { verbose = Boolean.parseBoolean(System.getProperty("tests.verbose")); - } catch (Throwable ignore) { + } catch (Exception ignore) { } iwc.setInfoStream(verbose ? InfoStream.getDefault() : new LoggerInfoStream(logger)); iwc.setMergeScheduler(mergeScheduler); @@ -1020,7 +1051,7 @@ public class InternalEngine extends Engine { try { assert searcher.getIndexReader() instanceof ElasticsearchDirectoryReader : "this class needs an ElasticsearchDirectoryReader but got: " + searcher.getIndexReader().getClass(); warmer.warm(new Searcher("top_reader_warming", searcher)); - } catch (Throwable e) { + } catch (Exception e) { if (isEngineClosed.get() == false) { logger.warn("failed to prepare/warm", e); } @@ -1093,7 +1124,7 @@ public class InternalEngine extends Engine { // we deadlock on engine#close for instance. engineConfig.getThreadPool().executor(ThreadPool.Names.FLUSH).execute(new AbstractRunnable() { @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { if (isClosed.get() == false) { logger.warn("failed to flush after merge has finished"); } @@ -1121,8 +1152,8 @@ public class InternalEngine extends Engine { logger.error("failed to merge", exc); engineConfig.getThreadPool().generic().execute(new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - logger.debug("merge failure action rejected", t); + public void onFailure(Exception e) { + logger.debug("merge failure action rejected", e); } @Override @@ -1147,8 +1178,12 @@ public class InternalEngine extends Engine { } indexWriter.setCommitData(commitData); writer.commit(); - } catch (Throwable ex) { - failEngine("lucene commit failed", ex); + } catch (Exception ex) { + try { + failEngine("lucene commit failed", ex); + } catch (Exception inner) { + ex.addSuppressed(inner); + } throw ex; } } diff --git a/core/src/main/java/org/elasticsearch/index/engine/ShadowEngine.java b/core/src/main/java/org/elasticsearch/index/engine/ShadowEngine.java index c8ee7d5b8b0..83f9d466f0e 100644 --- a/core/src/main/java/org/elasticsearch/index/engine/ShadowEngine.java +++ b/core/src/main/java/org/elasticsearch/index/engine/ShadowEngine.java @@ -89,7 +89,7 @@ public class ShadowEngine extends Engine { nonexistentRetryTime + "ms, " + "directory is not an index"); } - } catch (Throwable e) { + } catch (Exception e) { logger.warn("failed to create new reader", e); throw e; } finally { @@ -140,7 +140,7 @@ public class ShadowEngine extends Engine { try (ReleasableLock lock = readLock.acquire()) { // reread the last committed segment infos lastCommittedSegmentInfos = readLastCommittedSegmentInfos(searcherManager, store); - } catch (Throwable e) { + } catch (Exception e) { if (isClosed.get() == false) { logger.warn("failed to read latest segment infos on flush", e); if (Lucene.isCorruptionException(e)) { @@ -194,9 +194,13 @@ public class ShadowEngine extends Engine { ensureOpen(); } catch (EngineClosedException e) { throw e; - } catch (Throwable t) { - failEngine("refresh failed", t); - throw new RefreshFailedEngineException(shardId, t); + } catch (Exception e) { + try { + failEngine("refresh failed", e); + } catch (Exception inner) { + e.addSuppressed(inner); + } + throw new RefreshFailedEngineException(shardId, e); } } @@ -216,8 +220,8 @@ public class ShadowEngine extends Engine { try { logger.debug("shadow replica close searcher manager refCount: {}", store.refCount()); IOUtils.close(searcherManager); - } catch (Throwable t) { - logger.warn("shadow replica failed to close searcher manager", t); + } catch (Exception e) { + logger.warn("shadow replica failed to close searcher manager", e); } finally { store.decRef(); } diff --git a/core/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataService.java b/core/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataService.java index 30e1086e187..2577d967e62 100644 --- a/core/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataService.java +++ b/core/src/main/java/org/elasticsearch/index/fielddata/IndexFieldDataService.java @@ -21,26 +21,12 @@ package org.elasticsearch.index.fielddata; import org.apache.lucene.util.Accountable; import org.elasticsearch.ExceptionsHelper; -import org.elasticsearch.common.collect.MapBuilder; -import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.index.AbstractIndexComponent; import org.elasticsearch.index.IndexSettings; -import org.elasticsearch.index.fielddata.plain.AbstractGeoPointDVIndexFieldData; -import org.elasticsearch.index.fielddata.plain.BytesBinaryDVIndexFieldData; -import org.elasticsearch.index.fielddata.plain.DocValuesIndexFieldData; -import org.elasticsearch.index.fielddata.plain.GeoPointArrayIndexFieldData; -import org.elasticsearch.index.fielddata.plain.IndexIndexFieldData; -import org.elasticsearch.index.fielddata.plain.PagedBytesIndexFieldData; -import org.elasticsearch.index.fielddata.plain.ParentChildIndexFieldData; import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.MapperService; -import org.elasticsearch.index.mapper.core.BooleanFieldMapper; -import org.elasticsearch.index.mapper.core.KeywordFieldMapper; -import org.elasticsearch.index.mapper.core.TextFieldMapper; -import org.elasticsearch.index.mapper.internal.IndexFieldMapper; -import org.elasticsearch.index.mapper.internal.ParentFieldMapper; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.indices.breaker.CircuitBreakerService; import org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache; @@ -53,10 +39,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import static java.util.Collections.unmodifiableMap; - -/** - */ public class IndexFieldDataService extends AbstractIndexComponent implements Closeable { public static final String FIELDDATA_CACHE_VALUE_NODE = "node"; public static final String FIELDDATA_CACHE_KEY = "index.fielddata.cache"; @@ -97,13 +79,13 @@ public class IndexFieldDataService extends AbstractIndexComponent implements Clo } public synchronized void clear() { - List exceptions = new ArrayList<>(0); + List exceptions = new ArrayList<>(0); final Collection fieldDataCacheValues = fieldDataCaches.values(); for (IndexFieldDataCache cache : fieldDataCacheValues) { try { cache.clear(); - } catch (Throwable t) { - exceptions.add(t); + } catch (Exception e) { + exceptions.add(e); } } fieldDataCacheValues.clear(); @@ -111,13 +93,13 @@ public class IndexFieldDataService extends AbstractIndexComponent implements Clo } public synchronized void clearField(final String fieldName) { - List exceptions = new ArrayList<>(0); + List exceptions = new ArrayList<>(0); final IndexFieldDataCache cache = fieldDataCaches.remove(fieldName); if (cache != null) { try { cache.clear(); - } catch (Throwable t) { - exceptions.add(t); + } catch (Exception e) { + exceptions.add(e); } } ExceptionsHelper.maybeThrowRuntimeAndSuppress(exceptions); diff --git a/core/src/main/java/org/elasticsearch/index/fielddata/plain/AbstractIndexFieldData.java b/core/src/main/java/org/elasticsearch/index/fielddata/plain/AbstractIndexFieldData.java index 604e866de02..6c1f3e6fc9e 100644 --- a/core/src/main/java/org/elasticsearch/index/fielddata/plain/AbstractIndexFieldData.java +++ b/core/src/main/java/org/elasticsearch/index/fielddata/plain/AbstractIndexFieldData.java @@ -33,8 +33,6 @@ import org.elasticsearch.index.fielddata.RamAccountingTermsEnum; import java.io.IOException; -/** - */ public abstract class AbstractIndexFieldData extends AbstractIndexComponent implements IndexFieldData { private final String fieldName; @@ -69,7 +67,7 @@ public abstract class AbstractIndexFieldData extends try { FD fd = cache.load(context, this); return fd; - } catch (Throwable e) { + } catch (Exception e) { if (e instanceof ElasticsearchException) { throw (ElasticsearchException) e; } else { diff --git a/core/src/main/java/org/elasticsearch/index/fielddata/plain/AbstractIndexOrdinalsFieldData.java b/core/src/main/java/org/elasticsearch/index/fielddata/plain/AbstractIndexOrdinalsFieldData.java index 9c71f5bad9b..0223c1a0b63 100644 --- a/core/src/main/java/org/elasticsearch/index/fielddata/plain/AbstractIndexOrdinalsFieldData.java +++ b/core/src/main/java/org/elasticsearch/index/fielddata/plain/AbstractIndexOrdinalsFieldData.java @@ -86,7 +86,7 @@ public abstract class AbstractIndexOrdinalsFieldData extends AbstractIndexFieldD } try { return cache.load(indexReader, this); - } catch (Throwable e) { + } catch (Exception e) { if (e instanceof ElasticsearchException) { throw (ElasticsearchException) e; } else { diff --git a/core/src/main/java/org/elasticsearch/index/fielddata/plain/ParentChildIndexFieldData.java b/core/src/main/java/org/elasticsearch/index/fielddata/plain/ParentChildIndexFieldData.java index caeb92a7d44..1fc82e31c60 100644 --- a/core/src/main/java/org/elasticsearch/index/fielddata/plain/ParentChildIndexFieldData.java +++ b/core/src/main/java/org/elasticsearch/index/fielddata/plain/ParentChildIndexFieldData.java @@ -158,7 +158,7 @@ public class ParentChildIndexFieldData extends AbstractIndexFieldDatae is caused by index corruption */ - public void failShard(String reason, @Nullable Throwable e) { + public void failShard(String reason, @Nullable Exception e) { // fail the engine. This will cause this shard to also be removed from the node's index service. getEngine().failEngine(reason, e); } @@ -1074,7 +1074,7 @@ public class IndexShard extends AbstractIndexShardComponent implements IndicesCl verifyNotClosed(null); } - private void verifyNotClosed(Throwable suppressed) throws IllegalIndexShardStateException { + private void verifyNotClosed(Exception suppressed) throws IllegalIndexShardStateException { IndexShardState state = this.state; // one time volatile read if (state == IndexShardState.CLOSED) { final IllegalIndexShardStateException exc = new IndexShardClosedException(shardId, "operation only allowed when not closed"); @@ -1388,7 +1388,7 @@ public class IndexShard extends AbstractIndexShardComponent implements IndicesCl try { markAsRecovering("from " + recoveryState.getSourceNode(), recoveryState); recoveryTargetService.startRecovery(this, recoveryState.getType(), recoveryState.getSourceNode(), recoveryListener); - } catch (Throwable e) { + } catch (Exception e) { failShard("corrupted preexisting index", e); recoveryListener.onRecoveryFailure(recoveryState, new RecoveryFailedException(recoveryState, null, e), true); } @@ -1400,8 +1400,8 @@ public class IndexShard extends AbstractIndexShardComponent implements IndicesCl if (recoverFromStore()) { recoveryListener.onRecoveryDone(recoveryState); } - } catch (Throwable t) { - recoveryListener.onRecoveryFailure(recoveryState, new RecoveryFailedException(recoveryState, null, t), true); + } catch (Exception e) { + recoveryListener.onRecoveryFailure(recoveryState, new RecoveryFailedException(recoveryState, null, e), true); } }); break; @@ -1428,21 +1428,21 @@ public class IndexShard extends AbstractIndexShardComponent implements IndicesCl .filter((s) -> shards.contains(s.shardId())).collect(Collectors.toList()))) { recoveryListener.onRecoveryDone(recoveryState); } - } catch (Throwable t) { + } catch (Exception e) { recoveryListener.onRecoveryFailure(recoveryState, - new RecoveryFailedException(recoveryState, null, t), true); + new RecoveryFailedException(recoveryState, null, e), true); } }); } else { - final Throwable t; + final Exception e; if (numShards == -1) { - t = new IndexNotFoundException(mergeSourceIndex); + e = new IndexNotFoundException(mergeSourceIndex); } else { - t = new IllegalStateException("not all shards from index " + mergeSourceIndex + e = new IllegalStateException("not all shards from index " + mergeSourceIndex + " are started yet, expected " + numShards + " found " + startedShards.size() + " can't recover shard " + shardId()); } - recoveryListener.onRecoveryFailure(recoveryState, new RecoveryFailedException(recoveryState, null, t), true); + recoveryListener.onRecoveryFailure(recoveryState, new RecoveryFailedException(recoveryState, null, e), true); } break; case SNAPSHOT: @@ -1454,7 +1454,7 @@ public class IndexShard extends AbstractIndexShardComponent implements IndicesCl if (restoreFromRepository(indexShardRepository)) { recoveryListener.onRecoveryDone(recoveryState); } - } catch (Throwable first) { + } catch (Exception first) { recoveryListener.onRecoveryFailure(recoveryState, new RecoveryFailedException(recoveryState, null, first), true); } }); @@ -1469,13 +1469,14 @@ public class IndexShard extends AbstractIndexShardComponent implements IndicesCl // called by the current engine @Override - public void onFailedEngine(String reason, @Nullable Throwable failure) { + public void onFailedEngine(String reason, @Nullable Exception failure) { final ShardFailure shardFailure = new ShardFailure(shardRouting, reason, failure); for (Callback listener : delegates) { try { listener.handle(shardFailure); - } catch (Exception e) { - logger.warn("exception while notifying engine failure", e); + } catch (Exception inner) { + inner.addSuppressed(failure); + logger.warn("exception while notifying engine failure", inner); } } } @@ -1620,9 +1621,9 @@ public class IndexShard extends AbstractIndexShardComponent implements IndicesCl logger.debug("submitting async flush request"); final AbstractRunnable abstractRunnable = new AbstractRunnable() { @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { if (state != IndexShardState.CLOSED) { - logger.warn("failed to flush index", t); + logger.warn("failed to flush index", e); } } @@ -1665,9 +1666,9 @@ public class IndexShard extends AbstractIndexShardComponent implements IndicesCl public final ShardRouting routing; public final String reason; @Nullable - public final Throwable cause; + public final Exception cause; - public ShardFailure(ShardRouting routing, String reason, @Nullable Throwable cause) { + public ShardFailure(ShardRouting routing, String reason, @Nullable Exception cause) { this.routing = routing; this.reason = reason; this.cause = cause; diff --git a/core/src/main/java/org/elasticsearch/index/shard/IndexingOperationListener.java b/core/src/main/java/org/elasticsearch/index/shard/IndexingOperationListener.java index aedc8554624..13ff87d4187 100644 --- a/core/src/main/java/org/elasticsearch/index/shard/IndexingOperationListener.java +++ b/core/src/main/java/org/elasticsearch/index/shard/IndexingOperationListener.java @@ -43,7 +43,7 @@ public interface IndexingOperationListener { /** * Called after the indexing operation occurred with exception. */ - default void postIndex(Engine.Index index, Throwable ex) {} + default void postIndex(Engine.Index index, Exception ex) {} /** * Called before the delete occurs. @@ -61,7 +61,7 @@ public interface IndexingOperationListener { /** * Called after the delete operation occurred with exception. */ - default void postDelete(Engine.Delete delete, Throwable ex) {} + default void postDelete(Engine.Delete delete, Exception ex) {} /** * A Composite listener that multiplexes calls to each of the listeners methods. @@ -81,8 +81,8 @@ public interface IndexingOperationListener { for (IndexingOperationListener listener : listeners) { try { listener.preIndex(operation); - } catch (Throwable t) { - logger.warn("preIndex listener [{}] failed", t, listener); + } catch (Exception e) { + logger.warn("preIndex listener [{}] failed", e, listener); } } return operation; @@ -94,20 +94,21 @@ public interface IndexingOperationListener { for (IndexingOperationListener listener : listeners) { try { listener.postIndex(index, created); - } catch (Throwable t) { - logger.warn("postIndex listener [{}] failed", t, listener); + } catch (Exception e) { + logger.warn("postIndex listener [{}] failed", e, listener); } } } @Override - public void postIndex(Engine.Index index, Throwable ex) { + public void postIndex(Engine.Index index, Exception ex) { assert index != null && ex != null; for (IndexingOperationListener listener : listeners) { try { listener.postIndex(index, ex); - } catch (Throwable t) { - logger.warn("postIndex listener [{}] failed", t, listener); + } catch (Exception inner) { + inner.addSuppressed(ex); + logger.warn("postIndex listener [{}] failed", inner, listener); } } } @@ -118,8 +119,8 @@ public interface IndexingOperationListener { for (IndexingOperationListener listener : listeners) { try { listener.preDelete(delete); - } catch (Throwable t) { - logger.warn("preDelete listener [{}] failed", t, listener); + } catch (Exception e) { + logger.warn("preDelete listener [{}] failed", e, listener); } } return delete; @@ -131,20 +132,21 @@ public interface IndexingOperationListener { for (IndexingOperationListener listener : listeners) { try { listener.postDelete(delete); - } catch (Throwable t) { - logger.warn("postDelete listener [{}] failed", t, listener); + } catch (Exception e) { + logger.warn("postDelete listener [{}] failed", e, listener); } } } @Override - public void postDelete(Engine.Delete delete, Throwable ex) { + public void postDelete(Engine.Delete delete, Exception ex) { assert delete != null && ex != null; for (IndexingOperationListener listener : listeners) { try { listener.postDelete(delete, ex); - } catch (Throwable t) { - logger.warn("postDelete listener [{}] failed", t, listener); + } catch (Exception inner) { + inner.addSuppressed(ex); + logger.warn("postDelete listener [{}] failed", inner, listener); } } } diff --git a/core/src/main/java/org/elasticsearch/index/shard/InternalIndexingStats.java b/core/src/main/java/org/elasticsearch/index/shard/InternalIndexingStats.java index b85ca7e6a9d..f62b8f7fe3c 100644 --- a/core/src/main/java/org/elasticsearch/index/shard/InternalIndexingStats.java +++ b/core/src/main/java/org/elasticsearch/index/shard/InternalIndexingStats.java @@ -86,7 +86,7 @@ final class InternalIndexingStats implements IndexingOperationListener { } @Override - public void postIndex(Engine.Index index, Throwable ex) { + public void postIndex(Engine.Index index, Exception ex) { if (!index.origin().isRecovery()) { totalStats.indexCurrent.dec(); typeStats(index.type()).indexCurrent.dec(); @@ -118,7 +118,7 @@ final class InternalIndexingStats implements IndexingOperationListener { } @Override - public void postDelete(Engine.Delete delete, Throwable ex) { + public void postDelete(Engine.Delete delete, Exception ex) { if (!delete.origin().isRecovery()) { totalStats.deleteCurrent.dec(); typeStats(delete.type()).deleteCurrent.dec(); diff --git a/core/src/main/java/org/elasticsearch/index/shard/RefreshListeners.java b/core/src/main/java/org/elasticsearch/index/shard/RefreshListeners.java index b594b31abb8..76352e79bb4 100644 --- a/core/src/main/java/org/elasticsearch/index/shard/RefreshListeners.java +++ b/core/src/main/java/org/elasticsearch/index/shard/RefreshListeners.java @@ -200,8 +200,8 @@ public final class RefreshListeners implements ReferenceManager.RefreshListener for (Consumer listener : finalListenersToFire) { try { listener.accept(false); - } catch (Throwable t) { - logger.warn("Error firing refresh listener", t); + } catch (Exception e) { + logger.warn("Error firing refresh listener", e); } } }); diff --git a/core/src/main/java/org/elasticsearch/index/shard/SearchOperationListener.java b/core/src/main/java/org/elasticsearch/index/shard/SearchOperationListener.java index 012617edcd0..5a4ac1297f7 100644 --- a/core/src/main/java/org/elasticsearch/index/shard/SearchOperationListener.java +++ b/core/src/main/java/org/elasticsearch/index/shard/SearchOperationListener.java @@ -119,8 +119,8 @@ public interface SearchOperationListener { for (SearchOperationListener listener : listeners) { try { listener.onPreQueryPhase(searchContext); - } catch (Throwable t) { - logger.warn("onPreQueryPhase listener [{}] failed", t, listener); + } catch (Exception e) { + logger.warn("onPreQueryPhase listener [{}] failed", e, listener); } } } @@ -130,8 +130,8 @@ public interface SearchOperationListener { for (SearchOperationListener listener : listeners) { try { listener.onFailedQueryPhase(searchContext); - } catch (Throwable t) { - logger.warn("onFailedQueryPhase listener [{}] failed", t, listener); + } catch (Exception e) { + logger.warn("onFailedQueryPhase listener [{}] failed", e, listener); } } } @@ -141,8 +141,8 @@ public interface SearchOperationListener { for (SearchOperationListener listener : listeners) { try { listener.onQueryPhase(searchContext, tookInNanos); - } catch (Throwable t) { - logger.warn("onQueryPhase listener [{}] failed", t, listener); + } catch (Exception e) { + logger.warn("onQueryPhase listener [{}] failed", e, listener); } } } @@ -152,8 +152,8 @@ public interface SearchOperationListener { for (SearchOperationListener listener : listeners) { try { listener.onPreFetchPhase(searchContext); - } catch (Throwable t) { - logger.warn("onPreFetchPhase listener [{}] failed", t, listener); + } catch (Exception e) { + logger.warn("onPreFetchPhase listener [{}] failed", e, listener); } } } @@ -163,8 +163,8 @@ public interface SearchOperationListener { for (SearchOperationListener listener : listeners) { try { listener.onFailedFetchPhase(searchContext); - } catch (Throwable t) { - logger.warn("onFailedFetchPhase listener [{}] failed", t, listener); + } catch (Exception e) { + logger.warn("onFailedFetchPhase listener [{}] failed", e, listener); } } } @@ -174,8 +174,8 @@ public interface SearchOperationListener { for (SearchOperationListener listener : listeners) { try { listener.onFetchPhase(searchContext, tookInNanos); - } catch (Throwable t) { - logger.warn("onFetchPhase listener [{}] failed", t, listener); + } catch (Exception e) { + logger.warn("onFetchPhase listener [{}] failed", e, listener); } } } @@ -185,8 +185,8 @@ public interface SearchOperationListener { for (SearchOperationListener listener : listeners) { try { listener.onNewContext(context); - } catch (Throwable t) { - logger.warn("onNewContext listener [{}] failed", t, listener); + } catch (Exception e) { + logger.warn("onNewContext listener [{}] failed", e, listener); } } } @@ -196,8 +196,8 @@ public interface SearchOperationListener { for (SearchOperationListener listener : listeners) { try { listener.onFreeContext(context); - } catch (Throwable t) { - logger.warn("onFreeContext listener [{}] failed", t, listener); + } catch (Exception e) { + logger.warn("onFreeContext listener [{}] failed", e, listener); } } } @@ -207,8 +207,8 @@ public interface SearchOperationListener { for (SearchOperationListener listener : listeners) { try { listener.onNewScrollContext(context); - } catch (Throwable t) { - logger.warn("onNewScrollContext listener [{}] failed", t, listener); + } catch (Exception e) { + logger.warn("onNewScrollContext listener [{}] failed", e, listener); } } } @@ -218,8 +218,8 @@ public interface SearchOperationListener { for (SearchOperationListener listener : listeners) { try { listener.onFreeScrollContext(context); - } catch (Throwable t) { - logger.warn("onFreeScrollContext listener [{}] failed", t, listener); + } catch (Exception e) { + logger.warn("onFreeScrollContext listener [{}] failed", e, listener); } } } diff --git a/core/src/main/java/org/elasticsearch/index/shard/StoreRecovery.java b/core/src/main/java/org/elasticsearch/index/shard/StoreRecovery.java index dbfcad6048a..4a9284d8155 100644 --- a/core/src/main/java/org/elasticsearch/index/shard/StoreRecovery.java +++ b/core/src/main/java/org/elasticsearch/index/shard/StoreRecovery.java @@ -319,12 +319,13 @@ final class StoreRecovery { store.failIfCorrupted(); try { si = store.readLastCommittedSegmentsInfo(); - } catch (Throwable e) { + } catch (Exception e) { String files = "_unknown_"; try { files = Arrays.toString(store.directory().listAll()); - } catch (Throwable e1) { - files += " (failure=" + ExceptionsHelper.detailedMessage(e1) + ")"; + } catch (Exception inner) { + inner.addSuppressed(e); + files += " (failure=" + ExceptionsHelper.detailedMessage(inner) + ")"; } if (indexShouldExists) { throw new IndexShardRecoveryException(shardId, "shard allocated for local recovery (post api), should exist, but doesn't, current files: " + files, e); @@ -340,7 +341,7 @@ final class StoreRecovery { Lucene.cleanLuceneIndex(store.directory()); } } - } catch (Throwable e) { + } catch (Exception e) { throw new IndexShardRecoveryException(shardId, "failed to fetch index version after copying it over", e); } recoveryState.getIndex().updateVersion(version); @@ -400,8 +401,8 @@ final class StoreRecovery { indexShard.skipTranslogRecovery(); indexShard.finalizeRecovery(); indexShard.postRecovery("restore done"); - } catch (Throwable t) { - throw new IndexShardRestoreFailedException(shardId, "restore failed", t); + } catch (Exception e) { + throw new IndexShardRestoreFailedException(shardId, "restore failed", e); } } diff --git a/core/src/main/java/org/elasticsearch/index/shard/TranslogRecoveryPerformer.java b/core/src/main/java/org/elasticsearch/index/shard/TranslogRecoveryPerformer.java index 54cfa80926c..78628a02c49 100644 --- a/core/src/main/java/org/elasticsearch/index/shard/TranslogRecoveryPerformer.java +++ b/core/src/main/java/org/elasticsearch/index/shard/TranslogRecoveryPerformer.java @@ -72,8 +72,8 @@ public class TranslogRecoveryPerformer { numOps++; } engine.getTranslog().sync(); - } catch (Throwable t) { - throw new BatchOperationException(shardId, "failed to apply batch translog operation", numOps, t); + } catch (Exception e) { + throw new BatchOperationException(shardId, "failed to apply batch translog operation", numOps, e); } return numOps; } diff --git a/core/src/main/java/org/elasticsearch/index/snapshots/blobstore/BlobStoreIndexShardRepository.java b/core/src/main/java/org/elasticsearch/index/snapshots/blobstore/BlobStoreIndexShardRepository.java index 96230459934..526aab7581b 100644 --- a/core/src/main/java/org/elasticsearch/index/snapshots/blobstore/BlobStoreIndexShardRepository.java +++ b/core/src/main/java/org/elasticsearch/index/snapshots/blobstore/BlobStoreIndexShardRepository.java @@ -181,7 +181,7 @@ public class BlobStoreIndexShardRepository extends AbstractComponent implements snapshotContext.snapshot(snapshotIndexCommit); snapshotStatus.time(System.currentTimeMillis() - snapshotStatus.startTime()); snapshotStatus.updateStage(IndexShardSnapshotStatus.Stage.DONE); - } catch (Throwable e) { + } catch (Exception e) { snapshotStatus.time(System.currentTimeMillis() - snapshotStatus.startTime()); snapshotStatus.updateStage(IndexShardSnapshotStatus.Stage.FAILURE); snapshotStatus.failure(ExceptionsHelper.detailedMessage(e)); @@ -201,7 +201,7 @@ public class BlobStoreIndexShardRepository extends AbstractComponent implements final RestoreContext snapshotContext = new RestoreContext(snapshotId, version, shardId, snapshotShardId, recoveryState); try { snapshotContext.restore(); - } catch (Throwable e) { + } catch (Exception e) { throw new IndexShardRestoreFailedException(shardId, "failed to restore snapshot [" + snapshotId + "]", e); } } @@ -559,7 +559,7 @@ public class BlobStoreIndexShardRepository extends AbstractComponent implements // don't have this hash we try to read that hash from the blob store // in a bwc compatible way. maybeRecalculateMetadataHash(blobContainer, fileInfo, metadata); - } catch (Throwable e) { + } catch (Exception e) { logger.warn("{} Can't calculate hash from blob for file [{}] [{}]", e, shardId, fileInfo.physicalName(), fileInfo.metadata()); } if (fileInfo.isSame(md) && snapshotFileExistsInBlobs(fileInfo, blobs)) { @@ -651,19 +651,20 @@ public class BlobStoreIndexShardRepository extends AbstractComponent implements } Store.verify(indexInput); snapshotStatus.addProcessedFile(fileInfo.length()); - } catch (Throwable t) { + } catch (Exception t) { failStoreIfCorrupted(t); snapshotStatus.addProcessedFile(0); throw t; } } - private void failStoreIfCorrupted(Throwable t) { - if (t instanceof CorruptIndexException || t instanceof IndexFormatTooOldException || t instanceof IndexFormatTooNewException) { + private void failStoreIfCorrupted(Exception e) { + if (e instanceof CorruptIndexException || e instanceof IndexFormatTooOldException || e instanceof IndexFormatTooNewException) { try { - store.markStoreCorrupted((IOException) t); - } catch (IOException e) { - logger.warn("store cannot be marked as corrupted", e); + store.markStoreCorrupted((IOException) e); + } catch (IOException inner) { + inner.addSuppressed(e); + logger.warn("store cannot be marked as corrupted", inner); } } } @@ -730,7 +731,7 @@ public class BlobStoreIndexShardRepository extends AbstractComponent implements * The new logic for StoreFileMetaData reads the entire .si and segments.n files to strengthen the * comparison of the files on a per-segment / per-commit level. */ - private static void maybeRecalculateMetadataHash(final BlobContainer blobContainer, final FileInfo fileInfo, Store.MetadataSnapshot snapshot) throws Throwable { + private static void maybeRecalculateMetadataHash(final BlobContainer blobContainer, final FileInfo fileInfo, Store.MetadataSnapshot snapshot) throws Exception { final StoreFileMetaData metadata; if (fileInfo != null && (metadata = snapshot.get(fileInfo.physicalName())) != null) { if (metadata.hash().length > 0 && fileInfo.metadata().hash().length == 0) { @@ -836,7 +837,7 @@ public class BlobStoreIndexShardRepository extends AbstractComponent implements // don't have this hash we try to read that hash from the blob store // in a bwc compatible way. maybeRecalculateMetadataHash(blobContainer, fileInfo, recoveryTargetMetadata); - } catch (Throwable e) { + } catch (Exception e) { // if the index is broken we might not be able to read it logger.warn("{} Can't calculate hash from blog for file [{}] [{}]", e, shardId, fileInfo.physicalName(), fileInfo.metadata()); } diff --git a/core/src/main/java/org/elasticsearch/index/store/Store.java b/core/src/main/java/org/elasticsearch/index/store/Store.java index 2f647933ea2..211f97d8916 100644 --- a/core/src/main/java/org/elasticsearch/index/store/Store.java +++ b/core/src/main/java/org/elasticsearch/index/store/Store.java @@ -302,7 +302,7 @@ public class Store extends AbstractIndexShardComponent implements Closeable, Ref try { directory.deleteFile(origFile); } catch (FileNotFoundException | NoSuchFileException e) { - } catch (Throwable ex) { + } catch (Exception ex) { logger.debug("failed to delete file [{}]", ex, origFile); } // now, rename the files... and fail it it won't work @@ -569,7 +569,7 @@ public class Store extends AbstractIndexShardComponent implements Closeable, Ref final byte[] buffer = new byte[size]; input.readBytes(buffer, 0, buffer.length); StreamInput in = StreamInput.wrap(buffer); - Throwable t = in.readThrowable(); + Exception t = in.readException(); if (t instanceof CorruptIndexException) { ex.add((CorruptIndexException) t); } else { @@ -838,7 +838,7 @@ public class Store extends AbstractIndexShardComponent implements Closeable, Ref } catch (CorruptIndexException | IndexNotFoundException | IndexFormatTooOldException | IndexFormatTooNewException ex) { // we either know the index is corrupted or it's just not there throw ex; - } catch (Throwable ex) { + } catch (Exception ex) { try { // Lucene checks the checksum after it tries to lookup the codec etc. // in that case we might get only IAE or similar exceptions while we are really corrupt... @@ -846,14 +846,14 @@ public class Store extends AbstractIndexShardComponent implements Closeable, Ref logger.warn("failed to build store metadata. checking segment info integrity (with commit [{}])", ex, commit == null ? "no" : "yes"); Lucene.checkSegmentInfoIntegrity(directory); + throw ex; } catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException cex) { cex.addSuppressed(ex); throw cex; - } catch (Throwable e) { - // ignore... + } catch (Exception inner) { + ex.addSuppressed(inner); + throw ex; } - - throw ex; } return new LoadedMetadata(unmodifiableMap(builder), unmodifiableMap(commitUserDataBuilder), numDocs); } @@ -878,7 +878,7 @@ public class Store extends AbstractIndexShardComponent implements Closeable, Ref checksum = digestToString(CodecUtil.retrieveChecksum(in)); } - } catch (Throwable ex) { + } catch (Exception ex) { logger.debug("Can retrieve checksum from file [{}]", ex, file); throw ex; } @@ -1320,8 +1320,8 @@ public class Store extends AbstractIndexShardComponent implements Closeable, Ref for (String file : files) { try { directory().deleteFile(file); - } catch (Throwable ex) { - // ignore + } catch (Exception ex) { + // ignore :( } } } diff --git a/core/src/main/java/org/elasticsearch/index/termvectors/TermVectorsService.java b/core/src/main/java/org/elasticsearch/index/termvectors/TermVectorsService.java index 6b8bc607679..fb013f5c31f 100644 --- a/core/src/main/java/org/elasticsearch/index/termvectors/TermVectorsService.java +++ b/core/src/main/java/org/elasticsearch/index/termvectors/TermVectorsService.java @@ -65,9 +65,6 @@ import java.util.function.LongSupplier; import static org.elasticsearch.index.mapper.SourceToParse.source; -/** - */ - public class TermVectorsService { @@ -149,7 +146,7 @@ public class TermVectorsService { termVectorsResponse.setFields(termVectorsByField, request.selectedFields(), request.getFlags(), topLevelFields, dfs, termVectorsFilter); } termVectorsResponse.setTookInMillis(TimeUnit.NANOSECONDS.toMillis(nanoTimeSupplier.getAsLong() - startTime)); - } catch (Throwable ex) { + } catch (Exception ex) { throw new ElasticsearchException("failed to execute term vector request", ex); } finally { searcher.close(); @@ -237,8 +234,7 @@ public class TermVectorsService { return selectedFields; } - private static Fields generateTermVectors(IndexShard indexShard, Collection getFields, boolean withOffsets, @Nullable Map perFieldAnalyzer, Set fields) - throws IOException { + private static Fields generateTermVectors(IndexShard indexShard, Collection getFields, boolean withOffsets, @Nullable Map perFieldAnalyzer, Set fields) throws IOException { /* store document in memory index */ MemoryIndex index = new MemoryIndex(withOffsets); for (GetField getField : getFields) { @@ -256,7 +252,7 @@ public class TermVectorsService { return MultiFields.getFields(index.createSearcher().getIndexReader()); } - private static Fields generateTermVectorsFromDoc(IndexShard indexShard, TermVectorsRequest request, boolean doAllFields) throws Throwable { + private static Fields generateTermVectorsFromDoc(IndexShard indexShard, TermVectorsRequest request, boolean doAllFields) throws IOException { // parse the document, at the moment we do update the mapping, just like percolate ParsedDocument parsedDocument = parseDocument(indexShard, indexShard.shardId().getIndexName(), request.type(), request.doc()); @@ -287,7 +283,7 @@ public class TermVectorsService { return generateTermVectors(indexShard, getFields, request.offsets(), request.perFieldAnalyzer(), seenFields); } - private static ParsedDocument parseDocument(IndexShard indexShard, String index, String type, BytesReference doc) throws Throwable { + private static ParsedDocument parseDocument(IndexShard indexShard, String index, String type, BytesReference doc) { MapperService mapperService = indexShard.mapperService(); DocumentMapperForType docMapper = mapperService.documentMapperWithAutoCreate(type); ParsedDocument parsedDocument = docMapper.getDocumentMapper().parse(source(index, type, "_id_for_tv_api", doc)); diff --git a/core/src/main/java/org/elasticsearch/index/translog/Translog.java b/core/src/main/java/org/elasticsearch/index/translog/Translog.java index 083e011516c..cbb54bd9d50 100644 --- a/core/src/main/java/org/elasticsearch/index/translog/Translog.java +++ b/core/src/main/java/org/elasticsearch/index/translog/Translog.java @@ -206,11 +206,11 @@ public class Translog extends AbstractIndexShardComponent implements IndexShardC } // now that we know which files are there, create a new current one. - } catch (Throwable t) { + } catch (Exception e) { // close the opened translog files if we fail to create a new translog... IOUtils.closeWhileHandlingException(current); IOUtils.closeWhileHandlingException(readers); - throw t; + throw e; } } @@ -437,10 +437,18 @@ public class Translog extends AbstractIndexShardComponent implements IndexShardC return location; } } catch (AlreadyClosedException | IOException ex) { - closeOnTragicEvent(ex); + try { + closeOnTragicEvent(ex); + } catch (Exception inner) { + ex.addSuppressed(inner); + } throw ex; - } catch (Throwable e) { - closeOnTragicEvent(e); + } catch (Exception e) { + try { + closeOnTragicEvent(e); + } catch (Exception inner) { + e.addSuppressed(inner); + } throw new TranslogException(shardId, "Failed to write operation [" + operation + "]", e); } finally { Releasables.close(out.bytes()); @@ -508,8 +516,12 @@ public class Translog extends AbstractIndexShardComponent implements IndexShardC if (closed.get() == false) { current.sync(); } - } catch (Throwable ex) { - closeOnTragicEvent(ex); + } catch (Exception ex) { + try { + closeOnTragicEvent(ex); + } catch (Exception inner) { + ex.addSuppressed(inner); + } throw ex; } } @@ -541,14 +553,18 @@ public class Translog extends AbstractIndexShardComponent implements IndexShardC ensureOpen(); return current.syncUpTo(location.translogLocation + location.size); } - } catch (Throwable ex) { - closeOnTragicEvent(ex); + } catch (Exception ex) { + try { + closeOnTragicEvent(ex); + } catch (Exception inner) { + ex.addSuppressed(inner); + } throw ex; } return false; } - private void closeOnTragicEvent(Throwable ex) { + private void closeOnTragicEvent(Exception ex) { if (current.getTragicException() != null) { try { close(); @@ -1193,9 +1209,9 @@ public class Translog extends AbstractIndexShardComponent implements IndexShardC current = createWriter(current.getGeneration() + 1); logger.trace("current translog set to [{}]", current.getGeneration()); - } catch (Throwable t) { + } catch (Exception e) { IOUtils.closeWhileHandlingException(this); // tragic event - throw t; + throw e; } } @@ -1318,7 +1334,7 @@ public class Translog extends AbstractIndexShardComponent implements IndexShardC * e.g. disk full while flushing a new segment, this returns the root cause exception. * Otherwise (no tragic exception has occurred) it returns null. */ - public Throwable getTragicException() { + public Exception getTragicException() { return current.getTragicException(); } diff --git a/core/src/main/java/org/elasticsearch/index/translog/TranslogWriter.java b/core/src/main/java/org/elasticsearch/index/translog/TranslogWriter.java index b873c414b4d..89d12983b07 100644 --- a/core/src/main/java/org/elasticsearch/index/translog/TranslogWriter.java +++ b/core/src/main/java/org/elasticsearch/index/translog/TranslogWriter.java @@ -26,7 +26,6 @@ import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.IOUtils; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.Channels; -import org.elasticsearch.common.logging.ESLoggerFactory; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.index.shard.ShardId; @@ -36,7 +35,6 @@ import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; -import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.concurrent.atomic.AtomicBoolean; @@ -55,7 +53,7 @@ public class TranslogWriter extends BaseTranslogReader implements Closeable { /* the number of translog operations written to this file */ private volatile int operationCounter; /* if we hit an exception that we can't recover from we assign it to this var and ship it with every AlreadyClosedException we throw */ - private volatile Throwable tragedy; + private volatile Exception tragedy; /* A buffered outputstream what writes to the writers channel */ private final OutputStream outputStream; /* the total offset of this file including the bytes written to the file as well as into the buffer */ @@ -97,11 +95,11 @@ public class TranslogWriter extends BaseTranslogReader implements Closeable { writeCheckpoint(channelFactory, headerLength, 0, file.getParent(), fileGeneration); final TranslogWriter writer = new TranslogWriter(channelFactory, shardId, fileGeneration, channel, file, bufferSize); return writer; - } catch (Throwable throwable) { + } catch (Exception exception) { // if we fail to bake the file-generation into the checkpoint we stick with the file and once we recover and that // file exists we remove it. We only apply this logic to the checkpoint.generation+1 any other file with a higher generation is an error condition IOUtils.closeWhileHandlingException(channel); - throw throwable; + throw exception; } } @@ -110,18 +108,18 @@ public class TranslogWriter extends BaseTranslogReader implements Closeable { * e.g. disk full while flushing a new segment, this returns the root cause exception. * Otherwise (no tragic exception has occurred) it returns null. */ - public Throwable getTragicException() { + public Exception getTragicException() { return tragedy; } - private synchronized void closeWithTragicEvent(Throwable throwable) throws IOException { - assert throwable != null : "throwable must not be null in a tragic event"; + private synchronized void closeWithTragicEvent(Exception exception) throws IOException { + assert exception != null; if (tragedy == null) { - tragedy = throwable; - } else if (tragedy != throwable) { + tragedy = exception; + } else if (tragedy != exception) { // it should be safe to call closeWithTragicEvents on multiple layers without // worrying about self suppression. - tragedy.addSuppressed(throwable); + tragedy.addSuppressed(exception); } close(); } @@ -134,8 +132,12 @@ public class TranslogWriter extends BaseTranslogReader implements Closeable { final long offset = totalOffset; try { data.writeTo(outputStream); - } catch (Throwable ex) { - closeWithTragicEvent(ex); + } catch (Exception ex) { + try { + closeWithTragicEvent(ex); + } catch (Exception inner) { + ex.addSuppressed(inner); + } throw ex; } totalOffset += data.length(); @@ -184,7 +186,11 @@ public class TranslogWriter extends BaseTranslogReader implements Closeable { try { sync(); // sync before we close.. } catch (IOException e) { - closeWithTragicEvent(e); + try { + closeWithTragicEvent(e); + } catch (Exception inner) { + e.addSuppressed(inner); + } throw e; } if (closed.compareAndSet(false, true)) { @@ -247,8 +253,12 @@ public class TranslogWriter extends BaseTranslogReader implements Closeable { outputStream.flush(); offsetToSync = totalOffset; opsCounter = operationCounter; - } catch (Throwable ex) { - closeWithTragicEvent(ex); + } catch (Exception ex) { + try { + closeWithTragicEvent(ex); + } catch (Exception inner) { + ex.addSuppressed(inner); + } throw ex; } } @@ -257,8 +267,12 @@ public class TranslogWriter extends BaseTranslogReader implements Closeable { try { channel.force(false); writeCheckpoint(channelFactory, offsetToSync, opsCounter, path.getParent(), generation); - } catch (Throwable ex) { - closeWithTragicEvent(ex); + } catch (Exception ex) { + try { + closeWithTragicEvent(ex); + } catch (Exception inner) { + ex.addSuppressed(inner); + } throw ex; } assert lastSyncedOffset <= offsetToSync : "illegal state: " + lastSyncedOffset + " <= " + offsetToSync; @@ -324,8 +338,12 @@ public class TranslogWriter extends BaseTranslogReader implements Closeable { try { ensureOpen(); super.flush(); - } catch (Throwable ex) { - closeWithTragicEvent(ex); + } catch (Exception ex) { + try { + closeWithTragicEvent(ex); + } catch (Exception inner) { + ex.addSuppressed(inner); + } throw ex; } } diff --git a/core/src/main/java/org/elasticsearch/indices/IndexingMemoryController.java b/core/src/main/java/org/elasticsearch/indices/IndexingMemoryController.java index 2a09362e871..514060de844 100644 --- a/core/src/main/java/org/elasticsearch/indices/IndexingMemoryController.java +++ b/core/src/main/java/org/elasticsearch/indices/IndexingMemoryController.java @@ -176,8 +176,8 @@ public class IndexingMemoryController extends AbstractComponent implements Index } @Override - public void onFailure(Throwable t) { - logger.warn("failed to write indexing buffer for shard [{}]; ignoring", t, shard.shardId()); + public void onFailure(Exception e) { + logger.warn("failed to write indexing buffer for shard [{}]; ignoring", e, shard.shardId()); } }); } diff --git a/core/src/main/java/org/elasticsearch/indices/IndicesService.java b/core/src/main/java/org/elasticsearch/indices/IndicesService.java index fadd10eae58..e0b6bb3f0c7 100644 --- a/core/src/main/java/org/elasticsearch/indices/IndicesService.java +++ b/core/src/main/java/org/elasticsearch/indices/IndicesService.java @@ -20,15 +20,14 @@ package org.elasticsearch.indices; import com.carrotsearch.hppc.cursors.ObjectCursor; - import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.store.LockObtainFailedException; import org.apache.lucene.util.CollectionUtil; import org.apache.lucene.util.IOUtils; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.admin.indices.stats.CommonStats; -import org.elasticsearch.action.admin.indices.stats.CommonStatsFlags.Flag; import org.elasticsearch.action.admin.indices.stats.CommonStatsFlags; +import org.elasticsearch.action.admin.indices.stats.CommonStatsFlags.Flag; import org.elasticsearch.action.admin.indices.stats.IndexShardStats; import org.elasticsearch.action.admin.indices.stats.ShardStats; import org.elasticsearch.action.fieldstats.FieldStats; @@ -53,8 +52,8 @@ import org.elasticsearch.common.lease.Releasable; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.IndexScopedSettings; -import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.settings.Setting; +import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; @@ -132,9 +131,6 @@ import static java.util.Collections.unmodifiableMap; import static org.elasticsearch.common.collect.MapBuilder.newMapBuilder; import static org.elasticsearch.common.util.CollectionUtils.arrayAsArrayList; -/** - * - */ public class IndicesService extends AbstractLifecycleComponent implements IndicesClusterStateService.AllocatedIndices, IndexService.ShardStoreDeleter { @@ -221,7 +217,7 @@ public class IndicesService extends AbstractLifecycleComponent indicesStopExecutor.execute(() -> { try { removeIndex(index, "shutdown", false); - } catch (Throwable e) { + } catch (Exception e) { logger.warn("failed to remove index on stop [{}]", e, index); } finally { latch.countDown(); @@ -477,7 +473,7 @@ public class IndicesService extends AbstractLifecycleComponent public void removeIndex(Index index, String reason) { try { removeIndex(index, reason, false); - } catch (Throwable e) { + } catch (Exception e) { logger.warn("failed to remove index ({})", e, reason); } } @@ -568,7 +564,7 @@ public class IndicesService extends AbstractLifecycleComponent public void deleteIndex(Index index, String reason) { try { removeIndex(index, reason, true); - } catch (Throwable e) { + } catch (Exception e) { logger.warn("failed to delete index ({})", e, reason); } } diff --git a/core/src/main/java/org/elasticsearch/indices/analysis/HunspellService.java b/core/src/main/java/org/elasticsearch/indices/analysis/HunspellService.java index e7ba2bfd70f..f3812f6900e 100644 --- a/core/src/main/java/org/elasticsearch/indices/analysis/HunspellService.java +++ b/core/src/main/java/org/elasticsearch/indices/analysis/HunspellService.java @@ -96,7 +96,7 @@ public class HunspellService extends AbstractComponent { this.loadingFunction = (locale) -> { try { return loadDictionary(locale, settings, env); - } catch (Throwable e) { + } catch (Exception e) { throw new IllegalStateException("failed to load hunspell dictionary for locale: " + locale, e); } }; @@ -135,7 +135,7 @@ public class HunspellService extends AbstractComponent { if (inner.iterator().hasNext()) { // just making sure it's indeed a dictionary dir try { getDictionary(file.getFileName().toString()); - } catch (Throwable e) { + } catch (Exception e) { // The cache loader throws unchecked exception (see #loadDictionary()), // here we simply report the exception and continue loading the dictionaries logger.error("exception while loading dictionary {}", e, file.getFileName()); diff --git a/core/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java b/core/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java index b5644ac3bb0..3338f43ab4a 100644 --- a/core/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java +++ b/core/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java @@ -79,9 +79,6 @@ import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; -/** - * - */ public class IndicesClusterStateService extends AbstractLifecycleComponent implements ClusterStateListener { final AllocatedIndices> indicesService; @@ -268,8 +265,8 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent imple if (indexSettings != null) { threadPool.generic().execute(new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - logger.warn("[{}] failed to complete pending deletion for index", t, index); + public void onFailure(Exception e) { + logger.warn("[{}] failed to complete pending deletion for index", e, index); } @Override @@ -427,7 +424,7 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent imple indexMetaData.getIndexUUID(), state.nodes().getLocalNodeId()) ); } - } catch (Throwable t) { + } catch (Exception e) { final String failShardReason; if (indexService == null) { failShardReason = "failed to create index"; @@ -436,7 +433,7 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent imple indicesService.removeIndex(index, "removing index (mapping update failed)"); } for (ShardRouting shardRouting : entry.getValue()) { - sendFailShard(shardRouting, failShardReason, t); + sendFailShard(shardRouting, failShardReason, e); } } } @@ -461,7 +458,7 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent imple newIndexMetaData.getIndexUUID(), state.nodes().getLocalNodeId()) ); } - } catch (Throwable t) { + } catch (Exception e) { indicesService.removeIndex(indexService.index(), "removing index (mapping update failed)"); // fail shards that would be created or updated by createOrUpdateShards @@ -469,7 +466,7 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent imple if (localRoutingNode != null) { for (final ShardRouting shardRouting : localRoutingNode) { if (shardRouting.index().equals(index) && failedShardsCache.containsKey(shardRouting.shardId()) == false) { - sendFailShard(shardRouting, "failed to update mapping for index", t); + sendFailShard(shardRouting, "failed to update mapping for index", e); } } } @@ -526,7 +523,7 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent imple // ignore this, the method call can happen several times logger.debug("Trying to create shard that already exists", e); assert false; - } catch (Throwable e) { + } catch (Exception e) { failAndRemoveShard(shardRouting, true, "failed to create shard", e); } } @@ -539,7 +536,7 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent imple try { shard.updateRoutingEntry(shardRouting); - } catch (Throwable e) { + } catch (Exception e) { failAndRemoveShard(shardRouting, true, "failed updating shard routing entry", e); return; } @@ -627,7 +624,7 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent imple if (Lucene.isCorruptionException(e.getCause())) { restoreService.failRestore(state.getRestoreSource().snapshot(), shardRouting.shardId()); } - } catch (Throwable inner) { + } catch (Exception inner) { e.addSuppressed(inner); } finally { handleRecoveryFailure(shardRouting, sendShardFailure, e); @@ -659,11 +656,11 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent imple } } - private synchronized void handleRecoveryFailure(ShardRouting shardRouting, boolean sendShardFailure, Throwable failure) { + private synchronized void handleRecoveryFailure(ShardRouting shardRouting, boolean sendShardFailure, Exception failure) { failAndRemoveShard(shardRouting, sendShardFailure, "failed recovery", failure); } - private void failAndRemoveShard(ShardRouting shardRouting, boolean sendShardFailure, String message, @Nullable Throwable failure) { + private void failAndRemoveShard(ShardRouting shardRouting, boolean sendShardFailure, String message, @Nullable Exception failure) { try { AllocatedIndex indexService = indicesService.indexService(shardRouting.shardId().getIndex()); if (indexService != null) { @@ -671,8 +668,13 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent imple } } catch (ShardNotFoundException e) { // the node got closed on us, ignore it - } catch (Throwable e1) { - logger.warn("[{}][{}] failed to remove shard after failure ([{}])", e1, shardRouting.getIndexName(), shardRouting.getId(), + } catch (Exception inner) { + inner.addSuppressed(failure); + logger.warn( + "[{}][{}] failed to remove shard after failure ([{}])", + inner, + shardRouting.getIndexName(), + shardRouting.getId(), message); } if (sendShardFailure) { @@ -680,14 +682,19 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent imple } } - private void sendFailShard(ShardRouting shardRouting, String message, @Nullable Throwable failure) { + private void sendFailShard(ShardRouting shardRouting, String message, @Nullable Exception failure) { try { logger.warn("[{}] marking and sending shard failed due to [{}]", failure, shardRouting.shardId(), message); failedShardsCache.put(shardRouting.shardId(), shardRouting); shardStateAction.shardFailed(shardRouting, shardRouting, message, failure, SHARD_STATE_ACTION_LISTENER); - } catch (Throwable e1) { - logger.warn("[{}][{}] failed to mark shard as failed (because of [{}])", e1, shardRouting.getIndexName(), shardRouting.getId(), - message); + } catch (Exception inner) { + if (failure != null) inner.addSuppressed(failure); + logger.warn( + "[{}][{}] failed to mark shard as failed (because of [{}])", + inner, + shardRouting.getIndexName(), + shardRouting.getId(), + message); } } diff --git a/core/src/main/java/org/elasticsearch/indices/fielddata/cache/IndicesFieldDataCache.java b/core/src/main/java/org/elasticsearch/indices/fielddata/cache/IndicesFieldDataCache.java index 4f7d482f8a9..3ab18dd1bd0 100644 --- a/core/src/main/java/org/elasticsearch/indices/fielddata/cache/IndicesFieldDataCache.java +++ b/core/src/main/java/org/elasticsearch/indices/fielddata/cache/IndicesFieldDataCache.java @@ -48,8 +48,6 @@ import java.util.ArrayList; import java.util.List; import java.util.function.ToLongBiFunction; -/** - */ public class IndicesFieldDataCache extends AbstractComponent implements RemovalListener, Releasable{ public static final Setting INDICES_FIELDDATA_CACHE_SIZE_KEY = @@ -91,7 +89,7 @@ public class IndicesFieldDataCache extends AbstractComponent implements RemovalL for (IndexFieldDataCache.Listener listener : key.listeners) { try { listener.onRemoval(key.shardId, indexCache.fieldName, notification.getRemovalReason() == RemovalNotification.RemovalReason.EVICTED, value.ramBytesUsed()); - } catch (Throwable e) { + } catch (Exception e) { // load anyway since listeners should not throw exceptions logger.error("Failed to call listener on field data cache unloading", e); } @@ -138,7 +136,7 @@ public class IndicesFieldDataCache extends AbstractComponent implements RemovalL for (Listener listener : k.listeners) { try { listener.onCache(shardId, fieldName, fieldData); - } catch (Throwable e) { + } catch (Exception e) { // load anyway since listeners should not throw exceptions logger.error("Failed to call listener on atomic field data loading", e); } @@ -162,7 +160,7 @@ public class IndicesFieldDataCache extends AbstractComponent implements RemovalL for (Listener listener : k.listeners) { try { listener.onCache(shardId, fieldName, ifd); - } catch (Throwable e) { + } catch (Exception e) { // load anyway since listeners should not throw exceptions logger.error("Failed to call listener on global ordinals loading", e); } diff --git a/core/src/main/java/org/elasticsearch/indices/flush/SyncedFlushService.java b/core/src/main/java/org/elasticsearch/indices/flush/SyncedFlushService.java index 0fcdd16aba7..66963a4c59c 100644 --- a/core/src/main/java/org/elasticsearch/indices/flush/SyncedFlushService.java +++ b/core/src/main/java/org/elasticsearch/indices/flush/SyncedFlushService.java @@ -99,7 +99,7 @@ public class SyncedFlushService extends AbstractComponent implements IndexEventL } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { logger.debug("{} sync flush on inactive shard failed", e, indexShard.shardId()); } }); @@ -143,7 +143,7 @@ public class SyncedFlushService extends AbstractComponent implements IndexEventL } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { logger.debug("{} unexpected error while executing synced flush", shardId); final int totalShards = indexMetaData.getNumberOfReplicas() + 1; results.get(index).add(new ShardsSyncedFlushResult(shardId, totalShards, e.getMessage())); @@ -219,7 +219,7 @@ public class SyncedFlushService extends AbstractComponent implements IndexEventL } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { actionListener.onFailure(e); } }; @@ -228,15 +228,15 @@ public class SyncedFlushService extends AbstractComponent implements IndexEventL } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { actionListener.onFailure(e); } }; // 1. send pre-sync flushes to all replicas sendPreSyncRequests(activeShards, state, shardId, commitIdsListener); - } catch (Throwable t) { - actionListener.onFailure(t); + } catch (Exception e) { + actionListener.onFailure(e); } } @@ -292,8 +292,8 @@ public class SyncedFlushService extends AbstractComponent implements IndexEventL return ThreadPool.Names.SAME; } }); - } catch (Throwable t) { - listener.onFailure(t); + } catch (Exception e) { + listener.onFailure(e); } } diff --git a/core/src/main/java/org/elasticsearch/indices/recovery/RecoveriesCollection.java b/core/src/main/java/org/elasticsearch/indices/recovery/RecoveriesCollection.java index 4a2b93de084..19d7a4edf93 100644 --- a/core/src/main/java/org/elasticsearch/indices/recovery/RecoveriesCollection.java +++ b/core/src/main/java/org/elasticsearch/indices/recovery/RecoveriesCollection.java @@ -32,7 +32,6 @@ import org.elasticsearch.threadpool.ThreadPool; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Predicate; /** * This class holds a collection of all on going recoveries on the current node (i.e., the node is the target node @@ -198,8 +197,8 @@ public class RecoveriesCollection { } @Override - public void onFailure(Throwable t) { - logger.error("unexpected error while monitoring recovery [{}]", t, recoveryId); + public void onFailure(Exception e) { + logger.error("unexpected error while monitoring recovery [{}]", e, recoveryId); } @Override diff --git a/core/src/main/java/org/elasticsearch/indices/recovery/RecoverySourceHandler.java b/core/src/main/java/org/elasticsearch/indices/recovery/RecoverySourceHandler.java index 78d9bcf53fd..db2f97787d1 100644 --- a/core/src/main/java/org/elasticsearch/indices/recovery/RecoverySourceHandler.java +++ b/core/src/main/java/org/elasticsearch/indices/recovery/RecoverySourceHandler.java @@ -82,7 +82,7 @@ public class RecoverySourceHandler { private final CancellableThreads cancellableThreads = new CancellableThreads() { @Override - protected void onCancel(String reason, @Nullable Throwable suppressedException) { + protected void onCancel(String reason, @Nullable Exception suppressedException) { RuntimeException e; if (shard.state() == IndexShardState.CLOSED) { // check if the shard got closed on us e = new IndexShardClosedException(shard.shardId(), "shard is closed and recovery was canceled reason [" + reason + "]"); @@ -119,14 +119,14 @@ public class RecoverySourceHandler { final IndexCommit phase1Snapshot; try { phase1Snapshot = shard.snapshotIndex(false); - } catch (Throwable e) { + } catch (Exception e) { IOUtils.closeWhileHandlingException(translogView); throw new RecoveryEngineException(shard.shardId(), 1, "Snapshot failed", e); } try { phase1(phase1Snapshot, translogView); - } catch (Throwable e) { + } catch (Exception e) { throw new RecoveryEngineException(shard.shardId(), 1, "phase1 failed", e); } finally { try { @@ -139,7 +139,7 @@ public class RecoverySourceHandler { logger.trace("{} snapshot translog for recovery. current size is [{}]", shard.shardId(), translogView.totalOperations()); try { phase2(translogView.snapshot()); - } catch (Throwable e) { + } catch (Exception e) { throw new RecoveryEngineException(shard.shardId(), 2, "phase2 failed", e); } @@ -301,7 +301,7 @@ public class RecoverySourceHandler { logger.trace("[{}][{}] recovery [phase1] to {}: took [{}]", indexName, shardId, request.targetNode(), stopWatch.totalTime()); response.phase1Time = stopWatch.totalTime().millis(); - } catch (Throwable e) { + } catch (Exception e) { throw new RecoverFilesRecoveryException(request.shardId(), response.phase1FileNames.size(), new ByteSizeValue(totalSize), e); } finally { store.decRef(); @@ -365,7 +365,7 @@ public class RecoverySourceHandler { logger.trace("[{}][{}] performing relocation hand-off to {}", indexName, shardId, request.targetNode()); try { cancellableThreads.execute(() -> shard.relocated("to " + request.targetNode())); - } catch (Throwable e) { + } catch (Exception e) { logger.debug("[{}][{}] completing relocation hand-off to {} failed", e, indexName, shardId, request.targetNode()); throw e; } @@ -508,7 +508,7 @@ public class RecoverySourceHandler { } } - void sendFiles(Store store, StoreFileMetaData[] files, Function outputStreamFactory) throws Throwable { + void sendFiles(Store store, StoreFileMetaData[] files, Function outputStreamFactory) throws Exception { store.incRef(); try { ArrayUtil.timSort(files, (a, b) -> Long.compare(a.length(), b.length())); // send smallest first @@ -518,9 +518,9 @@ public class RecoverySourceHandler { // it's fine that we are only having the indexInput in the try/with block. The copy methods handles // exceptions during close correctly and doesn't hide the original exception. Streams.copy(new InputStreamIndexInput(indexInput, md.length()), outputStreamFactory.apply(md)); - } catch (Throwable t) { + } catch (Exception e) { final IOException corruptIndexException; - if ((corruptIndexException = ExceptionsHelper.unwrapCorruption(t)) != null) { + if ((corruptIndexException = ExceptionsHelper.unwrapCorruption(e)) != null) { if (store.checkIntegrityNoException(md) == false) { // we are corrupted on the primary -- fail! logger.warn("{} Corrupted file detected {} checksum mismatch", shardId, md); failEngine(corruptIndexException); @@ -528,13 +528,13 @@ public class RecoverySourceHandler { } else { // corruption has happened on the way to replica RemoteTransportException exception = new RemoteTransportException("File corruption occurred on recovery but " + "checksums are ok", null); - exception.addSuppressed(t); + exception.addSuppressed(e); logger.warn("{} Remote file corruption on node {}, recovering {}. local checksum OK", corruptIndexException, shardId, request.targetNode(), md); throw exception; } } else { - throw t; + throw e; } } } diff --git a/core/src/main/java/org/elasticsearch/indices/recovery/RecoveryTarget.java b/core/src/main/java/org/elasticsearch/indices/recovery/RecoveryTarget.java index a006c8de921..4a091f53ed1 100644 --- a/core/src/main/java/org/elasticsearch/indices/recovery/RecoveryTarget.java +++ b/core/src/main/java/org/elasticsearch/indices/recovery/RecoveryTarget.java @@ -267,8 +267,8 @@ public class RecoveryTarget extends AbstractRefCounted implements RecoveryTarget logger.trace("closing IndexOutput file [{}]", entry.getValue()); try { entry.getValue().close(); - } catch (Throwable t) { - logger.debug("error while closing recovery output [{}]", t, entry.getValue()); + } catch (Exception e) { + logger.debug("error while closing recovery output [{}]", e, entry.getValue()); } iterator.remove(); } @@ -353,7 +353,7 @@ public class RecoveryTarget extends AbstractRefCounted implements RecoveryTarget } finally { Lucene.cleanLuceneIndex(store.directory()); // clean up and delete all files } - } catch (Throwable e) { + } catch (Exception e) { logger.debug("Failed to clean lucene index", e); ex.addSuppressed(e); } diff --git a/core/src/main/java/org/elasticsearch/indices/recovery/RecoveryTargetService.java b/core/src/main/java/org/elasticsearch/indices/recovery/RecoveryTargetService.java index ec4e74ab8fb..d54d7859089 100644 --- a/core/src/main/java/org/elasticsearch/indices/recovery/RecoveryTargetService.java +++ b/core/src/main/java/org/elasticsearch/indices/recovery/RecoveryTargetService.java @@ -58,7 +58,6 @@ import org.elasticsearch.transport.TransportService; import java.io.IOException; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Predicate; import static org.elasticsearch.common.unit.TimeValue.timeValueMillis; @@ -152,7 +151,7 @@ public class RecoveryTargetService extends AbstractComponent implements IndexEve private void retryRecovery(final RecoveryTarget recoveryTarget, TimeValue retryAfter, final StartRecoveryRequest currentRequest) { try { recoveryTarget.resetRecovery(); - } catch (Throwable e) { + } catch (Exception e) { onGoingRecoveries.failRecovery(recoveryTarget.recoveryId(), new RecoveryFailedException(currentRequest, e), true); } threadPool.schedule(retryAfter, ThreadPool.Names.GENERIC, new RecoveryRunner(recoveryTarget.recoveryId())); @@ -220,7 +219,7 @@ public class RecoveryTargetService extends AbstractComponent implements IndexEve } } catch (CancellableThreads.ExecutionCancelledException e) { logger.trace("recovery cancelled", e); - } catch (Throwable e) { + } catch (Exception e) { if (logger.isTraceEnabled()) { logger.trace("[{}][{}] Got exception on recovery", e, request.shardId().getIndex().getName(), request.shardId().id()); } @@ -432,16 +431,16 @@ public class RecoveryTargetService extends AbstractComponent implements IndexEve } @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { try (RecoveriesCollection.RecoveryRef recoveryRef = onGoingRecoveries.getRecovery(recoveryId)) { if (recoveryRef != null) { - logger.error("unexpected error during recovery [{}], failing shard", t, recoveryId); + logger.error("unexpected error during recovery [{}], failing shard", e, recoveryId); onGoingRecoveries.failRecovery(recoveryId, - new RecoveryFailedException(recoveryRef.status().state(), "unexpected error", t), + new RecoveryFailedException(recoveryRef.status().state(), "unexpected error", e), true // be safe ); } else { - logger.debug("unexpected error during recovery, but recovery id [{}] is finished", t, recoveryId); + logger.debug("unexpected error during recovery, but recovery id [{}] is finished", e, recoveryId); } } } diff --git a/core/src/main/java/org/elasticsearch/indices/recovery/SharedFSRecoverySourceHandler.java b/core/src/main/java/org/elasticsearch/indices/recovery/SharedFSRecoverySourceHandler.java index 868b5dba9b9..6794475e0a3 100644 --- a/core/src/main/java/org/elasticsearch/indices/recovery/SharedFSRecoverySourceHandler.java +++ b/core/src/main/java/org/elasticsearch/indices/recovery/SharedFSRecoverySourceHandler.java @@ -61,7 +61,7 @@ public class SharedFSRecoverySourceHandler extends RecoverySourceHandler { prepareTargetForTranslog(0); finalizeRecovery(); return response; - } catch (Throwable t) { + } catch (Exception e) { if (engineClosed) { // If the relocation fails then the primary is closed and can't be // used anymore... (because it's closed) that's a problem, so in @@ -69,11 +69,11 @@ public class SharedFSRecoverySourceHandler extends RecoverySourceHandler { // create a new IndexWriter logger.info("recovery failed for primary shadow shard, failing shard"); // pass the failure as null, as we want to ensure the store is not marked as corrupted - shard.failShard("primary relocation failed on shared filesystem", t); + shard.failShard("primary relocation failed on shared filesystem", e); } else { - logger.info("recovery failed on shared filesystem", t); + logger.info("recovery failed on shared filesystem", e); } - throw t; + throw e; } } diff --git a/core/src/main/java/org/elasticsearch/indices/store/IndicesStore.java b/core/src/main/java/org/elasticsearch/indices/store/IndicesStore.java index 8766d23d3ee..bc7e7f59fc0 100644 --- a/core/src/main/java/org/elasticsearch/indices/store/IndicesStore.java +++ b/core/src/main/java/org/elasticsearch/indices/store/IndicesStore.java @@ -265,15 +265,15 @@ public class IndicesStore extends AbstractComponent implements ClusterStateListe } try { indicesService.deleteShardStore("no longer used", shardId, currentState); - } catch (Throwable ex) { + } catch (Exception ex) { logger.debug("{} failed to delete unallocated shard, ignoring", ex, shardId); } return currentState; } @Override - public void onFailure(String source, Throwable t) { - logger.error("{} unexpected error during deletion of unallocated shard", t, shardId); + public void onFailure(String source, Exception e) { + logger.error("{} unexpected error during deletion of unallocated shard", e, shardId); } }); } diff --git a/core/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java b/core/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java index b837839ce86..a752c226429 100644 --- a/core/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java +++ b/core/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java @@ -140,7 +140,7 @@ public class IndicesTTLService extends AbstractLifecycleComponent { try { List shardsToPurge = getShardsToPurge(); purgeShards(shardsToPurge); - } catch (Throwable e) { + } catch (Exception e) { if (running.get()) { logger.warn("failed to execute ttl purge", e); } @@ -295,7 +295,7 @@ public class IndicesTTLService extends AbstractLifecycleComponent { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { if (logger.isTraceEnabled()) { logger.trace("failed to execute bulk", e); } else { diff --git a/core/src/main/java/org/elasticsearch/ingest/ConfigurationUtils.java b/core/src/main/java/org/elasticsearch/ingest/ConfigurationUtils.java index 54fbc4a0237..86c8644134c 100644 --- a/core/src/main/java/org/elasticsearch/ingest/ConfigurationUtils.java +++ b/core/src/main/java/org/elasticsearch/ingest/ConfigurationUtils.java @@ -120,7 +120,7 @@ public final class ConfigurationUtils { } try { return Integer.parseInt(value.toString()); - } catch (Throwable t) { + } catch (Exception e) { throw newConfigurationException(processorType, processorTag, propertyName, "property cannot be converted to an int [" + value.toString() + "]"); } diff --git a/core/src/main/java/org/elasticsearch/ingest/PipelineExecutionService.java b/core/src/main/java/org/elasticsearch/ingest/PipelineExecutionService.java index e47c4db2340..e7146636534 100644 --- a/core/src/main/java/org/elasticsearch/ingest/PipelineExecutionService.java +++ b/core/src/main/java/org/elasticsearch/ingest/PipelineExecutionService.java @@ -51,13 +51,13 @@ public class PipelineExecutionService implements ClusterStateListener { this.threadPool = threadPool; } - public void executeIndexRequest(IndexRequest request, Consumer failureHandler, Consumer completionHandler) { + public void executeIndexRequest(IndexRequest request, Consumer failureHandler, Consumer completionHandler) { Pipeline pipeline = getPipeline(request.getPipeline()); threadPool.executor(ThreadPool.Names.INDEX).execute(new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - failureHandler.accept(t); + public void onFailure(Exception e) { + failureHandler.accept(e); } @Override @@ -69,13 +69,13 @@ public class PipelineExecutionService implements ClusterStateListener { } public void executeBulkRequest(Iterable> actionRequests, - BiConsumer itemFailureHandler, - Consumer completionHandler) { + BiConsumer itemFailureHandler, + Consumer completionHandler) { threadPool.executor(ThreadPool.Names.BULK).execute(new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - completionHandler.accept(t); + public void onFailure(Exception e) { + completionHandler.accept(e); } @Override @@ -89,7 +89,7 @@ public class PipelineExecutionService implements ClusterStateListener { //this shouldn't be needed here but we do it for consistency with index api // which requires it to prevent double execution indexRequest.setPipeline(null); - } catch (Throwable e) { + } catch (Exception e) { itemFailureHandler.accept(indexRequest, e); } } diff --git a/core/src/main/java/org/elasticsearch/monitor/Probes.java b/core/src/main/java/org/elasticsearch/monitor/Probes.java index e31903c0bce..fbdd022736b 100644 --- a/core/src/main/java/org/elasticsearch/monitor/Probes.java +++ b/core/src/main/java/org/elasticsearch/monitor/Probes.java @@ -30,7 +30,7 @@ public class Probes { if (load >= 0) { return (short) (load * 100); } - } catch (Throwable t) { + } catch (Exception e) { return -1; } } diff --git a/core/src/main/java/org/elasticsearch/monitor/jvm/JvmGcMonitorService.java b/core/src/main/java/org/elasticsearch/monitor/jvm/JvmGcMonitorService.java index 4c89c6a2a50..1f769e1dc96 100644 --- a/core/src/main/java/org/elasticsearch/monitor/jvm/JvmGcMonitorService.java +++ b/core/src/main/java/org/elasticsearch/monitor/jvm/JvmGcMonitorService.java @@ -185,8 +185,8 @@ public class JvmGcMonitorService extends AbstractLifecycleComponent { } scheduledFuture = threadPool.scheduleWithFixedDelay(new JvmMonitor(gcThresholds, gcOverheadThreshold) { @Override - void onMonitorFailure(Throwable t) { - logger.debug("failed to monitor", t); + void onMonitorFailure(Exception e) { + logger.debug("failed to monitor", e); } @Override @@ -389,12 +389,12 @@ public class JvmGcMonitorService extends AbstractLifecycleComponent { public void run() { try { monitorGc(); - } catch (Throwable t) { - onMonitorFailure(t); + } catch (Exception e) { + onMonitorFailure(e); } } - abstract void onMonitorFailure(Throwable t); + abstract void onMonitorFailure(Exception e); synchronized void monitorGc() { seq++; diff --git a/core/src/main/java/org/elasticsearch/monitor/jvm/JvmInfo.java b/core/src/main/java/org/elasticsearch/monitor/jvm/JvmInfo.java index 69abd0752f6..1619ecee23a 100644 --- a/core/src/main/java/org/elasticsearch/monitor/jvm/JvmInfo.java +++ b/core/src/main/java/org/elasticsearch/monitor/jvm/JvmInfo.java @@ -76,7 +76,7 @@ public class JvmInfo implements Streamable, ToXContent { try { Class vmClass = Class.forName("sun.misc.VM"); info.mem.directMemoryMax = (Long) vmClass.getMethod("maxDirectMemory").invoke(null); - } catch (Throwable t) { + } catch (Exception t) { // ignore } info.inputArguments = runtimeMXBean.getInputArguments().toArray(new String[runtimeMXBean.getInputArguments().size()]); diff --git a/core/src/main/java/org/elasticsearch/monitor/jvm/JvmStats.java b/core/src/main/java/org/elasticsearch/monitor/jvm/JvmStats.java index 7122f1ea382..353b4178259 100644 --- a/core/src/main/java/org/elasticsearch/monitor/jvm/JvmStats.java +++ b/core/src/main/java/org/elasticsearch/monitor/jvm/JvmStats.java @@ -88,9 +88,7 @@ public class JvmStats implements Streamable, ToXContent { peakUsage.getUsed() < 0 ? 0 : peakUsage.getUsed(), peakUsage.getMax() < 0 ? 0 : peakUsage.getMax() )); - } catch (OutOfMemoryError err) { - throw err; // rethrow - } catch (Throwable ex) { + } catch (Exception ex) { /* ignore some JVMs might barf here with: * java.lang.InternalError: Memory Pool not found * we just omit the pool in that case!*/ @@ -119,7 +117,7 @@ public class JvmStats implements Streamable, ToXContent { for (BufferPoolMXBean bufferPool : bufferPools) { stats.bufferPools.add(new BufferPool(bufferPool.getName(), bufferPool.getCount(), bufferPool.getTotalCapacity(), bufferPool.getMemoryUsed())); } - } catch (Throwable t) { + } catch (Exception e) { // buffer pools are not available } diff --git a/core/src/main/java/org/elasticsearch/monitor/os/OsProbe.java b/core/src/main/java/org/elasticsearch/monitor/os/OsProbe.java index f41afb90e05..017f961a315 100644 --- a/core/src/main/java/org/elasticsearch/monitor/os/OsProbe.java +++ b/core/src/main/java/org/elasticsearch/monitor/os/OsProbe.java @@ -60,7 +60,7 @@ public class OsProbe { } try { return (long) getFreePhysicalMemorySize.invoke(osMxBean); - } catch (Throwable t) { + } catch (Exception e) { return -1; } } @@ -74,7 +74,7 @@ public class OsProbe { } try { return (long) getTotalPhysicalMemorySize.invoke(osMxBean); - } catch (Throwable t) { + } catch (Exception e) { return -1; } } @@ -88,7 +88,7 @@ public class OsProbe { } try { return (long) getFreeSwapSpaceSize.invoke(osMxBean); - } catch (Throwable t) { + } catch (Exception e) { return -1; } } @@ -102,7 +102,7 @@ public class OsProbe { } try { return (long) getTotalSwapSpaceSize.invoke(osMxBean); - } catch (Throwable t) { + } catch (Exception e) { return -1; } } @@ -128,7 +128,7 @@ public class OsProbe { try { double oneMinuteLoadAverage = (double) getSystemLoadAverage.invoke(osMxBean); return new double[] { oneMinuteLoadAverage >= 0 ? oneMinuteLoadAverage : -1, -1, -1 }; - } catch (Throwable t) { + } catch (Exception e) { return null; } } @@ -199,7 +199,7 @@ public class OsProbe { private static Method getMethod(String methodName) { try { return Class.forName("com.sun.management.OperatingSystemMXBean").getMethod(methodName); - } catch (Throwable t) { + } catch (Exception e) { // not available return null; } diff --git a/core/src/main/java/org/elasticsearch/monitor/process/ProcessProbe.java b/core/src/main/java/org/elasticsearch/monitor/process/ProcessProbe.java index 019a00bd4c8..b19b54a9478 100644 --- a/core/src/main/java/org/elasticsearch/monitor/process/ProcessProbe.java +++ b/core/src/main/java/org/elasticsearch/monitor/process/ProcessProbe.java @@ -66,7 +66,7 @@ public class ProcessProbe { } try { return (Long) getMaxFileDescriptorCountField.invoke(osMxBean); - } catch (Throwable t) { + } catch (Exception t) { return -1; } } @@ -80,7 +80,7 @@ public class ProcessProbe { } try { return (Long) getOpenFileDescriptorCountField.invoke(osMxBean); - } catch (Throwable t) { + } catch (Exception t) { return -1; } } @@ -102,7 +102,7 @@ public class ProcessProbe { if (time >= 0) { return (time / 1_000_000L); } - } catch (Throwable t) { + } catch (Exception t) { return -1; } } @@ -119,7 +119,7 @@ public class ProcessProbe { if (virtual >= 0) { return virtual; } - } catch (Throwable t) { + } catch (Exception t) { return -1; } } @@ -155,12 +155,12 @@ public class ProcessProbe { private static Method getMethod(String methodName) { try { return Class.forName("com.sun.management.OperatingSystemMXBean").getMethod(methodName); - } catch (Throwable t) { + } catch (Exception t) { // not available return null; } } - + /** * Returns a given method of the UnixOperatingSystemMXBean, * or null if the method is not found or unavailable. @@ -168,7 +168,7 @@ public class ProcessProbe { private static Method getUnixMethod(String methodName) { try { return Class.forName("com.sun.management.UnixOperatingSystemMXBean").getMethod(methodName); - } catch (Throwable t) { + } catch (Exception t) { // not available return null; } diff --git a/core/src/main/java/org/elasticsearch/plugins/PluginsService.java b/core/src/main/java/org/elasticsearch/plugins/PluginsService.java index 4769b5954ba..077f65d3da8 100644 --- a/core/src/main/java/org/elasticsearch/plugins/PluginsService.java +++ b/core/src/main/java/org/elasticsearch/plugins/PluginsService.java @@ -457,7 +457,7 @@ public class PluginsService extends AbstractComponent { "Settings instance"); } } - } catch (Throwable e) { + } catch (Exception e) { throw new ElasticsearchException("Failed to load plugin class [" + pluginClass.getName() + "]", e); } } diff --git a/core/src/main/java/org/elasticsearch/repositories/RepositoriesService.java b/core/src/main/java/org/elasticsearch/repositories/RepositoriesService.java index 383ded2b2de..0ed53c0a9c5 100644 --- a/core/src/main/java/org/elasticsearch/repositories/RepositoriesService.java +++ b/core/src/main/java/org/elasticsearch/repositories/RepositoriesService.java @@ -147,9 +147,9 @@ public class RepositoriesService extends AbstractComponent implements ClusterSta } @Override - public void onFailure(String source, Throwable t) { - logger.warn("failed to create repository [{}]", t, request.name); - super.onFailure(source, t); + public void onFailure(String source, Exception e) { + logger.warn("failed to create repository [{}]", e, request.name); + super.onFailure(source, e); } @Override @@ -221,32 +221,33 @@ public class RepositoriesService extends AbstractComponent implements ClusterSta public void onResponse(VerifyResponse verifyResponse) { try { repository.endVerification(verificationToken); - } catch (Throwable t) { - logger.warn("[{}] failed to finish repository verification", t, repositoryName); - listener.onFailure(t); + } catch (Exception e) { + logger.warn("[{}] failed to finish repository verification", e, repositoryName); + listener.onFailure(e); return; } listener.onResponse(verifyResponse); } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { listener.onFailure(e); } }); - } catch (Throwable t) { + } catch (Exception e) { try { repository.endVerification(verificationToken); - } catch (Throwable t1) { - logger.warn("[{}] failed to finish repository verification", t1, repositoryName); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.warn("[{}] failed to finish repository verification", inner, repositoryName); } - listener.onFailure(t); + listener.onFailure(e); } } else { listener.onResponse(new VerifyResponse(new DiscoveryNode[0], new VerificationFailure[0])); } - } catch (Throwable t) { - listener.onFailure(t); + } catch (Exception e) { + listener.onFailure(e); } } @@ -313,7 +314,7 @@ public class RepositoriesService extends AbstractComponent implements ClusterSta } } repositories = unmodifiableMap(builder); - } catch (Throwable ex) { + } catch (Exception ex) { logger.warn("failure updating cluster state ", ex); } } @@ -410,9 +411,9 @@ public class RepositoriesService extends AbstractComponent implements ClusterSta IndexShardRepository indexShardRepository = repositoryInjector.getInstance(IndexShardRepository.class); repository.start(); return new RepositoryHolder(repositoryMetaData.type(), repositoryMetaData.settings(), repository, indexShardRepository); - } catch (Throwable t) { - logger.warn("failed to create repository [{}][{}]", t, repositoryMetaData.type(), repositoryMetaData.name()); - throw new RepositoryException(repositoryMetaData.name(), "failed to create repository", t); + } catch (Exception e) { + logger.warn("failed to create repository [{}][{}]", e, repositoryMetaData.type(), repositoryMetaData.name()); + throw new RepositoryException(repositoryMetaData.name(), "failed to create repository", e); } } @@ -448,7 +449,7 @@ public class RepositoriesService extends AbstractComponent implements ClusterSta } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { listener.onFailure(e); } }); @@ -458,7 +459,7 @@ public class RepositoriesService extends AbstractComponent implements ClusterSta } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { listener.onFailure(e); } } diff --git a/core/src/main/java/org/elasticsearch/repositories/VerificationFailure.java b/core/src/main/java/org/elasticsearch/repositories/VerificationFailure.java index c5c974715c4..5672506b7fe 100644 --- a/core/src/main/java/org/elasticsearch/repositories/VerificationFailure.java +++ b/core/src/main/java/org/elasticsearch/repositories/VerificationFailure.java @@ -31,13 +31,13 @@ public class VerificationFailure implements Streamable { private String nodeId; - private Throwable cause; + private Exception cause; VerificationFailure() { } - public VerificationFailure(String nodeId, Throwable cause) { + public VerificationFailure(String nodeId, Exception cause) { this.nodeId = nodeId; this.cause = cause; } @@ -53,7 +53,7 @@ public class VerificationFailure implements Streamable { @Override public void readFrom(StreamInput in) throws IOException { nodeId = in.readOptionalString(); - cause = in.readThrowable(); + cause = in.readException(); } @Override diff --git a/core/src/main/java/org/elasticsearch/repositories/VerifyNodeRepositoryAction.java b/core/src/main/java/org/elasticsearch/repositories/VerifyNodeRepositoryAction.java index 93bcca1c375..796c65e9b46 100644 --- a/core/src/main/java/org/elasticsearch/repositories/VerifyNodeRepositoryAction.java +++ b/core/src/main/java/org/elasticsearch/repositories/VerifyNodeRepositoryAction.java @@ -83,9 +83,9 @@ public class VerifyNodeRepositoryAction extends AbstractComponent { if (node.equals(localNode)) { try { doVerify(repository, verificationToken); - } catch (Throwable t) { - logger.warn("[{}] failed to verify repository", t, repository); - errors.add(new VerificationFailure(node.getId(), t)); + } catch (Exception e) { + logger.warn("[{}] failed to verify repository", e, repository); + errors.add(new VerificationFailure(node.getId(), e)); } if (counter.decrementAndGet() == 0) { finishVerification(listener, nodes, errors); diff --git a/core/src/main/java/org/elasticsearch/repositories/blobstore/BlobStoreRepository.java b/core/src/main/java/org/elasticsearch/repositories/blobstore/BlobStoreRepository.java index d0d6503a6f9..b1f1ff66cf5 100644 --- a/core/src/main/java/org/elasticsearch/repositories/blobstore/BlobStoreRepository.java +++ b/core/src/main/java/org/elasticsearch/repositories/blobstore/BlobStoreRepository.java @@ -223,7 +223,7 @@ public abstract class BlobStoreRepository extends AbstractLifecycleComponent imp protected void doClose() { try { blobStore().close(); - } catch (Throwable t) { + } catch (Exception t) { logger.warn("cannot close blob store", t); } } diff --git a/core/src/main/java/org/elasticsearch/rest/BytesRestResponse.java b/core/src/main/java/org/elasticsearch/rest/BytesRestResponse.java index 8cdbca512e7..fcf79962b6b 100644 --- a/core/src/main/java/org/elasticsearch/rest/BytesRestResponse.java +++ b/core/src/main/java/org/elasticsearch/rest/BytesRestResponse.java @@ -77,22 +77,22 @@ public class BytesRestResponse extends RestResponse { this.contentType = contentType; } - public BytesRestResponse(RestChannel channel, Throwable t) throws IOException { - this(channel, ExceptionsHelper.status(t), t); + public BytesRestResponse(RestChannel channel, Exception e) throws IOException { + this(channel, ExceptionsHelper.status(e), e); } - public BytesRestResponse(RestChannel channel, RestStatus status, Throwable t) throws IOException { + public BytesRestResponse(RestChannel channel, RestStatus status, Exception e) throws IOException { this.status = status; if (channel.request().method() == RestRequest.Method.HEAD) { this.content = BytesArray.EMPTY; this.contentType = TEXT_CONTENT_TYPE; } else { - XContentBuilder builder = convert(channel, status, t); + XContentBuilder builder = convert(channel, status, e); this.content = builder.bytes(); this.contentType = builder.contentType().mediaType(); } - if (t instanceof ElasticsearchException) { - copyHeaders(((ElasticsearchException) t)); + if (e instanceof ElasticsearchException) { + copyHeaders(((ElasticsearchException) e)); } } @@ -113,9 +113,9 @@ public class BytesRestResponse extends RestResponse { private static final ESLogger SUPPRESSED_ERROR_LOGGER = ESLoggerFactory.getLogger("rest.suppressed"); - private static XContentBuilder convert(RestChannel channel, RestStatus status, Throwable t) throws IOException { + private static XContentBuilder convert(RestChannel channel, RestStatus status, Exception e) throws IOException { XContentBuilder builder = channel.newErrorBuilder().startObject(); - if (t == null) { + if (e == null) { builder.field("error", "unknown"); } else if (channel.detailedErrorsEnabled()) { final ToXContent.Params params; @@ -123,15 +123,15 @@ public class BytesRestResponse extends RestResponse { params = new ToXContent.DelegatingMapParams(Collections.singletonMap(ElasticsearchException.REST_EXCEPTION_SKIP_STACK_TRACE, "false"), channel.request()); } else { if (status.getStatus() < 500) { - SUPPRESSED_ERROR_LOGGER.debug("path: {}, params: {}", t, channel.request().rawPath(), channel.request().params()); + SUPPRESSED_ERROR_LOGGER.debug("path: {}, params: {}", e, channel.request().rawPath(), channel.request().params()); } else { - SUPPRESSED_ERROR_LOGGER.warn("path: {}, params: {}", t, channel.request().rawPath(), channel.request().params()); + SUPPRESSED_ERROR_LOGGER.warn("path: {}, params: {}", e, channel.request().rawPath(), channel.request().params()); } params = channel.request(); } builder.field("error"); builder.startObject(); - final ElasticsearchException[] rootCauses = ElasticsearchException.guessRootCauses(t); + final ElasticsearchException[] rootCauses = ElasticsearchException.guessRootCauses(e); builder.field("root_cause"); builder.startArray(); for (ElasticsearchException rootCause : rootCauses){ @@ -141,10 +141,10 @@ public class BytesRestResponse extends RestResponse { } builder.endArray(); - ElasticsearchException.toXContent(builder, params, t); + ElasticsearchException.toXContent(builder, params, e); builder.endObject(); } else { - builder.field("error", simpleMessage(t)); + builder.field("error", simpleMessage(e)); } builder.field("status", status.getStatus()); builder.endObject(); diff --git a/core/src/main/java/org/elasticsearch/rest/RestController.java b/core/src/main/java/org/elasticsearch/rest/RestController.java index 29dce98ca49..03d2c267c58 100644 --- a/core/src/main/java/org/elasticsearch/rest/RestController.java +++ b/core/src/main/java/org/elasticsearch/rest/RestController.java @@ -171,11 +171,12 @@ public class RestController extends AbstractLifecycleComponent { } } - public void sendErrorResponse(RestRequest request, RestChannel channel, Throwable e) { + public void sendErrorResponse(RestRequest request, RestChannel channel, Exception e) { try { channel.sendResponse(new BytesRestResponse(channel, e)); - } catch (Throwable e1) { - logger.error("failed to send failure response for uri [{}]", e1, request.uri()); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.error("failed to send failure response for uri [{}]", inner, request.uri()); } } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/tasks/RestListTasksAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/tasks/RestListTasksAction.java index 5d1c617e8e3..d2f1769041e 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/tasks/RestListTasksAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/tasks/RestListTasksAction.java @@ -86,7 +86,7 @@ public class RestListTasksAction extends BaseRestHandler { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { channelListener.onFailure(e); } }; diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/head/RestAliasesExistAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/head/RestAliasesExistAction.java index 7c539e1be48..54f9a649168 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/head/RestAliasesExistAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/head/RestAliasesExistAction.java @@ -70,18 +70,19 @@ public class RestAliasesExistAction extends BaseRestHandler { } else { channel.sendResponse(new BytesRestResponse(NOT_FOUND, BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY)); } - } catch (Throwable e) { + } catch (Exception e) { onFailure(e); } } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { try { channel.sendResponse( new BytesRestResponse(ExceptionsHelper.status(e), BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY)); - } catch (Exception e1) { - logger.error("Failed to send failure response", e1); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.error("Failed to send failure response", inner); } } }); diff --git a/core/src/main/java/org/elasticsearch/rest/action/support/RestActionListener.java b/core/src/main/java/org/elasticsearch/rest/action/support/RestActionListener.java index 9ebdc7b5d07..15b0736a790 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/support/RestActionListener.java +++ b/core/src/main/java/org/elasticsearch/rest/action/support/RestActionListener.java @@ -45,19 +45,20 @@ public abstract class RestActionListener implements ActionListener VS valuesSource(ValuesSourceConfig config, SearchContext context) throws IOException { - assert config.valid() : "value source config is invalid - must have either a field context or a script or marked as unmapped"; + if (!config.valid()) { + throw new IllegalStateException( + "value source config is invalid; must have either a field context or a script or marked as unwrapped"); + } final VS vs; if (config.unmapped()) { diff --git a/core/src/main/java/org/elasticsearch/search/query/QueryPhase.java b/core/src/main/java/org/elasticsearch/search/query/QueryPhase.java index 22e6c40d338..189fead7813 100644 --- a/core/src/main/java/org/elasticsearch/search/query/QueryPhase.java +++ b/core/src/main/java/org/elasticsearch/search/query/QueryPhase.java @@ -391,7 +391,7 @@ public class QueryPhase implements SearchPhase { return rescore; - } catch (Throwable e) { + } catch (Exception e) { throw new QueryPhaseExecutionException(searchContext, "Failed to execute main query", e); } } diff --git a/core/src/main/java/org/elasticsearch/snapshots/RestoreService.java b/core/src/main/java/org/elasticsearch/snapshots/RestoreService.java index 4c4d5ed95bf..53fb6f4781e 100644 --- a/core/src/main/java/org/elasticsearch/snapshots/RestoreService.java +++ b/core/src/main/java/org/elasticsearch/snapshots/RestoreService.java @@ -458,9 +458,9 @@ public class RestoreService extends AbstractComponent implements ClusterStateLis @Override - public void onFailure(String source, Throwable t) { - logger.warn("[{}] failed to restore snapshot", t, snapshotId); - listener.onFailure(t); + public void onFailure(String source, Exception e) { + logger.warn("[{}] failed to restore snapshot", e, snapshotId); + listener.onFailure(e); } @Override @@ -475,7 +475,7 @@ public class RestoreService extends AbstractComponent implements ClusterStateLis }); - } catch (Throwable e) { + } catch (Exception e) { logger.warn("[{}] failed to restore snapshot", e, request.repositoryName + ":" + request.snapshotName); listener.onFailure(e); } @@ -598,9 +598,9 @@ public class RestoreService extends AbstractComponent implements ClusterStateLis } @Override - public void onFailure(String source, @Nullable Throwable t) { + public void onFailure(String source, @Nullable Exception e) { for (UpdateIndexShardRestoreStatusRequest request : drainedRequests) { - logger.warn("[{}][{}] failed to update snapshot status to [{}]", t, request.snapshot(), request.shardId(), request.status()); + logger.warn("[{}][{}] failed to update snapshot status to [{}]", e, request.snapshot(), request.shardId(), request.status()); } } @@ -667,7 +667,7 @@ public class RestoreService extends AbstractComponent implements ClusterStateLis for (ActionListener listener : listeners) { try { listener.onResponse(new RestoreCompletionResponse(snapshot, restoreInfo)); - } catch (Throwable e) { + } catch (Exception e) { logger.warn("failed to update snapshot status for [{}]", e, listener); } } @@ -840,7 +840,7 @@ public class RestoreService extends AbstractComponent implements ClusterStateLis if (event.localNodeMaster()) { processDeletedIndices(event); } - } catch (Throwable t) { + } catch (Exception t) { logger.warn("Failed to update restore state ", t); } } diff --git a/core/src/main/java/org/elasticsearch/snapshots/SnapshotShardsService.java b/core/src/main/java/org/elasticsearch/snapshots/SnapshotShardsService.java index 460eaf9f819..91db508b7e3 100644 --- a/core/src/main/java/org/elasticsearch/snapshots/SnapshotShardsService.java +++ b/core/src/main/java/org/elasticsearch/snapshots/SnapshotShardsService.java @@ -163,8 +163,8 @@ public class SnapshotShardsService extends AbstractLifecycleComponent implements syncShardStatsOnNewMaster(event); } - } catch (Throwable t) { - logger.warn("Failed to update snapshot state ", t); + } catch (Exception e) { + logger.warn("Failed to update snapshot state ", e); } } @@ -301,14 +301,14 @@ public class SnapshotShardsService extends AbstractLifecycleComponent implements } @Override - public void onFailure(Throwable t) { - logger.warn("[{}] [{}] failed to create snapshot", t, shardId, entry.getKey()); - updateIndexShardSnapshotStatus(entry.getKey(), shardId, new SnapshotsInProgress.ShardSnapshotStatus(localNodeId, SnapshotsInProgress.State.FAILED, ExceptionsHelper.detailedMessage(t))); + public void onFailure(Exception e) { + logger.warn("[{}] [{}] failed to create snapshot", e, shardId, entry.getKey()); + updateIndexShardSnapshotStatus(entry.getKey(), shardId, new SnapshotsInProgress.ShardSnapshotStatus(localNodeId, SnapshotsInProgress.State.FAILED, ExceptionsHelper.detailedMessage(e))); } }); - } catch (Throwable t) { - updateIndexShardSnapshotStatus(entry.getKey(), shardId, new SnapshotsInProgress.ShardSnapshotStatus(localNodeId, SnapshotsInProgress.State.FAILED, ExceptionsHelper.detailedMessage(t))); + } catch (Exception e) { + updateIndexShardSnapshotStatus(entry.getKey(), shardId, new SnapshotsInProgress.ShardSnapshotStatus(localNodeId, SnapshotsInProgress.State.FAILED, ExceptionsHelper.detailedMessage(e))); } } } @@ -354,7 +354,7 @@ public class SnapshotShardsService extends AbstractLifecycleComponent implements throw e; } catch (IndexShardSnapshotFailedException e) { throw e; - } catch (Throwable e) { + } catch (Exception e) { throw new IndexShardSnapshotFailedException(shardId, "Failed to snapshot", e); } } @@ -483,8 +483,8 @@ public class SnapshotShardsService extends AbstractLifecycleComponent implements transportService.sendRequest(clusterService.state().nodes().getMasterNode(), UPDATE_SNAPSHOT_ACTION_NAME, request, EmptyTransportResponseHandler.INSTANCE_SAME); } - } catch (Throwable t) { - logger.warn("[{}] [{}] failed to update snapshot state", t, request.snapshot(), request.status()); + } catch (Exception e) { + logger.warn("[{}] [{}] failed to update snapshot state", e, request.snapshot(), request.status()); } } @@ -566,9 +566,9 @@ public class SnapshotShardsService extends AbstractLifecycleComponent implements } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { for (UpdateIndexShardSnapshotStatusRequest request : drainedRequests) { - logger.warn("[{}][{}] failed to update snapshot status to [{}]", t, request.snapshot(), request.shardId(), request.status()); + logger.warn("[{}][{}] failed to update snapshot status to [{}]", e, request.snapshot(), request.shardId(), request.status()); } } }); diff --git a/core/src/main/java/org/elasticsearch/snapshots/SnapshotsService.java b/core/src/main/java/org/elasticsearch/snapshots/SnapshotsService.java index e242d1be732..5f5ac65e38e 100644 --- a/core/src/main/java/org/elasticsearch/snapshots/SnapshotsService.java +++ b/core/src/main/java/org/elasticsearch/snapshots/SnapshotsService.java @@ -95,7 +95,7 @@ import static org.elasticsearch.cluster.SnapshotsInProgress.completed; *
  • Once shard snapshot is created data node updates state of the shard in the cluster state using the {@link SnapshotShardsService#updateIndexShardSnapshotStatus} method
  • *
  • When last shard is completed master node in {@link SnapshotShardsService#innerUpdateSnapshotState} method marks the snapshot as completed
  • *
  • After cluster state is updated, the {@link #endSnapshot(SnapshotsInProgress.Entry)} finalizes snapshot in the repository, - * notifies all {@link #snapshotCompletionListeners} that snapshot is completed, and finally calls {@link #removeSnapshotFromClusterState(Snapshot, SnapshotInfo, Throwable)} to remove snapshot from cluster state
  • + * notifies all {@link #snapshotCompletionListeners} that snapshot is completed, and finally calls {@link #removeSnapshotFromClusterState(Snapshot, SnapshotInfo, Exception)} to remove snapshot from cluster state * */ public class SnapshotsService extends AbstractLifecycleComponent implements ClusterStateListener { @@ -249,10 +249,10 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus } @Override - public void onFailure(String source, Throwable t) { - logger.warn("[{}][{}] failed to create snapshot", t, repositoryName, snapshotName); + public void onFailure(String source, Exception e) { + logger.warn("[{}][{}] failed to create snapshot", e, repositoryName, snapshotName); newSnapshot = null; - listener.onFailure(t); + listener.onFailure(e); } @Override @@ -400,9 +400,9 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus } @Override - public void onFailure(String source, Throwable t) { - logger.warn("[{}] failed to create snapshot", t, snapshot.snapshot().getSnapshotId()); - removeSnapshotFromClusterState(snapshot.snapshot(), null, t, new CleanupAfterErrorListener(snapshot, true, userCreateSnapshotListener, t)); + public void onFailure(String source, Exception e) { + logger.warn("[{}] failed to create snapshot", e, snapshot.snapshot().getSnapshotId()); + removeSnapshotFromClusterState(snapshot.snapshot(), null, e, new CleanupAfterErrorListener(snapshot, true, userCreateSnapshotListener, e)); } @Override @@ -422,9 +422,9 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus } } }); - } catch (Throwable t) { - logger.warn("failed to create snapshot [{}]", t, snapshot.snapshot().getSnapshotId()); - removeSnapshotFromClusterState(snapshot.snapshot(), null, t, new CleanupAfterErrorListener(snapshot, snapshotCreated, userCreateSnapshotListener, t)); + } catch (Exception e) { + logger.warn("failed to create snapshot [{}]", e, snapshot.snapshot().getSnapshotId()); + removeSnapshotFromClusterState(snapshot.snapshot(), null, e, new CleanupAfterErrorListener(snapshot, snapshotCreated, userCreateSnapshotListener, e)); } } @@ -433,40 +433,42 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus private final SnapshotsInProgress.Entry snapshot; private final boolean snapshotCreated; private final CreateSnapshotListener userCreateSnapshotListener; - private final Throwable t; + private final Exception e; - public CleanupAfterErrorListener(SnapshotsInProgress.Entry snapshot, boolean snapshotCreated, CreateSnapshotListener userCreateSnapshotListener, Throwable t) { + public CleanupAfterErrorListener(SnapshotsInProgress.Entry snapshot, boolean snapshotCreated, CreateSnapshotListener userCreateSnapshotListener, Exception e) { this.snapshot = snapshot; this.snapshotCreated = snapshotCreated; this.userCreateSnapshotListener = userCreateSnapshotListener; - this.t = t; + this.e = e; } @Override public void onResponse(SnapshotInfo snapshotInfo) { - cleanupAfterError(); + cleanupAfterError(this.e); } @Override - public void onFailure(Throwable e) { - cleanupAfterError(); + public void onFailure(Exception e) { + e.addSuppressed(this.e); + cleanupAfterError(e); } - private void cleanupAfterError() { + private void cleanupAfterError(Exception exception) { if(snapshotCreated) { try { repositoriesService.repository(snapshot.snapshot().getRepository()) .finalizeSnapshot(snapshot.snapshot().getSnapshotId(), snapshot.indices(), snapshot.startTime(), - ExceptionsHelper.detailedMessage(t), + ExceptionsHelper.detailedMessage(exception), 0, Collections.emptyList()); - } catch (Throwable t2) { - logger.warn("[{}] failed to close snapshot in repository", snapshot.snapshot()); + } catch (Exception inner) { + inner.addSuppressed(exception); + logger.warn("[{}] failed to close snapshot in repository", inner, snapshot.snapshot()); } } - userCreateSnapshotListener.onFailure(t); + userCreateSnapshotListener.onFailure(e); } } @@ -591,8 +593,8 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus processStartedShards(event); } } - } catch (Throwable t) { - logger.warn("Failed to update snapshot state ", t); + } catch (Exception e) { + logger.warn("Failed to update snapshot state ", e); } } @@ -653,7 +655,7 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus } @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { logger.warn("failed to clean up abandoned snapshot {} in INIT state", snapshot.snapshot()); } }); @@ -670,7 +672,7 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { logger.warn("failed to update snapshot state after node removal"); } }); @@ -712,8 +714,8 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus } @Override - public void onFailure(String source, Throwable t) { - logger.warn("failed to update snapshot state after shards started from [{}] ", t, source); + public void onFailure(String source, Exception e) { + logger.warn("failed to update snapshot state after shards started from [{}] ", e, source); } }); } @@ -866,9 +868,9 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus } SnapshotInfo snapshotInfo = repository.finalizeSnapshot(snapshot.getSnapshotId(), entry.indices(), entry.startTime(), failure, entry.shards().size(), Collections.unmodifiableList(shardFailures)); removeSnapshotFromClusterState(snapshot, snapshotInfo, null); - } catch (Throwable t) { - logger.warn("[{}] failed to finalize snapshot", t, snapshot); - removeSnapshotFromClusterState(snapshot, null, t); + } catch (Exception e) { + logger.warn("[{}] failed to finalize snapshot", e, snapshot); + removeSnapshotFromClusterState(snapshot, null, e); } } }); @@ -876,24 +878,21 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus /** * Removes record of running snapshot from cluster state - * - * @param snapshot snapshot + * @param snapshot snapshot * @param snapshotInfo snapshot info if snapshot was successful - * @param t exception if snapshot failed + * @param e exception if snapshot failed */ - private void removeSnapshotFromClusterState(final Snapshot snapshot, final SnapshotInfo snapshotInfo, final Throwable t) { - removeSnapshotFromClusterState(snapshot, snapshotInfo, t, null); + private void removeSnapshotFromClusterState(final Snapshot snapshot, final SnapshotInfo snapshotInfo, final Exception e) { + removeSnapshotFromClusterState(snapshot, snapshotInfo, e, null); } /** * Removes record of running snapshot from cluster state and notifies the listener when this action is complete - * - * @param snapshot snapshot - * @param snapshot snapshot info if snapshot was successful - * @param t exception if snapshot failed + * @param snapshot snapshot + * @param failure exception if snapshot failed * @param listener listener to notify when snapshot information is removed from the cluster state */ - private void removeSnapshotFromClusterState(final Snapshot snapshot, final SnapshotInfo snapshotInfo, final Throwable t, + private void removeSnapshotFromClusterState(final Snapshot snapshot, final SnapshotInfo snapshotInfo, final Exception failure, @Nullable ActionListener listener) { clusterService.submitStateUpdateTask("remove snapshot metadata", new ClusterStateUpdateTask() { @Override @@ -918,10 +917,10 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus } @Override - public void onFailure(String source, Throwable t) { - logger.warn("[{}] failed to remove snapshot metadata", t, snapshot); + public void onFailure(String source, Exception e) { + logger.warn("[{}] failed to remove snapshot metadata", e, snapshot); if (listener != null) { - listener.onFailure(t); + listener.onFailure(e); } } @@ -932,9 +931,9 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus if (snapshotInfo != null) { listener.onSnapshotCompletion(snapshot, snapshotInfo); } else { - listener.onSnapshotFailure(snapshot, t); + listener.onSnapshotFailure(snapshot, failure); } - } catch (Throwable t) { + } catch (Exception t) { logger.warn("failed to notify listener [{}]", t, listener); } } @@ -1045,8 +1044,8 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus } @Override - public void onFailure(String source, Throwable t) { - listener.onFailure(t); + public void onFailure(String source, Exception e) { + listener.onFailure(e); } @Override @@ -1064,9 +1063,9 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus } @Override - public void onSnapshotFailure(Snapshot failedSnapshot, Throwable t) { + public void onSnapshotFailure(Snapshot failedSnapshot, Exception e) { if (failedSnapshot.equals(snapshot)) { - logger.trace("deleted snapshot failed - deleting files", t); + logger.trace("deleted snapshot failed - deleting files", e); removeListener(this); deleteSnapshotFromRepository(snapshot, listener); } @@ -1111,7 +1110,7 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus Repository repository = repositoriesService.repository(snapshot.getRepository()); repository.deleteSnapshot(snapshot.getSnapshotId()); listener.onResponse(); - } catch (Throwable t) { + } catch (Exception t) { listener.onFailure(t); } }); @@ -1272,7 +1271,7 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus /** * Called if a snapshot operation couldn't start */ - void onFailure(Throwable t); + void onFailure(Exception e); } /** @@ -1288,14 +1287,14 @@ public class SnapshotsService extends AbstractLifecycleComponent implements Clus /** * Called if delete operation failed */ - void onFailure(Throwable t); + void onFailure(Exception e); } public interface SnapshotCompletionListener { void onSnapshotCompletion(Snapshot snapshot, SnapshotInfo snapshotInfo); - void onSnapshotFailure(Snapshot snapshot, Throwable t); + void onSnapshotFailure(Snapshot snapshot, Exception e); } /** diff --git a/core/src/main/java/org/elasticsearch/tasks/PersistedTaskInfo.java b/core/src/main/java/org/elasticsearch/tasks/PersistedTaskInfo.java index 4e92cf2e874..ceea2774419 100644 --- a/core/src/main/java/org/elasticsearch/tasks/PersistedTaskInfo.java +++ b/core/src/main/java/org/elasticsearch/tasks/PersistedTaskInfo.java @@ -67,7 +67,7 @@ public final class PersistedTaskInfo implements Writeable, ToXContent { /** * Construct a {@linkplain PersistedTaskInfo} for a task that completed with an error. */ - public PersistedTaskInfo(TaskInfo task, Throwable error) throws IOException { + public PersistedTaskInfo(TaskInfo task, Exception error) throws IOException { this(true, task, toXContent(error), null); } @@ -228,12 +228,12 @@ public final class PersistedTaskInfo implements Writeable, ToXContent { } } - private static BytesReference toXContent(Throwable error) throws IOException { + private static BytesReference toXContent(Exception error) throws IOException { try (XContentBuilder builder = XContentFactory.contentBuilder(Requests.INDEX_CONTENT_TYPE)) { builder.startObject(); ElasticsearchException.toXContent(builder, ToXContent.EMPTY_PARAMS, error); builder.endObject(); - return builder.bytes(); + return builder.bytes(); } } } diff --git a/core/src/main/java/org/elasticsearch/tasks/Task.java b/core/src/main/java/org/elasticsearch/tasks/Task.java index 8c0b599e933..93fee29d249 100644 --- a/core/src/main/java/org/elasticsearch/tasks/Task.java +++ b/core/src/main/java/org/elasticsearch/tasks/Task.java @@ -135,7 +135,7 @@ public class Task { public interface Status extends ToXContent, NamedWriteable {} - public PersistedTaskInfo result(DiscoveryNode node, Throwable error) throws IOException { + public PersistedTaskInfo result(DiscoveryNode node, Exception error) throws IOException { return new PersistedTaskInfo(taskInfo(node, true), error); } diff --git a/core/src/main/java/org/elasticsearch/tasks/TaskManager.java b/core/src/main/java/org/elasticsearch/tasks/TaskManager.java index 7a7a71174a6..a6724d16f25 100644 --- a/core/src/main/java/org/elasticsearch/tasks/TaskManager.java +++ b/core/src/main/java/org/elasticsearch/tasks/TaskManager.java @@ -155,7 +155,7 @@ public class TaskManager extends AbstractComponent implements ClusterStateListen /** * Stores the task failure */ - public void persistResult(Task task, Throwable error, ActionListener listener) { + public void persistResult(Task task, Exception error, ActionListener listener) { DiscoveryNode localNode = lastDiscoveryNodes.getLocalNode(); if (localNode == null) { // too early to persist anything, shouldn't really be here - just pass the error along @@ -177,7 +177,7 @@ public class TaskManager extends AbstractComponent implements ClusterStateListen } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { logger.warn("couldn't persist error {}", e, ExceptionsHelper.detailedMessage(error)); listener.onFailure(e); } @@ -211,7 +211,7 @@ public class TaskManager extends AbstractComponent implements ClusterStateListen } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { logger.warn("couldn't persist response {}", e, response); listener.onFailure(e); } diff --git a/core/src/main/java/org/elasticsearch/tasks/TaskPersistenceService.java b/core/src/main/java/org/elasticsearch/tasks/TaskPersistenceService.java index e1a26663e7b..992a7de4b72 100644 --- a/core/src/main/java/org/elasticsearch/tasks/TaskPersistenceService.java +++ b/core/src/main/java/org/elasticsearch/tasks/TaskPersistenceService.java @@ -90,13 +90,14 @@ public class TaskPersistenceService extends AbstractComponent { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) { // we have the index, do it try { doPersist(taskResult, listener); - } catch (Throwable e1) { - listener.onFailure(e1); + } catch (Exception inner) { + inner.addSuppressed(e); + listener.onFailure(inner); } } else { listener.onFailure(e); @@ -115,7 +116,7 @@ public class TaskPersistenceService extends AbstractComponent { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { listener.onFailure(e); } } @@ -142,7 +143,7 @@ public class TaskPersistenceService extends AbstractComponent { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { listener.onFailure(e); } }); diff --git a/core/src/main/java/org/elasticsearch/threadpool/ThreadPool.java b/core/src/main/java/org/elasticsearch/threadpool/ThreadPool.java index c465f98c182..f0519080803 100644 --- a/core/src/main/java/org/elasticsearch/threadpool/ThreadPool.java +++ b/core/src/main/java/org/elasticsearch/threadpool/ThreadPool.java @@ -405,9 +405,9 @@ public class ThreadPool extends AbstractComponent implements Closeable { public void run() { try { runnable.run(); - } catch (Throwable t) { - logger.warn("failed to run {}", t, runnable.toString()); - throw t; + } catch (Exception e) { + logger.warn("failed to run {}", e, runnable.toString()); + throw e; } } diff --git a/core/src/main/java/org/elasticsearch/transport/DelegatingTransportChannel.java b/core/src/main/java/org/elasticsearch/transport/DelegatingTransportChannel.java index f6b178dba8d..af85b438618 100644 --- a/core/src/main/java/org/elasticsearch/transport/DelegatingTransportChannel.java +++ b/core/src/main/java/org/elasticsearch/transport/DelegatingTransportChannel.java @@ -64,8 +64,8 @@ public class DelegatingTransportChannel implements TransportChannel { } @Override - public void sendResponse(Throwable error) throws IOException { - channel.sendResponse(error); + public void sendResponse(Exception exception) throws IOException { + channel.sendResponse(exception); } public TransportChannel getChannel() { diff --git a/core/src/main/java/org/elasticsearch/transport/PlainTransportFuture.java b/core/src/main/java/org/elasticsearch/transport/PlainTransportFuture.java index 350d556536b..3d0e603195b 100644 --- a/core/src/main/java/org/elasticsearch/transport/PlainTransportFuture.java +++ b/core/src/main/java/org/elasticsearch/transport/PlainTransportFuture.java @@ -87,8 +87,8 @@ public class PlainTransportFuture extends BaseFutur try { handler.handleResponse(response); set(response); - } catch (Throwable t) { - handleException(new ResponseHandlerFailureTransportException(t)); + } catch (Exception e) { + handleException(new ResponseHandlerFailureTransportException(e)); } } diff --git a/core/src/main/java/org/elasticsearch/transport/RequestHandlerRegistry.java b/core/src/main/java/org/elasticsearch/transport/RequestHandlerRegistry.java index 9c783c57380..27342af1bdd 100644 --- a/core/src/main/java/org/elasticsearch/transport/RequestHandlerRegistry.java +++ b/core/src/main/java/org/elasticsearch/transport/RequestHandlerRegistry.java @@ -118,9 +118,9 @@ public class RequestHandlerRegistry { } @Override - public void sendResponse(Throwable error) throws IOException { + public void sendResponse(Exception exception) throws IOException { endTask(); - super.sendResponse(error); + super.sendResponse(exception); } private void endTask() { diff --git a/core/src/main/java/org/elasticsearch/transport/ResponseHandlerFailureTransportException.java b/core/src/main/java/org/elasticsearch/transport/ResponseHandlerFailureTransportException.java index 375fbb8bfcb..8597edb8761 100644 --- a/core/src/main/java/org/elasticsearch/transport/ResponseHandlerFailureTransportException.java +++ b/core/src/main/java/org/elasticsearch/transport/ResponseHandlerFailureTransportException.java @@ -25,8 +25,6 @@ import java.io.IOException; /** * A failure to handle the response of a transaction action. - * - * */ public class ResponseHandlerFailureTransportException extends TransportException { diff --git a/core/src/main/java/org/elasticsearch/transport/TcpTransport.java b/core/src/main/java/org/elasticsearch/transport/TcpTransport.java index cd8063969d4..6814e7ad5f1 100644 --- a/core/src/main/java/org/elasticsearch/transport/TcpTransport.java +++ b/core/src/main/java/org/elasticsearch/transport/TcpTransport.java @@ -103,8 +103,6 @@ import static org.elasticsearch.common.transport.NetworkExceptionHelper.isCloseC import static org.elasticsearch.common.transport.NetworkExceptionHelper.isConnectException; import static org.elasticsearch.common.util.concurrent.ConcurrentCollections.newConcurrentMap; -/** - */ public abstract class TcpTransport extends AbstractLifecycleComponent implements Transport { public static final String HTTP_SERVER_WORKER_THREAD_NAME_PREFIX = "http_server_worker"; @@ -257,12 +255,12 @@ public abstract class TcpTransport extends AbstractLifecycleComponent i for (Channel channel : channels.allChannels) { try { sendMessage(channel, pingHeader, successfulPings::inc, false); - } catch (Throwable t) { + } catch (Exception e) { if (isOpen(channel)) { - logger.debug("[{}] failed to send ping transport message", t, node); + logger.debug("[{}] failed to send ping transport message", e, node); failedPings.inc(); } else { - logger.trace("[{}] failed to send ping transport message (channel closed)", t, node); + logger.trace("[{}] failed to send ping transport message (channel closed)", e, node); } } } @@ -283,11 +281,11 @@ public abstract class TcpTransport extends AbstractLifecycleComponent i } @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { if (lifecycle.stoppedOrClosed()) { - logger.trace("failed to send ping transport message", t); + logger.trace("failed to send ping transport message", e); } else { - logger.warn("failed to send ping transport message", t); + logger.warn("failed to send ping transport message", e); } } } @@ -393,7 +391,7 @@ public abstract class TcpTransport extends AbstractLifecycleComponent i } else { try { nodeChannels = connectToChannels(node); - } catch (Throwable e) { + } catch (Exception e) { logger.trace("failed to connect to [{}], cleaning dangling connections", e, node); throw e; } @@ -445,7 +443,7 @@ public abstract class TcpTransport extends AbstractLifecycleComponent i /** * Disconnects from a node if a channel is found as part of that nodes channels. */ - protected final void disconnectFromNodeChannel(final Channel channel, final Throwable failure) { + protected final void disconnectFromNodeChannel(final Channel channel, final Exception failure) { threadPool.generic().execute(() -> { try { closeChannels(Collections.singletonList(channel)); @@ -769,8 +767,8 @@ public abstract class TcpTransport extends AbstractLifecycleComponent i for (Map.Entry> entry : serverChannels.entrySet()) { try { closeChannels(entry.getValue()); - } catch (Throwable t) { - logger.debug("Error closing serverChannel for profile [{}]", t, entry.getKey()); + } catch (Exception e) { + logger.debug("Error closing serverChannel for profile [{}]", e, entry.getKey()); } } try { @@ -797,7 +795,7 @@ public abstract class TcpTransport extends AbstractLifecycleComponent i } } - protected void onException(Channel channel, Throwable e) { + protected void onException(Channel channel, Exception e) { if (!lifecycle.started()) { // ignore return; @@ -937,7 +935,7 @@ public abstract class TcpTransport extends AbstractLifecycleComponent i * @param requestId the request ID this response replies to * @param action the action this response replies to */ - public void sendErrorResponse(Version nodeVersion, Channel channel, final Throwable error, final long requestId, + public void sendErrorResponse(Version nodeVersion, Channel channel, final Exception error, final long requestId, final String action) throws IOException { BytesStreamOutput stream = new BytesStreamOutput(); stream.setVersion(nodeVersion); @@ -964,7 +962,7 @@ public abstract class TcpTransport extends AbstractLifecycleComponent i /** * Sends the response to the given channel. This method should be used to send {@link TransportResponse} objects back to the caller. * - * @see #sendErrorResponse(Version, Object, Throwable, long, String) for sending back errors to the caller + * @see #sendErrorResponse(Version, Object, Exception, long, String) for sending back errors to the caller */ public void sendResponse(Version nodeVersion, Channel channel, final TransportResponse response, final long requestId, final String action, TransportResponseOptions options) throws IOException { @@ -1216,15 +1214,15 @@ public abstract class TcpTransport extends AbstractLifecycleComponent i response.remoteAddress(new InetSocketTransportAddress(remoteAddress)); try { response.readFrom(stream); - } catch (Throwable e) { + } catch (Exception e) { handleException(handler, new TransportSerializationException( "Failed to deserialize response of type [" + response.getClass().getName() + "]", e)); return; } threadPool.executor(handler.executor()).execute(new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - handleException(handler, new ResponseHandlerFailureTransportException(t)); + public void onFailure(Exception e) { + handleException(handler, new ResponseHandlerFailureTransportException(e)); } @Override @@ -1238,10 +1236,10 @@ public abstract class TcpTransport extends AbstractLifecycleComponent i * Executed for a received response error */ private void handlerResponseError(StreamInput stream, final TransportResponseHandler handler) { - Throwable error; + Exception error; try { - error = stream.readThrowable(); - } catch (Throwable e) { + error = stream.readException(); + } catch (Exception e) { error = new TransportSerializationException("Failed to deserialize exception response from stream", e); } handleException(handler, error); @@ -1255,7 +1253,7 @@ public abstract class TcpTransport extends AbstractLifecycleComponent i threadPool.executor(handler.executor()).execute(() -> { try { handler.handleException(rtx); - } catch (Throwable e) { + } catch (Exception e) { logger.error("failed to handle exception response [{}]", e, handler); } }); @@ -1284,16 +1282,16 @@ public abstract class TcpTransport extends AbstractLifecycleComponent i // in case we throw an exception, i.e. when the limit is hit, we don't want to verify validateRequest(stream, requestId, action); threadPool.executor(reg.getExecutor()).execute(new RequestHandler(reg, request, transportChannel)); - } catch (Throwable e) { + } catch (Exception e) { // the circuit breaker tripped if (transportChannel == null) { transportChannel = new TcpTransportChannel<>(this, channel, transportName, action, requestId, version, profileName, 0); } try { transportChannel.sendResponse(e); - } catch (IOException e1) { - logger.warn("Failed to send error message back to client for action [{}]", e, action); - logger.warn("Actual Exception", e1); + } catch (IOException inner) { + inner.addSuppressed(e); + logger.warn("Failed to send error message back to client for action [{}]", inner, action); } } return action; @@ -1332,14 +1330,14 @@ public abstract class TcpTransport extends AbstractLifecycleComponent i } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { if (lifecycleState() == Lifecycle.State.STARTED) { // we can only send a response transport is started.... try { transportChannel.sendResponse(e); - } catch (Throwable e1) { - logger.warn("Failed to send error message back to client for action [{}]", e1, reg.getAction()); - logger.warn("Actual Exception", e); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.warn("Failed to send error message back to client for action [{}]", inner, reg.getAction()); } } } diff --git a/core/src/main/java/org/elasticsearch/transport/TcpTransportChannel.java b/core/src/main/java/org/elasticsearch/transport/TcpTransportChannel.java index 74bdad48746..dc8f26f1864 100644 --- a/core/src/main/java/org/elasticsearch/transport/TcpTransportChannel.java +++ b/core/src/main/java/org/elasticsearch/transport/TcpTransportChannel.java @@ -72,9 +72,9 @@ public final class TcpTransportChannel implements TransportChannel { } @Override - public void sendResponse(Throwable error) throws IOException { + public void sendResponse(Exception exception) throws IOException { release(); - transport.sendErrorResponse(version, channel, error, requestId, action); + transport.sendErrorResponse(version, channel, exception, requestId, action); } private void release() { diff --git a/core/src/main/java/org/elasticsearch/transport/TransportChannel.java b/core/src/main/java/org/elasticsearch/transport/TransportChannel.java index 53fd4ebe91e..d9fbcad30e0 100644 --- a/core/src/main/java/org/elasticsearch/transport/TransportChannel.java +++ b/core/src/main/java/org/elasticsearch/transport/TransportChannel.java @@ -38,5 +38,5 @@ public interface TransportChannel { void sendResponse(TransportResponse response, TransportResponseOptions options) throws IOException; - void sendResponse(Throwable error) throws IOException; + void sendResponse(Exception exception) throws IOException; } diff --git a/core/src/main/java/org/elasticsearch/transport/TransportService.java b/core/src/main/java/org/elasticsearch/transport/TransportService.java index 5a62c8bad31..765bb988777 100644 --- a/core/src/main/java/org/elasticsearch/transport/TransportService.java +++ b/core/src/main/java/org/elasticsearch/transport/TransportService.java @@ -64,7 +64,6 @@ import java.util.function.Supplier; import static java.util.Collections.emptyList; import static org.elasticsearch.common.settings.Setting.listSetting; -import static org.elasticsearch.common.settings.Settings.Builder.EMPTY_SETTINGS; /** * @@ -204,13 +203,13 @@ public class TransportService extends AbstractLifecycleComponent { // want handlers to worry about stack overflows threadPool.generic().execute(new AbstractRunnable() { @Override - public void onRejection(Throwable t) { + public void onRejection(Exception e) { // if we get rejected during node shutdown we don't wanna bubble it up - logger.debug("failed to notify response handler on rejection, action: {}", t, holderToNotify.action()); + logger.debug("failed to notify response handler on rejection, action: {}", e, holderToNotify.action()); } @Override - public void onFailure(Throwable t) { - logger.warn("failed to notify response handler on exception, action: {}", t, holderToNotify.action()); + public void onFailure(Exception e) { + logger.warn("failed to notify response handler on exception, action: {}", e, holderToNotify.action()); } @Override public void doRun() { @@ -470,7 +469,7 @@ public class TransportService extends AbstractLifecycleComponent { } else { transport.sendRequest(node, requestId, action, request, options); } - } catch (final Throwable e) { + } catch (final Exception e) { // usually happen either because we failed to connect to the node // or because we failed serializing the message final RequestHolder holderToNotify = clientHandlers.remove(requestId); @@ -482,13 +481,13 @@ public class TransportService extends AbstractLifecycleComponent { final SendRequestTransportException sendRequestException = new SendRequestTransportException(node, action, e); threadPool.executor(ThreadPool.Names.GENERIC).execute(new AbstractRunnable() { @Override - public void onRejection(Throwable t) { + public void onRejection(Exception e) { // if we get rejected during node shutdown we don't wanna bubble it up - logger.debug("failed to notify response handler on rejection, action: {}", t, holderToNotify.action()); + logger.debug("failed to notify response handler on rejection, action: {}", e, holderToNotify.action()); } @Override - public void onFailure(Throwable t) { - logger.warn("failed to notify response handler on exception, action: {}", t, holderToNotify.action()); + public void onFailure(Exception e) { + logger.warn("failed to notify response handler on exception, action: {}", e, holderToNotify.action()); } @Override protected void doRun() throws Exception { @@ -524,23 +523,23 @@ public class TransportService extends AbstractLifecycleComponent { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { try { channel.sendResponse(e); - } catch (Throwable e1) { - logger.warn("failed to notify channel of error message for action [{}]", e1, action); - logger.warn("actual exception", e); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.warn("failed to notify channel of error message for action [{}]", inner, action); } } }); } - } catch (Throwable e) { + } catch (Exception e) { try { channel.sendResponse(e); - } catch (Throwable e1) { - logger.warn("failed to notify channel of error message for action [{}]", e1, action); - logger.warn("actual exception", e1); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.warn("failed to notify channel of error message for action [{}]", inner, action); } } @@ -655,14 +654,14 @@ public class TransportService extends AbstractLifecycleComponent { } @Override - public void onResponseSent(long requestId, String action, Throwable t) { + public void onResponseSent(long requestId, String action, Exception e) { if (traceEnabled() && shouldTraceAction(action)) { - traceResponseSent(requestId, action, t); + traceResponseSent(requestId, action, e); } } - protected void traceResponseSent(long requestId, String action, Throwable t) { - tracerLog.trace("[{}][{}] sent error response", t, requestId, action); + protected void traceResponseSent(long requestId, String action, Exception e) { + tracerLog.trace("[{}][{}] sent error response", e, requestId, action); } @Override @@ -998,17 +997,17 @@ public class TransportService extends AbstractLifecycleComponent { protected void processResponse(TransportResponseHandler handler, TransportResponse response) { try { handler.handleResponse(response); - } catch (Throwable e) { + } catch (Exception e) { processException(handler, wrapInRemote(new ResponseHandlerFailureTransportException(e))); } } @Override - public void sendResponse(Throwable error) throws IOException { + public void sendResponse(Exception exception) throws IOException { final TransportResponseHandler handler = adapter.onResponseReceived(requestId); // ignore if its null, the adapter logs it if (handler != null) { - final RemoteTransportException rtx = wrapInRemote(error); + final RemoteTransportException rtx = wrapInRemote(exception); final String executor = handler.executor(); if (ThreadPool.Names.SAME.equals(executor)) { processException(handler, rtx); @@ -1024,17 +1023,17 @@ public class TransportService extends AbstractLifecycleComponent { } } - protected RemoteTransportException wrapInRemote(Throwable t) { - if (t instanceof RemoteTransportException) { - return (RemoteTransportException) t; + protected RemoteTransportException wrapInRemote(Exception e) { + if (e instanceof RemoteTransportException) { + return (RemoteTransportException) e; } - return new RemoteTransportException(localNode.getName(), localNode.getAddress(), action, t); + return new RemoteTransportException(localNode.getName(), localNode.getAddress(), action, e); } protected void processException(final TransportResponseHandler handler, final RemoteTransportException rtx) { try { handler.handleException(rtx); - } catch (Throwable e) { + } catch (Exception e) { logger.error("failed to handle exception for action [{}], handler [{}]", e, action, handler); } } diff --git a/core/src/main/java/org/elasticsearch/transport/TransportServiceAdapter.java b/core/src/main/java/org/elasticsearch/transport/TransportServiceAdapter.java index 382a4192d1c..5a1b9e9b349 100644 --- a/core/src/main/java/org/elasticsearch/transport/TransportServiceAdapter.java +++ b/core/src/main/java/org/elasticsearch/transport/TransportServiceAdapter.java @@ -37,7 +37,7 @@ public interface TransportServiceAdapter { void onResponseSent(long requestId, String action, TransportResponse response, TransportResponseOptions options); /** called by the {@link Transport} implementation after an exception was sent as a response to an incoming request */ - void onResponseSent(long requestId, String action, Throwable t); + void onResponseSent(long requestId, String action, Exception e); /** * called by the {@link Transport} implementation when a response or an exception has been received for a previously diff --git a/core/src/main/java/org/elasticsearch/transport/local/LocalTransport.java b/core/src/main/java/org/elasticsearch/transport/local/LocalTransport.java index 930e3951098..f6519cbeeba 100644 --- a/core/src/main/java/org/elasticsearch/transport/local/LocalTransport.java +++ b/core/src/main/java/org/elasticsearch/transport/local/LocalTransport.java @@ -274,7 +274,7 @@ public class LocalTransport extends AbstractLifecycleComponent implements Transp } } } - } catch (Throwable e) { + } catch (Exception e) { if (sendRequestId != null) { TransportResponseHandler handler = sourceTransport.transportServiceAdapter.onResponseReceived(sendRequestId); if (handler != null) { @@ -329,25 +329,25 @@ public class LocalTransport extends AbstractLifecycleComponent implements Transp } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { if (lifecycleState() == Lifecycle.State.STARTED) { // we can only send a response transport is started.... try { transportChannel.sendResponse(e); - } catch (Throwable e1) { - logger.warn("Failed to send error message back to client for action [{}]", e1, action); - logger.warn("Actual Exception", e); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.warn("Failed to send error message back to client for action [{}]", inner, action); } } } }); } - } catch (Throwable e) { + } catch (Exception e) { try { transportChannel.sendResponse(e); - } catch (Throwable e1) { - logger.warn("Failed to send error message back to client for action [{}]", e, action); - logger.warn("Actual Exception", e1); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.warn("Failed to send error message back to client for action [{}]", inner, action); } } @@ -359,7 +359,7 @@ public class LocalTransport extends AbstractLifecycleComponent implements Transp response.remoteAddress(sourceTransport.boundAddress.publishAddress()); try { response.readFrom(buffer); - } catch (Throwable e) { + } catch (Exception e) { handleException(handler, new TransportSerializationException( "Failed to deserialize response of type [" + response.getClass().getName() + "]", e)); return; @@ -371,31 +371,31 @@ public class LocalTransport extends AbstractLifecycleComponent implements Transp threadPool.executor(handler.executor()).execute(() -> { try { handler.handleResponse(response); - } catch (Throwable e) { + } catch (Exception e) { handleException(handler, new ResponseHandlerFailureTransportException(e)); } }); } private void handleResponseError(StreamInput buffer, final TransportResponseHandler handler) { - Throwable error; + Exception exception; try { - error = buffer.readThrowable(); - } catch (Throwable e) { - error = new TransportSerializationException("Failed to deserialize exception response from stream", e); + exception = buffer.readException(); + } catch (Exception e) { + exception = new TransportSerializationException("Failed to deserialize exception response from stream", e); } - handleException(handler, error); + handleException(handler, exception); } - private void handleException(final TransportResponseHandler handler, Throwable error) { - if (!(error instanceof RemoteTransportException)) { - error = new RemoteTransportException("None remote transport exception", null, null, error); + private void handleException(final TransportResponseHandler handler, Exception exception) { + if (!(exception instanceof RemoteTransportException)) { + exception = new RemoteTransportException("None remote transport exception", null, null, exception); } - final RemoteTransportException rtx = (RemoteTransportException) error; + final RemoteTransportException rtx = (RemoteTransportException) exception; try { handler.handleException(rtx); - } catch (Throwable t) { - logger.error("failed to handle exception response [{}]", t, handler); + } catch (Exception e) { + logger.error("failed to handle exception response [{}]", e, handler); } } diff --git a/core/src/main/java/org/elasticsearch/transport/local/LocalTransportChannel.java b/core/src/main/java/org/elasticsearch/transport/local/LocalTransportChannel.java index fc3b4a3b32f..129d35c8ebf 100644 --- a/core/src/main/java/org/elasticsearch/transport/local/LocalTransportChannel.java +++ b/core/src/main/java/org/elasticsearch/transport/local/LocalTransportChannel.java @@ -91,14 +91,14 @@ public class LocalTransportChannel implements TransportChannel { } @Override - public void sendResponse(Throwable error) throws IOException { + public void sendResponse(Exception exception) throws IOException { BytesStreamOutput stream = new BytesStreamOutput(); writeResponseExceptionHeader(stream); RemoteTransportException tx = new RemoteTransportException(targetTransport.nodeName(), - targetTransport.boundAddress().boundAddresses()[0], action, error); + targetTransport.boundAddress().boundAddresses()[0], action, exception); stream.writeThrowable(tx); sendResponseData(BytesReference.toBytes(stream.bytes())); - sourceTransportServiceAdapter.onResponseSent(requestId, action, error); + sourceTransportServiceAdapter.onResponseSent(requestId, action, exception); } private void sendResponseData(byte[] data) { diff --git a/core/src/main/java/org/elasticsearch/transport/netty/NettyTransport.java b/core/src/main/java/org/elasticsearch/transport/netty/NettyTransport.java index d591a75d051..804d84e8374 100644 --- a/core/src/main/java/org/elasticsearch/transport/netty/NettyTransport.java +++ b/core/src/main/java/org/elasticsearch/transport/netty/NettyTransport.java @@ -19,6 +19,7 @@ package org.elasticsearch.transport.netty; +import org.elasticsearch.ElasticsearchException; import org.elasticsearch.Version; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.Booleans; @@ -321,7 +322,10 @@ public class NettyTransport extends TcpTransport { } protected final void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { - onException(ctx.getChannel(), e.getCause()); + onException( + ctx.getChannel(), + e.getCause() == null || e.getCause() instanceof Exception ? + (Exception)e.getCause() : new ElasticsearchException(e.getCause())); } @Override @@ -602,8 +606,8 @@ public class NettyTransport extends TcpTransport { ServerBootstrap serverBootstrap = entry.getValue(); try { serverBootstrap.releaseExternalResources(); - } catch (Throwable t) { - logger.debug("Error closing serverBootstrap for profile [{}]", t, name); + } catch (Exception e) { + logger.debug("Error closing serverBootstrap for profile [{}]", e, name); } } serverBootstraps.clear(); diff --git a/core/src/main/java/org/elasticsearch/tribe/TribeService.java b/core/src/main/java/org/elasticsearch/tribe/TribeService.java index 5c7d6d93f7c..43e36f2993b 100644 --- a/core/src/main/java/org/elasticsearch/tribe/TribeService.java +++ b/core/src/main/java/org/elasticsearch/tribe/TribeService.java @@ -255,13 +255,14 @@ public class TribeService extends AbstractLifecycleComponent { try { node.injector().getInstance(ClusterService.class).add(new TribeClusterStateListener(node)); node.start(); - } catch (Throwable e) { + } catch (Exception e) { // calling close is safe for non started nodes, we can just iterate over all for (Node otherNode : nodes) { try { otherNode.close(); - } catch (Throwable t) { - logger.warn("failed to close node {} on failed start", t, otherNode); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.warn("failed to close node {} on failed start", inner, otherNode); } } if (e instanceof RuntimeException) { @@ -282,8 +283,8 @@ public class TribeService extends AbstractLifecycleComponent { for (Node node : nodes) { try { node.close(); - } catch (Throwable t) { - logger.warn("failed to close node {}", t, node); + } catch (Exception e) { + logger.warn("failed to close node {}", e, node); } } } @@ -307,7 +308,7 @@ public class TribeService extends AbstractLifecycleComponent { event, ClusterStateTaskConfig.build(Priority.NORMAL), executor, - (source, t) -> logger.warn("failed to process [{}]", t, source)); + (source, e) -> logger.warn("failed to process [{}]", e, source)); } } @@ -333,8 +334,8 @@ public class TribeService extends AbstractLifecycleComponent { // we only need to apply the latest cluster state update accumulator = applyUpdate(accumulator, tasks.get(tasks.size() - 1)); builder.successes(tasks); - } catch (Throwable t) { - builder.failures(tasks, t); + } catch (Exception e) { + builder.failures(tasks, e); } return builder.build(accumulator); diff --git a/core/src/main/java/org/elasticsearch/watcher/FileWatcher.java b/core/src/main/java/org/elasticsearch/watcher/FileWatcher.java index 2b498fed130..a6b0bdd8401 100644 --- a/core/src/main/java/org/elasticsearch/watcher/FileWatcher.java +++ b/core/src/main/java/org/elasticsearch/watcher/FileWatcher.java @@ -257,8 +257,8 @@ public class FileWatcher extends AbstractResourceWatcher { } else { listener.onFileCreated(file); } - } catch (Throwable t) { - logger.warn("cannot notify file changes listener", t); + } catch (Exception e) { + logger.warn("cannot notify file changes listener", e); } } } @@ -267,8 +267,8 @@ public class FileWatcher extends AbstractResourceWatcher { for (FileChangesListener listener : listeners()) { try { listener.onFileDeleted(file); - } catch (Throwable t) { - logger.warn("cannot notify file changes listener", t); + } catch (Exception e) { + logger.warn("cannot notify file changes listener", e); } } } @@ -277,8 +277,8 @@ public class FileWatcher extends AbstractResourceWatcher { for (FileChangesListener listener : listeners()) { try { listener.onFileChanged(file); - } catch (Throwable t) { - logger.warn("cannot notify file changes listener", t); + } catch (Exception e) { + logger.warn("cannot notify file changes listener", e); } } @@ -292,8 +292,8 @@ public class FileWatcher extends AbstractResourceWatcher { } else { listener.onDirectoryCreated(file); } - } catch (Throwable t) { - logger.warn("cannot notify file changes listener", t); + } catch (Exception e) { + logger.warn("cannot notify file changes listener", e); } } children = listChildren(initial); @@ -307,8 +307,8 @@ public class FileWatcher extends AbstractResourceWatcher { for (FileChangesListener listener : listeners()) { try { listener.onDirectoryDeleted(file); - } catch (Throwable t) { - logger.warn("cannot notify file changes listener", t); + } catch (Exception e) { + logger.warn("cannot notify file changes listener", e); } } } diff --git a/core/src/test/java/org/elasticsearch/ESExceptionTests.java b/core/src/test/java/org/elasticsearch/ESExceptionTests.java index d27790beed1..5e761a97c63 100644 --- a/core/src/test/java/org/elasticsearch/ESExceptionTests.java +++ b/core/src/test/java/org/elasticsearch/ESExceptionTests.java @@ -57,6 +57,14 @@ import static org.hamcrest.Matchers.equalTo; public class ESExceptionTests extends ESTestCase { private static final ToXContent.Params PARAMS = ToXContent.EMPTY_PARAMS; + private class UnknownException extends Exception { + + UnknownException(final String message, final Exception cause) { + super(message, cause); + } + + } + public void testStatus() { ElasticsearchException exception = new ElasticsearchException("test"); assertThat(exception.status(), equalTo(RestStatus.INTERNAL_SERVER_ERROR)); @@ -296,7 +304,7 @@ public class ESExceptionTests extends ESTestCase { out.writeThrowable(ex); StreamInput in = out.bytes().streamInput(); - ParsingException e = in.readThrowable(); + ParsingException e = in.readException(); assertEquals(ex.getIndex(), e.getIndex()); assertEquals(ex.getMessage(), e.getMessage()); assertEquals(ex.getLineNumber(), e.getLineNumber()); @@ -305,23 +313,27 @@ public class ESExceptionTests extends ESTestCase { public void testSerializeUnknownException() throws IOException { BytesStreamOutput out = new BytesStreamOutput(); - ParsingException ParsingException = new ParsingException(1, 2, "foobar", null); - Throwable ex = new Throwable("eggplant", ParsingException); + ParsingException parsingException = new ParsingException(1, 2, "foobar", null); + final Exception ex = new UnknownException("eggplant", parsingException); out.writeThrowable(ex); StreamInput in = out.bytes().streamInput(); - Throwable throwable = in.readThrowable(); - assertEquals("throwable: eggplant", throwable.getMessage()); + Throwable throwable = in.readException(); + assertEquals("unknown_exception: eggplant", throwable.getMessage()); assertTrue(throwable instanceof ElasticsearchException); ParsingException e = (ParsingException)throwable.getCause(); - assertEquals(ParsingException.getIndex(), e.getIndex()); - assertEquals(ParsingException.getMessage(), e.getMessage()); - assertEquals(ParsingException.getLineNumber(), e.getLineNumber()); - assertEquals(ParsingException.getColumnNumber(), e.getColumnNumber()); + assertEquals(parsingException.getIndex(), e.getIndex()); + assertEquals(parsingException.getMessage(), e.getMessage()); + assertEquals(parsingException.getLineNumber(), e.getLineNumber()); + assertEquals(parsingException.getColumnNumber(), e.getColumnNumber()); } public void testWriteThrowable() throws IOException { - Throwable[] causes = new Throwable[] { + + final QueryShardException queryShardException = new QueryShardException(new Index("foo", "_na_"), "foobar", null); + final UnknownException unknownException = new UnknownException("this exception is unknown", queryShardException); + + final Exception[] causes = new Exception[]{ new IllegalStateException("foobar"), new IllegalArgumentException("alalaal"), new NullPointerException("boom"), @@ -336,32 +348,30 @@ public class ESExceptionTests extends ESTestCase { new StringIndexOutOfBoundsException("booom"), new FileNotFoundException("booom"), new NoSuchFileException("booom"), - new AssertionError("booom", new NullPointerException()), - new OutOfMemoryError("no memory left"), new AlreadyClosedException("closed!!", new NullPointerException()), new LockObtainFailedException("can't lock directory", new NullPointerException()), - new Throwable("this exception is unknown", new QueryShardException(new Index("foo", "_na_"), "foobar", null) ), // somethin unknown - }; - for (Throwable t : causes) { + unknownException}; + for (final Exception cause : causes) { BytesStreamOutput out = new BytesStreamOutput(); - ElasticsearchException ex = new ElasticsearchException("topLevel", t); + ElasticsearchException ex = new ElasticsearchException("topLevel", cause); out.writeThrowable(ex); StreamInput in = out.bytes().streamInput(); - ElasticsearchException e = in.readThrowable(); + ElasticsearchException e = in.readException(); assertEquals(e.getMessage(), ex.getMessage()); assertTrue("Expected: " + e.getCause().getMessage() + " to contain: " + ex.getCause().getClass().getName() + " but it didn't", e.getCause().getMessage().contains(ex.getCause().getMessage())); - if (ex.getCause().getClass() != Throwable.class) { // throwable is not directly mapped + if (ex.getCause().getClass() != UnknownException.class) { // unknown exception is not directly mapped assertEquals(e.getCause().getClass(), ex.getCause().getClass()); } else { assertEquals(e.getCause().getClass(), NotSerializableExceptionWrapper.class); } assertArrayEquals(e.getStackTrace(), ex.getStackTrace()); assertTrue(e.getStackTrace().length > 1); - ElasticsearchAssertions.assertVersionSerializable(VersionUtils.randomVersion(random()), t); + ElasticsearchAssertions.assertVersionSerializable(VersionUtils.randomVersion(random()), cause); ElasticsearchAssertions.assertVersionSerializable(VersionUtils.randomVersion(random()), ex); ElasticsearchAssertions.assertVersionSerializable(VersionUtils.randomVersion(random()), e); } } + } diff --git a/core/src/test/java/org/elasticsearch/ExceptionSerializationTests.java b/core/src/test/java/org/elasticsearch/ExceptionSerializationTests.java index 6a65b1d1695..17ff2047238 100644 --- a/core/src/test/java/org/elasticsearch/ExceptionSerializationTests.java +++ b/core/src/test/java/org/elasticsearch/ExceptionSerializationTests.java @@ -219,12 +219,12 @@ public class ExceptionSerializationTests extends ESTestCase { } } - private T serialize(T exception) throws IOException { + private T serialize(T exception) throws IOException { ElasticsearchAssertions.assertVersionSerializable(VersionUtils.randomVersion(random()), exception); BytesStreamOutput out = new BytesStreamOutput(); out.writeThrowable(exception); StreamInput in = out.bytes().streamInput(); - return in.readThrowable(); + return in.readException(); } public void testIllegalShardRoutingStateException() throws IOException { @@ -546,12 +546,20 @@ public class ExceptionSerializationTests extends ESTestCase { ex = serialize(new NotSerializableExceptionWrapper(new IllegalArgumentException("nono!"))); assertEquals("{\"type\":\"illegal_argument_exception\",\"reason\":\"illegal_argument_exception: nono!\"}", toXContent(ex)); - Throwable[] unknowns = new Throwable[]{ + class UnknownException extends Exception { + + public UnknownException(final String message) { + super(message); + } + + } + + Exception[] unknowns = new Exception[]{ new Exception("foobar"), new ClassCastException("boom boom boom"), - new UnsatisfiedLinkError("booom") + new UnknownException("boom") }; - for (Throwable t : unknowns) { + for (Exception t : unknowns) { if (randomBoolean()) { t.addSuppressed(new UnsatisfiedLinkError("suppressed")); t.addSuppressed(new NullPointerException()); diff --git a/core/src/test/java/org/elasticsearch/action/ListenerActionIT.java b/core/src/test/java/org/elasticsearch/action/ListenerActionIT.java index 3976f665df9..93389f898e9 100644 --- a/core/src/test/java/org/elasticsearch/action/ListenerActionIT.java +++ b/core/src/test/java/org/elasticsearch/action/ListenerActionIT.java @@ -51,7 +51,7 @@ public class ListenerActionIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { threadName.set(Thread.currentThread().getName()); failure.set(e); latch.countDown(); diff --git a/core/src/test/java/org/elasticsearch/action/RejectionActionIT.java b/core/src/test/java/org/elasticsearch/action/RejectionActionIT.java index 6f100170250..6745906488a 100644 --- a/core/src/test/java/org/elasticsearch/action/RejectionActionIT.java +++ b/core/src/test/java/org/elasticsearch/action/RejectionActionIT.java @@ -75,7 +75,7 @@ public class RejectionActionIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { responses.add(e); latch.countDown(); } @@ -92,7 +92,7 @@ public class RejectionActionIT extends ESIntegTestCase { assertTrue("got unexpected reason..." + failure.reason(), failure.reason().toLowerCase(Locale.ENGLISH).contains("rejected")); } } else { - Throwable t = (Throwable) response; + Exception t = (Exception) response; Throwable unwrap = ExceptionsHelper.unwrapCause(t); if (unwrap instanceof SearchPhaseExecutionException) { SearchPhaseExecutionException e = (SearchPhaseExecutionException) unwrap; diff --git a/core/src/test/java/org/elasticsearch/action/admin/HotThreadsIT.java b/core/src/test/java/org/elasticsearch/action/admin/HotThreadsIT.java index 480c103df81..5d512538821 100644 --- a/core/src/test/java/org/elasticsearch/action/admin/HotThreadsIT.java +++ b/core/src/test/java/org/elasticsearch/action/admin/HotThreadsIT.java @@ -100,7 +100,7 @@ public class HotThreadsIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { logger.error("FAILED", e); hasErrors.set(true); latch.countDown(); diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/CancellableTasksTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/CancellableTasksTests.java index 594028f4e6f..9027b3d372e 100644 --- a/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/CancellableTasksTests.java +++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/CancellableTasksTests.java @@ -230,7 +230,7 @@ public class CancellableTasksTests extends TaskManagerTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { throwableReference.set(e); responseLatch.countDown(); } @@ -308,7 +308,7 @@ public class CancellableTasksTests extends TaskManagerTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { throwableReference.set(e); responseLatch.countDown(); } diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TasksIT.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TasksIT.java index 6f8e3fda156..f9045b58413 100644 --- a/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TasksIT.java +++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TasksIT.java @@ -738,12 +738,12 @@ public class TasksIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { throw new RuntimeException(e); } }); b.await(); - + // Now we can find it! GetTaskResponse response = expectFinishedTask(new TaskId("fake:1")); assertEquals("test", response.getTask().getTask().getAction()); diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java index 56756ad9fdb..2c78786ab04 100644 --- a/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java +++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java @@ -338,7 +338,7 @@ public class TransportTasksActionTests extends TaskManagerTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { logger.warn("Couldn't get list of tasks", e); responseLatch.countDown(); } @@ -526,7 +526,7 @@ public class TransportTasksActionTests extends TaskManagerTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { responseLatch.countDown(); } }); diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteTests.java index dac878eefec..657fec558b8 100644 --- a/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteTests.java +++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteTests.java @@ -94,7 +94,7 @@ public class ClusterRerouteTests extends ESAllocationTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { } }; diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/create/CreateIndexIT.java b/core/src/test/java/org/elasticsearch/action/admin/indices/create/CreateIndexIT.java index 3e7323dceeb..428e859e342 100644 --- a/core/src/test/java/org/elasticsearch/action/admin/indices/create/CreateIndexIT.java +++ b/core/src/test/java/org/elasticsearch/action/admin/indices/create/CreateIndexIT.java @@ -41,14 +41,11 @@ import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.index.mapper.MapperParsingException; import org.elasticsearch.index.query.RangeQueryBuilder; import org.elasticsearch.index.query.TermsQueryBuilder; -import org.elasticsearch.node.service.NodeService; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; -import org.junit.Ignore; import java.util.HashMap; -import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; @@ -232,7 +229,7 @@ public class CreateIndexIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { throw new RuntimeException(e); } } diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/template/put/MetaDataIndexTemplateServiceTests.java b/core/src/test/java/org/elasticsearch/action/admin/indices/template/put/MetaDataIndexTemplateServiceTests.java index d62fe30f6fa..58784fdb7df 100644 --- a/core/src/test/java/org/elasticsearch/action/admin/indices/template/put/MetaDataIndexTemplateServiceTests.java +++ b/core/src/test/java/org/elasticsearch/action/admin/indices/template/put/MetaDataIndexTemplateServiceTests.java @@ -19,7 +19,6 @@ package org.elasticsearch.action.admin.indices.template.put; -import org.elasticsearch.Version; import org.elasticsearch.action.admin.indices.alias.Alias; import org.elasticsearch.cluster.metadata.AliasValidator; import org.elasticsearch.cluster.metadata.IndexMetaData; @@ -172,8 +171,8 @@ public class MetaDataIndexTemplateServiceTests extends ESSingleNodeTestCase { } @Override - public void onFailure(Throwable t) { - throwables.add(t); + public void onFailure(Exception e) { + throwables.add(e); } }); return throwables; @@ -205,8 +204,8 @@ public class MetaDataIndexTemplateServiceTests extends ESSingleNodeTestCase { } @Override - public void onFailure(Throwable t) { - throwables.add(t); + public void onFailure(Exception e) { + throwables.add(e); latch.countDown(); } }); diff --git a/core/src/test/java/org/elasticsearch/action/bulk/RetryTests.java b/core/src/test/java/org/elasticsearch/action/bulk/RetryTests.java index 6d9987394f9..4fa640b3adc 100644 --- a/core/src/test/java/org/elasticsearch/action/bulk/RetryTests.java +++ b/core/src/test/java/org/elasticsearch/action/bulk/RetryTests.java @@ -149,7 +149,7 @@ public class RetryTests extends ESTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { this.lastFailure = e; latch.countDown(); } diff --git a/core/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTookTests.java b/core/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTookTests.java index 6111c4c9953..7c39adc76f6 100644 --- a/core/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTookTests.java +++ b/core/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTookTests.java @@ -201,7 +201,7 @@ public class TransportBulkActionTookTests extends ESTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { } }); diff --git a/core/src/test/java/org/elasticsearch/action/ingest/BulkRequestModifierTests.java b/core/src/test/java/org/elasticsearch/action/ingest/BulkRequestModifierTests.java index 3286c07e06c..9ee5036131d 100644 --- a/core/src/test/java/org/elasticsearch/action/ingest/BulkRequestModifierTests.java +++ b/core/src/test/java/org/elasticsearch/action/ingest/BulkRequestModifierTests.java @@ -111,7 +111,7 @@ public class BulkRequestModifierTests extends ESTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { } }); @@ -157,7 +157,7 @@ public class BulkRequestModifierTests extends ESTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { } public BulkResponse getResponse() { diff --git a/core/src/test/java/org/elasticsearch/action/main/MainActionTests.java b/core/src/test/java/org/elasticsearch/action/main/MainActionTests.java index 3e592d1c341..a8c550e01c5 100644 --- a/core/src/test/java/org/elasticsearch/action/main/MainActionTests.java +++ b/core/src/test/java/org/elasticsearch/action/main/MainActionTests.java @@ -121,7 +121,7 @@ public class MainActionTests extends ESTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { logger.error("unexpected error", e); } }); diff --git a/core/src/test/java/org/elasticsearch/action/support/ListenableActionFutureTests.java b/core/src/test/java/org/elasticsearch/action/support/ListenableActionFutureTests.java index 80492f0be61..8169a674bed 100644 --- a/core/src/test/java/org/elasticsearch/action/support/ListenableActionFutureTests.java +++ b/core/src/test/java/org/elasticsearch/action/support/ListenableActionFutureTests.java @@ -45,15 +45,15 @@ public class ListenableActionFutureTests extends ESTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { error.set(e); listenerCalled.countDown(); } }); Thread networkThread = new Thread(new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - error.set(t); + public void onFailure(Exception e) { + error.set(e); listenerCalled.countDown(); } diff --git a/core/src/test/java/org/elasticsearch/action/support/TransportActionFilterChainTests.java b/core/src/test/java/org/elasticsearch/action/support/TransportActionFilterChainTests.java index 00068c05efe..b78425cd2a5 100644 --- a/core/src/test/java/org/elasticsearch/action/support/TransportActionFilterChainTests.java +++ b/core/src/test/java/org/elasticsearch/action/support/TransportActionFilterChainTests.java @@ -41,6 +41,8 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import java.util.stream.IntStream; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; @@ -102,8 +104,8 @@ public class TransportActionFilterChainTests extends ESTestCase { try { assertThat(future.get(), notNullValue()); assertThat("shouldn't get here if an error is expected", errorExpected, equalTo(false)); - } catch(Throwable t) { - assertThat("shouldn't get here if an error is not expected " + t.getMessage(), errorExpected, equalTo(true)); + } catch (ExecutionException e) { + assertThat("shouldn't get here if an error is not expected " + e.getMessage(), errorExpected, equalTo(true)); } List testFiltersByLastExecution = new ArrayList<>(); @@ -182,8 +184,8 @@ public class TransportActionFilterChainTests extends ESTestCase { try { assertThat(future.get(), notNullValue()); assertThat("shouldn't get here if an error is expected", errorExpected, equalTo(false)); - } catch(Throwable t) { - assertThat("shouldn't get here if an error is not expected " + t.getMessage(), errorExpected, equalTo(true)); + } catch(ExecutionException e) { + assertThat("shouldn't get here if an error is not expected " + e.getMessage(), errorExpected, equalTo(true)); } List testFiltersByLastExecution = new ArrayList<>(); @@ -252,7 +254,7 @@ public class TransportActionFilterChainTests extends ESTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { failures.add(e); latch.countDown(); } @@ -309,7 +311,7 @@ public class TransportActionFilterChainTests extends ESTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { failures.add(e); latch.countDown(); } diff --git a/core/src/test/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeActionTests.java b/core/src/test/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeActionTests.java index 1d65f277e3c..5e49518bd5a 100644 --- a/core/src/test/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeActionTests.java +++ b/core/src/test/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeActionTests.java @@ -491,7 +491,7 @@ public class TransportBroadcastByNodeActionTests extends ESTestCase { } @Override - public void sendResponse(Throwable error) throws IOException { + public void sendResponse(Exception exception) throws IOException { } @Override diff --git a/core/src/test/java/org/elasticsearch/action/support/master/TransportMasterNodeActionTests.java b/core/src/test/java/org/elasticsearch/action/support/master/TransportMasterNodeActionTests.java index 37cd74e00d9..c6d17605eb4 100644 --- a/core/src/test/java/org/elasticsearch/action/support/master/TransportMasterNodeActionTests.java +++ b/core/src/test/java/org/elasticsearch/action/support/master/TransportMasterNodeActionTests.java @@ -167,7 +167,7 @@ public class TransportMasterNodeActionTests extends ESTestCase { Request request = new Request(); PlainActionFuture listener = new PlainActionFuture<>(); - final Throwable exception = new Throwable(); + final Exception exception = new Exception(); final Response response = new Response(); setState(clusterService, ClusterStateCreationUtils.state(localNode, localNode, allNodes)); @@ -342,7 +342,7 @@ public class TransportMasterNodeActionTests extends ESTestCase { protected void masterOperation(Request request, ClusterState state, ActionListener listener) throws Exception { // The other node has become master, simulate failures of this node while publishing cluster state through ZenDiscovery setState(clusterService, ClusterStateCreationUtils.state(localNode, remoteNode, allNodes)); - Throwable failure = randomBoolean() + Exception failure = randomBoolean() ? new Discovery.FailedToCommitClusterStateException("Fake error") : new NotMasterException("Fake error"); listener.onFailure(failure); diff --git a/core/src/test/java/org/elasticsearch/action/support/replication/ReplicationOperationTests.java b/core/src/test/java/org/elasticsearch/action/support/replication/ReplicationOperationTests.java index 55e2a9d3cf2..9f41f0e37c2 100644 --- a/core/src/test/java/org/elasticsearch/action/support/replication/ReplicationOperationTests.java +++ b/core/src/test/java/org/elasticsearch/action/support/replication/ReplicationOperationTests.java @@ -81,11 +81,11 @@ public class ReplicationOperationTests extends ESTestCase { final Set expectedReplicas = getExpectedReplicas(shardId, state); - final Map expectedFailures = new HashMap<>(); + final Map expectedFailures = new HashMap<>(); final Set expectedFailedShards = new HashSet<>(); for (ShardRouting replica : expectedReplicas) { if (randomBoolean()) { - Throwable t; + Exception t; boolean criticalFailure = randomBoolean(); if (criticalFailure) { t = new CorruptIndexException("simulated", (String) null); @@ -166,7 +166,7 @@ public class ReplicationOperationTests extends ESTestCase { final Set expectedReplicas = getExpectedReplicas(shardId, state); - final Map expectedFailures = new HashMap<>(); + final Map expectedFailures = new HashMap<>(); final ShardRouting failedReplica = randomFrom(new ArrayList<>(expectedReplicas)); expectedFailures.put(failedReplica, new CorruptIndexException("simulated", (String) null)); @@ -175,9 +175,9 @@ public class ReplicationOperationTests extends ESTestCase { final ClusterState finalState = state; final TestReplicaProxy replicasProxy = new TestReplicaProxy(expectedFailures) { @Override - public void failShard(ShardRouting replica, ShardRouting primary, String message, Throwable throwable, - Runnable onSuccess, Consumer onPrimaryDemoted, - Consumer onIgnoredFailure) { + public void failShard(ShardRouting replica, ShardRouting primary, String message, Exception exception, + Runnable onSuccess, Consumer onPrimaryDemoted, + Consumer onIgnoredFailure) { assertThat(replica, equalTo(failedReplica)); onPrimaryDemoted.accept(new ElasticsearchException("the king is dead")); } @@ -185,7 +185,7 @@ public class ReplicationOperationTests extends ESTestCase { AtomicBoolean primaryFailed = new AtomicBoolean(); final TestPrimary primary = new TestPrimary(primaryShard, primaryTerm) { @Override - public void failShard(String message, Throwable throwable) { + public void failShard(String message, Exception exception) { assertTrue(primaryFailed.compareAndSet(false, true)); } }; @@ -376,8 +376,8 @@ public class ReplicationOperationTests extends ESTestCase { } @Override - public void failShard(String message, Throwable throwable) { - throw new AssertionError("should shouldn't be failed with [" + message + "]", throwable); + public void failShard(String message, Exception exception) { + throw new AssertionError("should shouldn't be failed with [" + message + "]", exception); } @Override @@ -415,7 +415,7 @@ public class ReplicationOperationTests extends ESTestCase { static class TestReplicaProxy implements ReplicationOperation.Replicas { - final Map opFailures; + final Map opFailures; final Set failedReplicas = ConcurrentCollections.newConcurrentSet(); @@ -423,7 +423,7 @@ public class ReplicationOperationTests extends ESTestCase { this(Collections.emptyMap()); } - TestReplicaProxy(Map opFailures) { + TestReplicaProxy(Map opFailures) { this.opFailures = opFailures; } @@ -438,8 +438,8 @@ public class ReplicationOperationTests extends ESTestCase { } @Override - public void failShard(ShardRouting replica, ShardRouting primary, String message, Throwable throwable, Runnable onSuccess, - Consumer onPrimaryDemoted, Consumer onIgnoredFailure) { + public void failShard(ShardRouting replica, ShardRouting primary, String message, Exception exception, Runnable onSuccess, + Consumer onPrimaryDemoted, Consumer onIgnoredFailure) { if (failedReplicas.add(replica) == false) { fail("replica [" + replica + "] was failed twice"); } diff --git a/core/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java b/core/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java index faa6a031f3b..de2ddabb0fe 100644 --- a/core/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java +++ b/core/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java @@ -785,7 +785,7 @@ public class TransportReplicationActionTests extends ESTestCase { } @Override - public void failShard(String reason, @Nullable Throwable e) { + public void failShard(String reason, @Nullable Exception e) { throw new UnsupportedOperationException(); } @@ -856,9 +856,9 @@ public class TransportReplicationActionTests extends ESTestCase { } @Override - public void sendResponse(Throwable error) throws IOException { - consumer.accept(error); - listener.onFailure(error); + public void sendResponse(Exception exception) throws IOException { + consumer.accept(exception); + listener.onFailure(exception); } @Override diff --git a/core/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java b/core/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java index 7b312959631..80e689743fd 100644 --- a/core/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java +++ b/core/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java @@ -179,7 +179,7 @@ public class TransportWriteActionTests extends ESTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { throw new RuntimeException(e); } } diff --git a/core/src/test/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationActionTests.java b/core/src/test/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationActionTests.java index c26d376b587..37abc4d5eed 100644 --- a/core/src/test/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationActionTests.java +++ b/core/src/test/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationActionTests.java @@ -179,9 +179,9 @@ public class TransportInstanceSingleOperationActionTests extends ESTestCase { action.new AsyncSingleAction(request, listener).start(); listener.get(); fail("expected ClusterBlockException"); - } catch (Throwable t) { - if (ExceptionsHelper.unwrap(t, ClusterBlockException.class) == null) { - logger.info("expected ClusterBlockException but got ", t); + } catch (Exception e) { + if (ExceptionsHelper.unwrap(e, ClusterBlockException.class) == null) { + logger.info("expected ClusterBlockException but got ", e); fail("expected ClusterBlockException"); } } @@ -317,9 +317,9 @@ public class TransportInstanceSingleOperationActionTests extends ESTestCase { assertThat(transport.capturedRequests().length, equalTo(0)); try { listener.get(); - } catch (Throwable t) { - if (ExceptionsHelper.unwrap(t, IllegalStateException.class) == null) { - logger.info("expected IllegalStateException but got ", t); + } catch (Exception e) { + if (ExceptionsHelper.unwrap(e, IllegalStateException.class) == null) { + logger.info("expected IllegalStateException but got ", e); fail("expected and IllegalStateException"); } } diff --git a/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java b/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java index 6ba31fdb88e..d8fd7916b5a 100644 --- a/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java +++ b/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java @@ -389,19 +389,15 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase { TestConfig[] testConfigs = generateTestConfigs(20, testDocs, testFieldSettings); for (TestConfig test : testConfigs) { - try { - TermVectorsRequestBuilder request = getRequestForConfig(test); - if (test.expectedException != null) { - assertThrows(request, test.expectedException); - continue; - } - - TermVectorsResponse response = request.get(); - Fields luceneTermVectors = getTermVectorsFromLucene(directoryReader, test.doc); - validateResponse(response, luceneTermVectors, test); - } catch (Throwable t) { - throw new Exception("Test exception while running " + test.toString(), t); + TermVectorsRequestBuilder request = getRequestForConfig(test); + if (test.expectedException != null) { + assertThrows(request, test.expectedException); + continue; } + + TermVectorsResponse response = request.get(); + Fields luceneTermVectors = getTermVectorsFromLucene(directoryReader, test.doc); + validateResponse(response, luceneTermVectors, test); } } diff --git a/core/src/test/java/org/elasticsearch/action/termvectors/MultiTermVectorsIT.java b/core/src/test/java/org/elasticsearch/action/termvectors/MultiTermVectorsIT.java index 57a89c82cc8..5ed4f3252d5 100644 --- a/core/src/test/java/org/elasticsearch/action/termvectors/MultiTermVectorsIT.java +++ b/core/src/test/java/org/elasticsearch/action/termvectors/MultiTermVectorsIT.java @@ -56,21 +56,16 @@ public class MultiTermVectorsIT extends AbstractTermVectorsTestCase { for (int i = 0; i < testConfigs.length; i++) { TestConfig test = testConfigs[i]; - try { - MultiTermVectorsItemResponse item = responseItems[i]; - if (test.expectedException != null) { - assertTrue(item.isFailed()); - continue; - } else if (item.isFailed()) { - fail(item.getFailure().getCause().getMessage()); - } - Fields luceneTermVectors = getTermVectorsFromLucene(directoryReader, test.doc); - validateResponse(item.getResponse(), luceneTermVectors, test); - } catch (Throwable t) { - throw new Exception("Test exception while running " + test.toString(), t); + MultiTermVectorsItemResponse item = responseItems[i]; + if (test.expectedException != null) { + assertTrue(item.isFailed()); + continue; + } else if (item.isFailed()) { + fail(item.getFailure().getCause().getMessage()); } + Fields luceneTermVectors = getTermVectorsFromLucene(directoryReader, test.doc); + validateResponse(item.getResponse(), luceneTermVectors, test); } - } public void testMissingIndexThrowsMissingIndex() throws Exception { diff --git a/core/src/test/java/org/elasticsearch/client/AbstractClientHeadersTestCase.java b/core/src/test/java/org/elasticsearch/client/AbstractClientHeadersTestCase.java index 196b053ff82..276a43581a6 100644 --- a/core/src/test/java/org/elasticsearch/client/AbstractClientHeadersTestCase.java +++ b/core/src/test/java/org/elasticsearch/client/AbstractClientHeadersTestCase.java @@ -179,7 +179,7 @@ public abstract class AbstractClientHeadersTestCase extends ESTestCase { } @Override - public void onFailure(Throwable t) { + public void onFailure(Exception t) { Throwable e = unwrap(t, InternalException.class); assertThat("expected action [" + action + "] to throw an internal exception", e, notNullValue()); assertThat(action, equalTo(((InternalException) e).action)); diff --git a/core/src/test/java/org/elasticsearch/client/transport/TransportClientNodesServiceTests.java b/core/src/test/java/org/elasticsearch/client/transport/TransportClientNodesServiceTests.java index 5c07f5e6f25..42ec724ed52 100644 --- a/core/src/test/java/org/elasticsearch/client/transport/TransportClientNodesServiceTests.java +++ b/core/src/test/java/org/elasticsearch/client/transport/TransportClientNodesServiceTests.java @@ -19,7 +19,6 @@ package org.elasticsearch.client.transport; -import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.cluster.node.liveness.LivenessResponse; import org.elasticsearch.action.admin.cluster.node.liveness.TransportLivenessAction; @@ -171,7 +170,7 @@ public class TransportClientNodesServiceTests extends ESTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { finalFailures.incrementAndGet(); finalFailure.set(e); latch.countDown(); diff --git a/core/src/test/java/org/elasticsearch/cluster/MinimumMasterNodesIT.java b/core/src/test/java/org/elasticsearch/cluster/MinimumMasterNodesIT.java index 61bb898acc2..aad2aa212a1 100644 --- a/core/src/test/java/org/elasticsearch/cluster/MinimumMasterNodesIT.java +++ b/core/src/test/java/org/elasticsearch/cluster/MinimumMasterNodesIT.java @@ -395,8 +395,8 @@ public class MinimumMasterNodesIT extends ESIntegTestCase { } @Override - public void onFailure(String source, Throwable t) { - failure.set(t); + public void onFailure(String source, Exception e) { + failure.set(e); latch.countDown(); } }); diff --git a/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java b/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java index 7f0ac1a6e45..d387d6f7d43 100644 --- a/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java +++ b/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java @@ -148,7 +148,7 @@ public class ShardStateActionTests extends ESTestCase { } @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { success.set(false); latch.countDown(); assert false; @@ -196,7 +196,7 @@ public class ShardStateActionTests extends ESTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { success.set(false); latch.countDown(); assert false; @@ -245,9 +245,9 @@ public class ShardStateActionTests extends ESTestCase { } @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { success.set(false); - throwable.set(t); + throwable.set(e); latch.countDown(); assert false; } @@ -281,7 +281,7 @@ public class ShardStateActionTests extends ESTestCase { } @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { failure.set(true); } }); @@ -313,7 +313,7 @@ public class ShardStateActionTests extends ESTestCase { } @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { success.set(false); latch.countDown(); assert false; @@ -348,8 +348,8 @@ public class ShardStateActionTests extends ESTestCase { } @Override - public void onFailure(Throwable t) { - failure.set(t); + public void onFailure(Exception e) { + failure.set(e); latch.countDown(); } }); @@ -401,7 +401,7 @@ public class ShardStateActionTests extends ESTestCase { } } - private Throwable getSimulatedFailure() { + private Exception getSimulatedFailure() { return new CorruptIndexException("simulated", (String) null); } } diff --git a/core/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java b/core/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java index 0918358a510..8718c479216 100644 --- a/core/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java +++ b/core/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java @@ -118,8 +118,8 @@ public class ClusterStateHealthTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { - logger.warn("unexpected failure", t); + public void onFailure(String source, Exception e) { + logger.warn("unexpected failure", e); } }); diff --git a/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceIT.java b/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceIT.java index 7907ad3e63c..23713832edf 100644 --- a/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceIT.java +++ b/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceIT.java @@ -94,7 +94,7 @@ public class ClusterServiceIT extends ESIntegTestCase { } @Override - public void onAllNodesAcked(@Nullable Throwable t) { + public void onAllNodesAcked(@Nullable Exception e) { allNodesAcked.set(true); latch.countDown(); } @@ -127,8 +127,8 @@ public class ClusterServiceIT extends ESIntegTestCase { } @Override - public void onFailure(String source, Throwable t) { - logger.error("failed to execute callback in test {}", t, source); + public void onFailure(String source, Exception e) { + logger.error("failed to execute callback in test {}", e, source); onFailure.set(true); latch.countDown(); } @@ -165,7 +165,7 @@ public class ClusterServiceIT extends ESIntegTestCase { } @Override - public void onAllNodesAcked(@Nullable Throwable t) { + public void onAllNodesAcked(@Nullable Exception e) { allNodesAcked.set(true); latch.countDown(); } @@ -198,8 +198,8 @@ public class ClusterServiceIT extends ESIntegTestCase { } @Override - public void onFailure(String source, Throwable t) { - logger.error("failed to execute callback in test {}", t, source); + public void onFailure(String source, Exception e) { + logger.error("failed to execute callback in test {}", e, source); onFailure.set(true); latch.countDown(); } @@ -240,7 +240,7 @@ public class ClusterServiceIT extends ESIntegTestCase { } @Override - public void onAllNodesAcked(@Nullable Throwable t) { + public void onAllNodesAcked(@Nullable Exception e) { allNodesAcked.set(true); latch.countDown(); } @@ -272,8 +272,8 @@ public class ClusterServiceIT extends ESIntegTestCase { } @Override - public void onFailure(String source, Throwable t) { - logger.error("failed to execute callback in test {}", t, source); + public void onFailure(String source, Exception e) { + logger.error("failed to execute callback in test {}", e, source); onFailure.set(true); latch.countDown(); } @@ -313,7 +313,7 @@ public class ClusterServiceIT extends ESIntegTestCase { } @Override - public void onAllNodesAcked(@Nullable Throwable t) { + public void onAllNodesAcked(@Nullable Exception e) { allNodesAcked.set(true); latch.countDown(); } @@ -346,8 +346,8 @@ public class ClusterServiceIT extends ESIntegTestCase { } @Override - public void onFailure(String source, Throwable t) { - logger.error("failed to execute callback in test {}", t, source); + public void onFailure(String source, Exception e) { + logger.error("failed to execute callback in test {}", e, source); onFailure.set(true); latch.countDown(); } @@ -388,7 +388,7 @@ public class ClusterServiceIT extends ESIntegTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { invoked1.countDown(); fail(); } @@ -403,7 +403,7 @@ public class ClusterServiceIT extends ESIntegTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { fail(); } @@ -458,7 +458,7 @@ public class ClusterServiceIT extends ESIntegTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { invoked3.countDown(); fail(); } @@ -473,7 +473,7 @@ public class ClusterServiceIT extends ESIntegTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { fail(); } }); diff --git a/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceTests.java b/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceTests.java index 66f96f8cd3a..c94e441aea3 100644 --- a/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceTests.java +++ b/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceTests.java @@ -149,8 +149,8 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { - throw new RuntimeException(t); + public void onFailure(String source, Exception e) { + throw new RuntimeException(e); } }); @@ -163,7 +163,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { timedOut.countDown(); } @@ -183,8 +183,8 @@ public class ClusterServiceTests extends ESTestCase { final CountDownLatch allProcessed = new CountDownLatch(1); clusterService.submitStateUpdateTask("test3", new ClusterStateUpdateTask() { @Override - public void onFailure(String source, Throwable t) { - throw new RuntimeException(t); + public void onFailure(String source, Exception e) { + throw new RuntimeException(e); } @Override @@ -212,7 +212,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { taskFailed[0] = true; latch1.countDown(); } @@ -237,7 +237,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { taskFailed[0] = true; latch2.countDown(); } @@ -286,7 +286,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { } } ); @@ -326,9 +326,9 @@ public class ClusterServiceTests extends ESTestCase { ClusterStateTaskListener listener = new ClusterStateTaskListener() { @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected failure: [{}]", t, source); - failures.add(new Tuple<>(source, t)); + public void onFailure(String source, Exception e) { + logger.error("unexpected failure: [{}]", e, source); + failures.add(new Tuple<>(source, e)); updateLatch.countDown(); } @@ -387,8 +387,8 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { - fail(ExceptionsHelper.detailedMessage(t)); + public void onFailure(String source, Exception e) { + fail(ExceptionsHelper.detailedMessage(e)); } })) ; } @@ -523,8 +523,8 @@ public class ClusterServiceTests extends ESTestCase { final CountDownLatch updateLatch = new CountDownLatch(totalTaskCount); final ClusterStateTaskListener listener = new ClusterStateTaskListener() { @Override - public void onFailure(String source, Throwable t) { - fail(ExceptionsHelper.detailedMessage(t)); + public void onFailure(String source, Exception e) { + fail(ExceptionsHelper.detailedMessage(e)); } @Override @@ -647,8 +647,8 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { - fail(ExceptionsHelper.detailedMessage(t)); + public void onFailure(String source, Exception e) { + fail(ExceptionsHelper.detailedMessage(e)); } }; @@ -693,7 +693,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { fail(); } }); @@ -710,7 +710,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { latch.countDown(); } }); @@ -727,7 +727,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { fail(); } }); @@ -745,7 +745,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { fail(); } }); @@ -788,7 +788,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { fail(); } }); @@ -807,7 +807,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { latch.countDown(); } }); @@ -824,7 +824,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { fail(); } }); @@ -841,7 +841,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { fail(); } }); @@ -859,7 +859,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { fail(); } }); @@ -902,7 +902,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { } public void close() { @@ -930,7 +930,7 @@ public class ClusterServiceTests extends ESTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { latch.countDown(); } } diff --git a/core/src/test/java/org/elasticsearch/common/breaker/MemoryCircuitBreakerTests.java b/core/src/test/java/org/elasticsearch/common/breaker/MemoryCircuitBreakerTests.java index bb9d23db1cb..f10a0da3029 100644 --- a/core/src/test/java/org/elasticsearch/common/breaker/MemoryCircuitBreakerTests.java +++ b/core/src/test/java/org/elasticsearch/common/breaker/MemoryCircuitBreakerTests.java @@ -43,7 +43,7 @@ public class MemoryCircuitBreakerTests extends ESTestCase { final int BYTES_PER_THREAD = scaledRandomIntBetween(500, 4500); final Thread[] threads = new Thread[NUM_THREADS]; final AtomicBoolean tripped = new AtomicBoolean(false); - final AtomicReference lastException = new AtomicReference<>(null); + final AtomicReference lastException = new AtomicReference<>(null); final MemoryCircuitBreaker breaker = new MemoryCircuitBreaker(new ByteSizeValue((BYTES_PER_THREAD * NUM_THREADS) - 1), 1.0, logger); @@ -60,8 +60,8 @@ public class MemoryCircuitBreakerTests extends ESTestCase { } else { assertThat(tripped.compareAndSet(false, true), equalTo(true)); } - } catch (Throwable e2) { - lastException.set(e2); + } catch (Exception e) { + lastException.set(e); } } } @@ -117,8 +117,8 @@ public class MemoryCircuitBreakerTests extends ESTestCase { } else { assertThat(tripped.compareAndSet(false, true), equalTo(true)); } - } catch (Throwable e2) { - lastException.set(e2); + } catch (Exception e) { + lastException.set(e); } } } @@ -178,8 +178,8 @@ public class MemoryCircuitBreakerTests extends ESTestCase { breaker.addEstimateBytesAndMaybeBreak(1L, "test"); } catch (CircuitBreakingException e) { tripped.incrementAndGet(); - } catch (Throwable e2) { - lastException.set(e2); + } catch (Exception e) { + lastException.set(e); } } } diff --git a/core/src/test/java/org/elasticsearch/common/util/CancellableThreadsTests.java b/core/src/test/java/org/elasticsearch/common/util/CancellableThreadsTests.java index a89cb48c37a..729c431d2b2 100644 --- a/core/src/test/java/org/elasticsearch/common/util/CancellableThreadsTests.java +++ b/core/src/test/java/org/elasticsearch/common/util/CancellableThreadsTests.java @@ -132,7 +132,7 @@ public class CancellableThreadsTests extends ESTestCase { public void testCancellableThreads() throws InterruptedException { Thread[] threads = new Thread[randomIntBetween(3, 10)]; final TestPlan[] plans = new TestPlan[threads.length]; - final Throwable[] throwables = new Throwable[threads.length]; + final Exception[] exceptions = new Exception[threads.length]; final boolean[] interrupted = new boolean[threads.length]; final CancellableThreads cancellableThreads = new CancellableThreads(); final CountDownLatch readyForCancel = new CountDownLatch(threads.length); @@ -153,8 +153,8 @@ public class CancellableThreadsTests extends ESTestCase { } else { cancellableThreads.execute(new TestRunnable(plan, readyForCancel)); } - } catch (Throwable t) { - throwables[plan.id] = t; + } catch (Exception e) { + exceptions[plan.id] = e; } if (plan.exceptBeforeCancel || plan.exitBeforeCancel) { // we have to mark we're ready now (actually done). @@ -176,19 +176,19 @@ public class CancellableThreadsTests extends ESTestCase { TestPlan plan = plans[i]; final Class exceptionClass = plan.ioException ? IOCustomException.class : CustomException.class; if (plan.exceptBeforeCancel) { - assertThat(throwables[i], Matchers.instanceOf(exceptionClass)); + assertThat(exceptions[i], Matchers.instanceOf(exceptionClass)); } else if (plan.exitBeforeCancel) { - assertNull(throwables[i]); + assertNull(exceptions[i]); } else { // in all other cases, we expect a cancellation exception. - assertThat(throwables[i], Matchers.instanceOf(CancellableThreads.ExecutionCancelledException.class)); + assertThat(exceptions[i], Matchers.instanceOf(CancellableThreads.ExecutionCancelledException.class)); if (plan.exceptAfterCancel) { - assertThat(throwables[i].getSuppressed(), + assertThat(exceptions[i].getSuppressed(), Matchers.arrayContaining( Matchers.instanceOf(exceptionClass) )); } else { - assertThat(throwables[i].getSuppressed(), Matchers.emptyArray()); + assertThat(exceptions[i].getSuppressed(), Matchers.emptyArray()); } } assertThat(interrupted[plan.id], Matchers.equalTo(plan.presetInterrupt)); diff --git a/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractLifecycleRunnableTests.java b/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractLifecycleRunnableTests.java index 4c2e4700943..02adb783197 100644 --- a/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractLifecycleRunnableTests.java +++ b/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractLifecycleRunnableTests.java @@ -48,7 +48,7 @@ public class AbstractLifecycleRunnableTests extends ESTestCase { AbstractLifecycleRunnable runnable = new AbstractLifecycleRunnable(lifecycle, logger) { @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { fail("It should not fail"); } @@ -77,7 +77,7 @@ public class AbstractLifecycleRunnableTests extends ESTestCase { AbstractLifecycleRunnable runnable = new AbstractLifecycleRunnable(lifecycle, logger) { @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { fail("It should not fail"); } @@ -106,7 +106,7 @@ public class AbstractLifecycleRunnableTests extends ESTestCase { AbstractLifecycleRunnable runnable = new AbstractLifecycleRunnable(lifecycle, logger) { @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { fail("It should not fail"); } @@ -145,7 +145,7 @@ public class AbstractLifecycleRunnableTests extends ESTestCase { AbstractLifecycleRunnable runnable = new AbstractLifecycleRunnable(lifecycle, logger) { @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { fail("It should not fail"); } diff --git a/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractRunnableTests.java b/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractRunnableTests.java index 54491aade6f..2373b30e1b2 100644 --- a/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractRunnableTests.java +++ b/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractRunnableTests.java @@ -37,8 +37,8 @@ public class AbstractRunnableTests extends ESTestCase { AbstractRunnable runnable = new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - fail("It should not fail"); + public void onFailure(Exception e) { + fail(e.toString()); } @Override @@ -57,8 +57,8 @@ public class AbstractRunnableTests extends ESTestCase { AbstractRunnable runnable = new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - assertSame(exception, t); + public void onFailure(Exception e) { + assertSame(exception, e); } @Override @@ -76,8 +76,8 @@ public class AbstractRunnableTests extends ESTestCase { AbstractRunnable runnable = new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - fail("It should not fail"); + public void onFailure(Exception e) { + fail(e.toString()); } @Override @@ -91,7 +91,7 @@ public class AbstractRunnableTests extends ESTestCase { afterCallable.call(); } catch (Exception e) { - fail("Unexpected for mock."); + fail(e.toString()); } } }; @@ -111,8 +111,8 @@ public class AbstractRunnableTests extends ESTestCase { AbstractRunnable runnable = new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - assertSame(exception, t); + public void onFailure(Exception e) { + assertSame(exception, e); } @Override @@ -126,7 +126,7 @@ public class AbstractRunnableTests extends ESTestCase { afterCallable.call(); } catch (Exception e) { - fail("Unexpected for mock."); + fail(e.toString()); } } }; @@ -142,14 +142,15 @@ public class AbstractRunnableTests extends ESTestCase { AbstractRunnable runnable = new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - assertSame(exception, t); + public void onFailure(Exception e) { + assertSame(exception, e); try { failureCallable.call(); } - catch (Exception e) { - fail("Unexpected for mock."); + catch (Exception inner) { + inner.addSuppressed(e); + fail(inner.toString()); } } @@ -165,8 +166,8 @@ public class AbstractRunnableTests extends ESTestCase { public void testIsForceExecutuonDefaultsFalse() { AbstractRunnable runnable = new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - fail("Not tested"); + public void onFailure(Exception e) { + fail(e.toString()); } @Override diff --git a/core/src/test/java/org/elasticsearch/common/util/concurrent/EsExecutorsTests.java b/core/src/test/java/org/elasticsearch/common/util/concurrent/EsExecutorsTests.java index 57da614e689..72db2911fc0 100644 --- a/core/src/test/java/org/elasticsearch/common/util/concurrent/EsExecutorsTests.java +++ b/core/src/test/java/org/elasticsearch/common/util/concurrent/EsExecutorsTests.java @@ -88,8 +88,8 @@ public class EsExecutorsTests extends ESTestCase { } @Override - public void onFailure(Throwable t) { - throw new AssertionError(t); + public void onFailure(Exception e) { + throw new AssertionError(e); } }); @@ -178,7 +178,7 @@ public class EsExecutorsTests extends ESTestCase { try { barrier.await(); barrier.await(); - } catch (Throwable e) { + } catch (Exception e) { barrier.reset(e); } } @@ -214,7 +214,7 @@ public class EsExecutorsTests extends ESTestCase { try { barrier.await(); barrier.await(); - } catch (Throwable e) { + } catch (Exception e) { barrier.reset(e); } } diff --git a/core/src/test/java/org/elasticsearch/common/util/concurrent/RefCountedTests.java b/core/src/test/java/org/elasticsearch/common/util/concurrent/RefCountedTests.java index 9338beccb9a..c5d0ec4257e 100644 --- a/core/src/test/java/org/elasticsearch/common/util/concurrent/RefCountedTests.java +++ b/core/src/test/java/org/elasticsearch/common/util/concurrent/RefCountedTests.java @@ -88,7 +88,7 @@ public class RefCountedTests extends ESTestCase { final MyRefCounted counted = new MyRefCounted(); Thread[] threads = new Thread[randomIntBetween(2, 5)]; final CountDownLatch latch = new CountDownLatch(1); - final CopyOnWriteArrayList exceptions = new CopyOnWriteArrayList<>(); + final CopyOnWriteArrayList exceptions = new CopyOnWriteArrayList<>(); for (int i = 0; i < threads.length; i++) { threads[i] = new Thread() { @Override @@ -103,7 +103,7 @@ public class RefCountedTests extends ESTestCase { counted.decRef(); } } - } catch (Throwable e) { + } catch (Exception e) { exceptions.add(e); } } diff --git a/core/src/test/java/org/elasticsearch/common/util/concurrent/ThreadContextTests.java b/core/src/test/java/org/elasticsearch/common/util/concurrent/ThreadContextTests.java index d6797d4be26..e6726879513 100644 --- a/core/src/test/java/org/elasticsearch/common/util/concurrent/ThreadContextTests.java +++ b/core/src/test/java/org/elasticsearch/common/util/concurrent/ThreadContextTests.java @@ -294,8 +294,8 @@ public class ThreadContextTests extends ESTestCase { } return new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - throw new RuntimeException(t); + public void onFailure(Exception e) { + throw new RuntimeException(e); } @Override diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/ConstructingObjectParserTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/ConstructingObjectParserTests.java index f3592936765..bef4a047ef5 100644 --- a/core/src/test/java/org/elasticsearch/common/xcontent/ConstructingObjectParserTests.java +++ b/core/src/test/java/org/elasticsearch/common/xcontent/ConstructingObjectParserTests.java @@ -68,7 +68,7 @@ public class ConstructingObjectParserTests extends ESTestCase { assertEquals(expected.b, parsed.b); assertEquals(expected.c, parsed.c); assertEquals(expected.d, parsed.d); - } catch (Throwable e) { + } catch (Exception e) { // It is convenient to decorate the error message with the json throw new Exception("Error parsing: [" + builder.string() + "]", e); } diff --git a/core/src/test/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandlerTests.java b/core/src/test/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandlerTests.java index bb38e329103..0f34ff181a7 100644 --- a/core/src/test/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandlerTests.java +++ b/core/src/test/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandlerTests.java @@ -58,8 +58,8 @@ public class BlockingClusterStatePublishResponseHandlerTests extends ESTestCase } @Override - public void onFailure(Throwable t) { - logger.error("unexpected error", t); + public void onFailure(Exception e) { + logger.error("unexpected error", e); } @Override diff --git a/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java b/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java index 13e19e84978..a1bac928daf 100644 --- a/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java +++ b/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java @@ -503,8 +503,8 @@ public class DiscoveryWithServiceDisruptionsIT extends ESIntegTestCase { } } catch (InterruptedException e) { // fine - semaphore interrupt - } catch (Throwable t) { - logger.info("unexpected exception in background thread of [{}]", t, node); + } catch (AssertionError | Exception e) { + logger.info("unexpected exception in background thread of [{}]", e, node); } } }); @@ -690,8 +690,8 @@ public class DiscoveryWithServiceDisruptionsIT extends ESIntegTestCase { } @Override - public void onFailure(String source, Throwable t) { - logger.warn("failure [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.warn("failure [{}]", e, source); } }); @@ -960,7 +960,7 @@ public class DiscoveryWithServiceDisruptionsIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable t) { + public void onFailure(Exception e) { success.set(false); latch.countDown(); assert false; diff --git a/core/src/test/java/org/elasticsearch/discovery/zen/NodeJoinControllerTests.java b/core/src/test/java/org/elasticsearch/discovery/zen/NodeJoinControllerTests.java index 9825cd3284e..531b20aa3c9 100644 --- a/core/src/test/java/org/elasticsearch/discovery/zen/NodeJoinControllerTests.java +++ b/core/src/test/java/org/elasticsearch/discovery/zen/NodeJoinControllerTests.java @@ -196,9 +196,9 @@ public class NodeJoinControllerTests extends ESTestCase { final SimpleFuture electionFuture = new SimpleFuture("master election"); final Thread masterElection = new Thread(new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - logger.error("unexpected error from waitToBeElectedAsMaster", t); - electionFuture.markAsFailed(t); + public void onFailure(Exception e) { + logger.error("unexpected error from waitToBeElectedAsMaster", e); + electionFuture.markAsFailed(e); } @Override @@ -244,9 +244,9 @@ public class NodeJoinControllerTests extends ESTestCase { final SimpleFuture electionFuture = new SimpleFuture("master election"); final Thread masterElection = new Thread(new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - logger.error("unexpected error from waitToBeElectedAsMaster", t); - electionFuture.markAsFailed(t); + public void onFailure(Exception e) { + logger.error("unexpected error from waitToBeElectedAsMaster", e); + electionFuture.markAsFailed(e); } @Override @@ -425,9 +425,9 @@ public class NodeJoinControllerTests extends ESTestCase { nodes.add(node); threads[i] = new Thread(new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - logger.error("unexpected error in join thread", t); - backgroundExceptions.add(t); + public void onFailure(Exception e) { + logger.error("unexpected error in join thread", e); + backgroundExceptions.add(e); } @Override @@ -468,9 +468,9 @@ public class NodeJoinControllerTests extends ESTestCase { nodes.add(node); threads[i] = new Thread(new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - logger.error("unexpected error in join thread", t); - backgroundExceptions.add(t); + public void onFailure(Exception e) { + logger.error("unexpected error in join thread", e); + backgroundExceptions.add(e); } @Override @@ -587,9 +587,9 @@ public class NodeJoinControllerTests extends ESTestCase { } @Override - public void onFailure(Throwable t) { - logger.error("unexpected error for {}", t, future); - future.markAsFailed(t); + public void onFailure(Exception e) { + logger.error("unexpected error for {}", e, future); + future.markAsFailed(e); } }); return future; diff --git a/core/src/test/java/org/elasticsearch/discovery/zen/ZenDiscoveryIT.java b/core/src/test/java/org/elasticsearch/discovery/zen/ZenDiscoveryIT.java index fd0b11eae01..3d0d9ddd8b1 100644 --- a/core/src/test/java/org/elasticsearch/discovery/zen/ZenDiscoveryIT.java +++ b/core/src/test/java/org/elasticsearch/discovery/zen/ZenDiscoveryIT.java @@ -261,8 +261,8 @@ public class ZenDiscoveryIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable t) { - holder.set((IllegalStateException) t); + public void onFailure(Exception e) { + holder.set((IllegalStateException) e); } }); @@ -309,8 +309,8 @@ public class ZenDiscoveryIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable t) { - holder.set((IllegalStateException) t); + public void onFailure(Exception e) { + holder.set((IllegalStateException) e); } }); diff --git a/core/src/test/java/org/elasticsearch/discovery/zen/publish/PendingClusterStatesQueueTests.java b/core/src/test/java/org/elasticsearch/discovery/zen/publish/PendingClusterStatesQueueTests.java index ab9aed6ba44..073e0fe1478 100644 --- a/core/src/test/java/org/elasticsearch/discovery/zen/publish/PendingClusterStatesQueueTests.java +++ b/core/src/test/java/org/elasticsearch/discovery/zen/publish/PendingClusterStatesQueueTests.java @@ -259,8 +259,8 @@ public class PendingClusterStatesQueueTests extends ESTestCase { } @Override - public void onNewClusterStateFailed(Throwable t) { - failure = t; + public void onNewClusterStateFailed(Exception e) { + failure = e; } } diff --git a/core/src/test/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateActionTests.java b/core/src/test/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateActionTests.java index 61374cc0d8f..8271f2dff70 100644 --- a/core/src/test/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateActionTests.java +++ b/core/src/test/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateActionTests.java @@ -797,9 +797,9 @@ public class PublishClusterStateActionTests extends ESTestCase { } @Override - public void onNodeAck(DiscoveryNode node, @Nullable Throwable t) { - if (t != null) { - errors.add(new Tuple<>(node, t)); + public void onNodeAck(DiscoveryNode node, @Nullable Exception e) { + if (e != null) { + errors.add(new Tuple<>(node, e)); } countDown.countDown(); } @@ -910,8 +910,8 @@ public class PublishClusterStateActionTests extends ESTestCase { } @Override - public void sendResponse(Throwable error) throws IOException { - this.error.set(error); + public void sendResponse(Exception exception) throws IOException { + this.error.set(exception); assertThat(response.get(), nullValue()); } diff --git a/core/src/test/java/org/elasticsearch/env/NodeEnvironmentTests.java b/core/src/test/java/org/elasticsearch/env/NodeEnvironmentTests.java index ad425d8afc9..75bfed85333 100644 --- a/core/src/test/java/org/elasticsearch/env/NodeEnvironmentTests.java +++ b/core/src/test/java/org/elasticsearch/env/NodeEnvironmentTests.java @@ -22,7 +22,6 @@ import org.apache.lucene.index.SegmentInfos; import org.apache.lucene.store.LockObtainFailedException; import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.LuceneTestCase; -import org.elasticsearch.ElasticsearchException; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.io.PathUtils; @@ -48,8 +47,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFileExists; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFileNotExists; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.arrayWithSize; import static org.hamcrest.Matchers.containsString; @@ -269,9 +266,9 @@ public class NodeEnvironmentTests extends ESTestCase { if (randomBoolean()) { Thread t = new Thread(new AbstractRunnable() { @Override - public void onFailure(Throwable t) { - logger.error("unexpected error", t); - threadException.set(t); + public void onFailure(Exception e) { + logger.error("unexpected error", e); + threadException.set(e); latch.countDown(); blockLatch.countDown(); } diff --git a/core/src/test/java/org/elasticsearch/gateway/AsyncShardFetchTests.java b/core/src/test/java/org/elasticsearch/gateway/AsyncShardFetchTests.java index 948f4820439..c5a386976bd 100644 --- a/core/src/test/java/org/elasticsearch/gateway/AsyncShardFetchTests.java +++ b/core/src/test/java/org/elasticsearch/gateway/AsyncShardFetchTests.java @@ -292,7 +292,7 @@ public class AsyncShardFetchTests extends ESTestCase { } else { processAsyncFetch(shardId, Collections.singletonList(entry.response), null); } - } catch (Throwable e) { + } catch (Exception e) { logger.error("unexpected failure", e); } finally { if (entry != null) { diff --git a/core/src/test/java/org/elasticsearch/gateway/MetaDataWriteDataNodesIT.java b/core/src/test/java/org/elasticsearch/gateway/MetaDataWriteDataNodesIT.java index 4999ef5eac5..795046ba10c 100644 --- a/core/src/test/java/org/elasticsearch/gateway/MetaDataWriteDataNodesIT.java +++ b/core/src/test/java/org/elasticsearch/gateway/MetaDataWriteDataNodesIT.java @@ -161,8 +161,8 @@ public class MetaDataWriteDataNodesIT extends ESIntegTestCase { logger.info("checking if meta state exists..."); try { assertTrue("Expecting meta state of index " + indexName + " to be on node " + nodeName, getIndicesMetaDataOnNode(nodeName).containsKey(indexName)); - } catch (Throwable t) { - logger.info("failed to load meta state", t); + } catch (Exception e) { + logger.info("failed to load meta state", e); fail("could not load meta state"); } } diff --git a/core/src/test/java/org/elasticsearch/gateway/PrimaryShardAllocatorTests.java b/core/src/test/java/org/elasticsearch/gateway/PrimaryShardAllocatorTests.java index 96e360550af..e64c816c4bf 100644 --- a/core/src/test/java/org/elasticsearch/gateway/PrimaryShardAllocatorTests.java +++ b/core/src/test/java/org/elasticsearch/gateway/PrimaryShardAllocatorTests.java @@ -24,7 +24,6 @@ import org.elasticsearch.Version; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MetaData; -import org.elasticsearch.snapshots.SnapshotId; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.RestoreSource; @@ -41,6 +40,7 @@ import org.elasticsearch.common.util.set.Sets; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.shard.ShardStateMetaData; import org.elasticsearch.snapshots.Snapshot; +import org.elasticsearch.snapshots.SnapshotId; import org.elasticsearch.test.ESAllocationTestCase; import org.junit.Before; @@ -547,7 +547,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase { return addData(node, version, allocationId, primary, null); } - public TestAllocator addData(DiscoveryNode node, long version, String allocationId, boolean primary, @Nullable Throwable storeException) { + public TestAllocator addData(DiscoveryNode node, long version, String allocationId, boolean primary, @Nullable Exception storeException) { if (data == null) { data = new HashMap<>(); } diff --git a/core/src/test/java/org/elasticsearch/index/IndexWithShadowReplicasIT.java b/core/src/test/java/org/elasticsearch/index/IndexWithShadowReplicasIT.java index 596714b1c5b..f67ee09cf0f 100644 --- a/core/src/test/java/org/elasticsearch/index/IndexWithShadowReplicasIT.java +++ b/core/src/test/java/org/elasticsearch/index/IndexWithShadowReplicasIT.java @@ -379,7 +379,7 @@ public class IndexWithShadowReplicasIT extends ESIntegTestCase { assertThat(gResp2.getField("foo").getValue().toString(), equalTo("bar")); } - public void testPrimaryRelocationWithConcurrentIndexing() throws Throwable { + public void testPrimaryRelocationWithConcurrentIndexing() throws Exception { Path dataPath = createTempDir(); Settings nodeSettings = nodeSettings(dataPath); @@ -408,7 +408,7 @@ public class IndexWithShadowReplicasIT extends ESIntegTestCase { final int numPhase2Docs = scaledRandomIntBetween(25, 200); final CountDownLatch phase1finished = new CountDownLatch(1); final CountDownLatch phase2finished = new CountDownLatch(1); - final CopyOnWriteArrayList exceptions = new CopyOnWriteArrayList<>(); + final CopyOnWriteArrayList exceptions = new CopyOnWriteArrayList<>(); Thread thread = new Thread() { @Override public void run() { @@ -418,8 +418,8 @@ public class IndexWithShadowReplicasIT extends ESIntegTestCase { final IndexResponse indexResponse = client().prepareIndex(IDX, "doc", Integer.toString(counter.incrementAndGet())).setSource("foo", "bar").get(); assertTrue(indexResponse.isCreated()); - } catch (Throwable t) { - exceptions.add(t); + } catch (Exception e) { + exceptions.add(e); } final int docCount = counter.get(); if (docCount == numPhase1Docs) { diff --git a/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java b/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java index 0ecf8462651..a3fd266f603 100644 --- a/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java +++ b/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java @@ -297,7 +297,7 @@ public class InternalEngineTests extends ESTestCase { } Engine.EventListener listener = new Engine.EventListener() { @Override - public void onFailedEngine(String reason, @Nullable Throwable t) { + public void onFailedEngine(String reason, @Nullable Exception e) { // we don't need to notify anybody in this test } }; @@ -2092,7 +2092,7 @@ public class InternalEngineTests extends ESTestCase { } public void testShardNotAvailableExceptionWhenEngineClosedConcurrently() throws IOException, InterruptedException { - AtomicReference throwable = new AtomicReference<>(); + AtomicReference exception = new AtomicReference<>(); String operation = randomFrom("optimize", "refresh", "flush"); Thread mergeThread = new Thread() { @Override @@ -2115,8 +2115,8 @@ public class InternalEngineTests extends ESTestCase { break; } } - } catch (Throwable t) { - throwable.set(t); + } catch (Exception e) { + exception.set(e); stop = true; } } @@ -2125,8 +2125,8 @@ public class InternalEngineTests extends ESTestCase { mergeThread.start(); engine.close(); mergeThread.join(); - logger.info("exception caught: ", throwable.get()); - assertTrue("expected an Exception that signals shard is not available", TransportActions.isShardNotAvailableException(throwable.get())); + logger.info("exception caught: ", exception.get()); + assertTrue("expected an Exception that signals shard is not available", TransportActions.isShardNotAvailableException(exception.get())); } public void testCurrentTranslogIDisCommitted() throws IOException { diff --git a/core/src/test/java/org/elasticsearch/index/engine/ShadowEngineTests.java b/core/src/test/java/org/elasticsearch/index/engine/ShadowEngineTests.java index 39112ed602e..672686926bd 100644 --- a/core/src/test/java/org/elasticsearch/index/engine/ShadowEngineTests.java +++ b/core/src/test/java/org/elasticsearch/index/engine/ShadowEngineTests.java @@ -242,7 +242,7 @@ public class ShadowEngineTests extends ESTestCase { } Engine.EventListener eventListener = new Engine.EventListener() { @Override - public void onFailedEngine(String reason, @Nullable Throwable t) { + public void onFailedEngine(String reason, @Nullable Exception e) { // we don't need to notify anybody in this test } }; diff --git a/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingDisabledTests.java b/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingDisabledTests.java index f9fb5e77b70..9a8815e9398 100644 --- a/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingDisabledTests.java +++ b/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingDisabledTests.java @@ -19,7 +19,6 @@ package org.elasticsearch.index.mapper; -import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; @@ -116,7 +115,7 @@ public class DynamicMappingDisabledTests extends ESSingleNodeTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { onFailureCalled.set(true); assertThat(e, instanceOf(IndexNotFoundException.class)); assertEquals(e.getMessage(), "no such index"); diff --git a/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingIntegrationIT.java b/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingIntegrationIT.java index 8afdea27451..71628c06128 100644 --- a/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingIntegrationIT.java +++ b/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingIntegrationIT.java @@ -96,8 +96,8 @@ public class DynamicMappingIntegrationIT extends ESIntegTestCase { try { startLatch.await(); assertTrue(client().prepareIndex("index", "type", id).setSource("field" + id, "bar").get().isCreated()); - } catch (Throwable t) { - error.compareAndSet(null, t); + } catch (Exception e) { + error.compareAndSet(null, e); } } }); diff --git a/core/src/test/java/org/elasticsearch/index/mapper/MapperServiceTests.java b/core/src/test/java/org/elasticsearch/index/mapper/MapperServiceTests.java index c93c181f860..2afeb02499d 100644 --- a/core/src/test/java/org/elasticsearch/index/mapper/MapperServiceTests.java +++ b/core/src/test/java/org/elasticsearch/index/mapper/MapperServiceTests.java @@ -103,7 +103,7 @@ public class MapperServiceTests extends ESSingleNodeTestCase { // 2. already existing index IndexService indexService = createIndex("index2"); - expectThrows(ExecutionException.class, () -> { + e = expectThrows(ExecutionException.class, () -> { client().prepareIndex("index1", MapperService.DEFAULT_MAPPING, "2").setSource().execute().get(); }); throwable = ExceptionsHelper.unwrapCause(e.getCause()); diff --git a/core/src/test/java/org/elasticsearch/index/mapper/merge/TestMergeMapperTests.java b/core/src/test/java/org/elasticsearch/index/mapper/merge/TestMergeMapperTests.java index 627f268545a..0133d3e5943 100644 --- a/core/src/test/java/org/elasticsearch/index/mapper/merge/TestMergeMapperTests.java +++ b/core/src/test/java/org/elasticsearch/index/mapper/merge/TestMergeMapperTests.java @@ -159,7 +159,7 @@ public class TestMergeMapperTests extends ESSingleNodeTestCase { final AtomicBoolean stopped = new AtomicBoolean(false); final CyclicBarrier barrier = new CyclicBarrier(2); final AtomicReference lastIntroducedFieldName = new AtomicReference<>(); - final AtomicReference error = new AtomicReference<>(); + final AtomicReference error = new AtomicReference<>(); final Thread updater = new Thread() { @Override public void run() { @@ -173,8 +173,8 @@ public class TestMergeMapperTests extends ESSingleNodeTestCase { lastIntroducedFieldName.set(fieldName); mapperService.merge("test", new CompressedXContent(update.toString()), MapperService.MergeReason.MAPPING_UPDATE, false); } - } catch (Throwable t) { - error.set(t); + } catch (Exception e) { + error.set(e); } finally { stopped.set(true); } diff --git a/core/src/test/java/org/elasticsearch/index/replication/ESIndexLevelReplicationTestCase.java b/core/src/test/java/org/elasticsearch/index/replication/ESIndexLevelReplicationTestCase.java index 1191806bc8e..1c6a973192a 100644 --- a/core/src/test/java/org/elasticsearch/index/replication/ESIndexLevelReplicationTestCase.java +++ b/core/src/test/java/org/elasticsearch/index/replication/ESIndexLevelReplicationTestCase.java @@ -408,7 +408,7 @@ public abstract class ESIndexLevelReplicationTestCase extends ESTestCase { } @Override - public void failShard(String message, Throwable throwable) { + public void failShard(String message, Exception exception) { throw new UnsupportedOperationException(); } @@ -436,14 +436,14 @@ public abstract class ESIndexLevelReplicationTestCase extends ESTestCase { .filter(s -> replicaRouting.isSameAllocation(s.routingEntry())).findFirst().get(); TransportIndexAction.executeIndexRequestOnReplica(request, replica); listener.onResponse(TransportResponse.Empty.INSTANCE); - } catch (Throwable t) { + } catch (Exception t) { listener.onFailure(t); } } @Override - public void failShard(ShardRouting replica, ShardRouting primary, String message, Throwable throwable, Runnable onSuccess, - Consumer onPrimaryDemoted, Consumer onIgnoredFailure) { + public void failShard(ShardRouting replica, ShardRouting primary, String message, Exception exception, Runnable onSuccess, + Consumer onPrimaryDemoted, Consumer onIgnoredFailure) { throw new UnsupportedOperationException(); } } diff --git a/core/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java b/core/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java index 6674d6859ab..9bc49ad626e 100644 --- a/core/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java +++ b/core/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java @@ -725,7 +725,7 @@ public class IndexShardTests extends ESSingleNodeTestCase { } @Override - public void postIndex(Engine.Index index, Throwable ex) { + public void postIndex(Engine.Index index, Exception ex) { postIndexException.incrementAndGet(); } @@ -741,7 +741,7 @@ public class IndexShardTests extends ESSingleNodeTestCase { } @Override - public void postDelete(Engine.Delete delete, Throwable ex) { + public void postDelete(Engine.Delete delete, Exception ex) { postDeleteException.incrementAndGet(); } @@ -1383,7 +1383,7 @@ public class IndexShardTests extends ESSingleNodeTestCase { IndexSearcherWrapper wrapper = new IndexSearcherWrapper() {}; shard.close("simon says", false); AtomicReference shardRef = new AtomicReference<>(); - List failures = new ArrayList<>(); + List failures = new ArrayList<>(); IndexingOperationListener listener = new IndexingOperationListener() { @Override @@ -1393,9 +1393,9 @@ public class IndexShardTests extends ESSingleNodeTestCase { // this is all IMC needs to do - check current memory and refresh assertTrue(shardRef.get().getIndexBufferRAMBytesUsed() > 0); shardRef.get().refresh("test"); - } catch (Throwable t) { - failures.add(t); - throw t; + } catch (Exception e) { + failures.add(e); + throw e; } } @@ -1407,9 +1407,9 @@ public class IndexShardTests extends ESSingleNodeTestCase { // this is all IMC needs to do - check current memory and refresh assertTrue(shardRef.get().getIndexBufferRAMBytesUsed() > 0); shardRef.get().refresh("test"); - } catch (Throwable t) { - failures.add(t); - throw t; + } catch (Exception e) { + failures.add(e); + throw e; } } }; diff --git a/core/src/test/java/org/elasticsearch/index/shard/IndexingOperationListenerTests.java b/core/src/test/java/org/elasticsearch/index/shard/IndexingOperationListenerTests.java index 8d86e64a391..d1cf8b32f58 100644 --- a/core/src/test/java/org/elasticsearch/index/shard/IndexingOperationListenerTests.java +++ b/core/src/test/java/org/elasticsearch/index/shard/IndexingOperationListenerTests.java @@ -51,7 +51,7 @@ public class IndexingOperationListenerTests extends ESTestCase{ } @Override - public void postIndex(Engine.Index index, Throwable ex) { + public void postIndex(Engine.Index index, Exception ex) { postIndexException.incrementAndGet(); } @@ -67,7 +67,7 @@ public class IndexingOperationListenerTests extends ESTestCase{ } @Override - public void postDelete(Engine.Delete delete, Throwable ex) { + public void postDelete(Engine.Delete delete, Exception ex) { postDeleteException.incrementAndGet(); } }; @@ -83,7 +83,7 @@ public class IndexingOperationListenerTests extends ESTestCase{ throw new RuntimeException(); } @Override - public void postIndex(Engine.Index index, Throwable ex) { + public void postIndex(Engine.Index index, Exception ex) { throw new RuntimeException(); } @Override @@ -96,7 +96,7 @@ public class IndexingOperationListenerTests extends ESTestCase{ throw new RuntimeException(); } @Override - public void postDelete(Engine.Delete delete, Throwable ex) { + public void postDelete(Engine.Delete delete, Exception ex) { throw new RuntimeException(); } }; diff --git a/core/src/test/java/org/elasticsearch/index/shard/RefreshListenersTests.java b/core/src/test/java/org/elasticsearch/index/shard/RefreshListenersTests.java index 4938f686f60..79b0773481e 100644 --- a/core/src/test/java/org/elasticsearch/index/shard/RefreshListenersTests.java +++ b/core/src/test/java/org/elasticsearch/index/shard/RefreshListenersTests.java @@ -115,7 +115,7 @@ public class RefreshListenersTests extends ESTestCase { BigArrays.NON_RECYCLING_INSTANCE); Engine.EventListener eventListener = new Engine.EventListener() { @Override - public void onFailedEngine(String reason, @Nullable Throwable t) { + public void onFailedEngine(String reason, @Nullable Exception e) { // we don't need to notify anybody in this test } }; @@ -251,7 +251,7 @@ public class RefreshListenersTests extends ESTestCase { getResult.docIdAndVersion().context.reader().document(getResult.docIdAndVersion().docId, visitor); assertEquals(Arrays.asList(testFieldValue), visitor.fields().get("test")); } - } catch (Throwable t) { + } catch (Exception t) { throw new RuntimeException("failure on the [" + iteration + "] iteration of thread [" + threadId + "]", t); } } @@ -279,7 +279,7 @@ public class RefreshListenersTests extends ESTestCase { document.add(uidField); document.add(versionField); BytesReference source = new BytesArray(new byte[] { 1 }); - ParsedDocument doc = new ParsedDocument(versionField, id, type, null, -1, -1, Arrays.asList(document), source, null); + ParsedDocument doc = new ParsedDocument(versionField, id, type, null, -1, -1, Arrays.asList(document), source, null); Engine.Index index = new Engine.Index(new Term("_uid", uid), doc); engine.index(index); return index; @@ -290,7 +290,7 @@ public class RefreshListenersTests extends ESTestCase { * When the listener is called this captures it's only argument. */ AtomicReference forcedRefresh = new AtomicReference<>(); - private volatile Throwable error; + private volatile Exception error; @Override public void accept(Boolean forcedRefresh) { @@ -298,7 +298,7 @@ public class RefreshListenersTests extends ESTestCase { assertNotNull(forcedRefresh); Boolean oldValue = this.forcedRefresh.getAndSet(forcedRefresh); assertNull("Listener called twice", oldValue); - } catch (Throwable e) { + } catch (Exception e) { error = e; } } diff --git a/core/src/test/java/org/elasticsearch/index/store/CorruptedFileIT.java b/core/src/test/java/org/elasticsearch/index/store/CorruptedFileIT.java index 84d50c6620f..eb70069b0b7 100644 --- a/core/src/test/java/org/elasticsearch/index/store/CorruptedFileIT.java +++ b/core/src/test/java/org/elasticsearch/index/store/CorruptedFileIT.java @@ -193,7 +193,7 @@ public class CorruptedFileIT extends ESIntegTestCase { * run the checkindex. if the corruption is still there we will catch it. */ final CountDownLatch latch = new CountDownLatch(numShards * 3); // primary + 2 replicas - final CopyOnWriteArrayList exception = new CopyOnWriteArrayList<>(); + final CopyOnWriteArrayList exception = new CopyOnWriteArrayList<>(); final IndexEventListener listener = new IndexEventListener() { @Override public void afterIndexShardClosed(ShardId sid, @Nullable IndexShard indexShard, Settings indexSettings) { @@ -215,8 +215,8 @@ public class CorruptedFileIT extends ESIntegTestCase { throw new IOException("index check failure"); } } - } catch (Throwable t) { - exception.add(t); + } catch (Exception e) { + exception.add(e); } finally { store.decRef(); latch.countDown(); diff --git a/core/src/test/java/org/elasticsearch/index/translog/TranslogTests.java b/core/src/test/java/org/elasticsearch/index/translog/TranslogTests.java index 01eead9c96b..c9b3daa806a 100644 --- a/core/src/test/java/org/elasticsearch/index/translog/TranslogTests.java +++ b/core/src/test/java/org/elasticsearch/index/translog/TranslogTests.java @@ -20,7 +20,6 @@ package org.elasticsearch.index.translog; import com.carrotsearch.randomizedtesting.generators.RandomPicks; - import org.apache.lucene.codecs.CodecUtil; import org.apache.lucene.index.Term; import org.apache.lucene.mockfile.FilterFileChannel; @@ -456,7 +455,7 @@ public class TranslogTests extends ESTestCase { final BlockingQueue writtenOperations = new ArrayBlockingQueue<>(threadCount * opsPerThread); Thread[] threads = new Thread[threadCount]; - final Throwable[] threadExceptions = new Throwable[threadCount]; + final Exception[] threadExceptions = new Exception[threadCount]; final CountDownLatch downLatch = new CountDownLatch(1); for (int i = 0; i < threadCount; i++) { final int threadId = i; @@ -624,7 +623,7 @@ public class TranslogTests extends ESTestCase { final AtomicBoolean run = new AtomicBoolean(true); // any errors on threads - final List errors = new CopyOnWriteArrayList<>(); + final List errors = new CopyOnWriteArrayList<>(); logger.debug("using [{}] readers. [{}] writers. flushing every ~[{}] ops.", readers.length, writers.length, flushEveryOps); for (int i = 0; i < writers.length; i++) { final String threadName = "writer_" + i; @@ -663,9 +662,9 @@ public class TranslogTests extends ESTestCase { } @Override - public void onFailure(Throwable t) { - logger.error("--> writer [{}] had an error", t, threadName); - errors.add(t); + public void onFailure(Exception e) { + logger.error("--> writer [{}] had an error", e, threadName); + errors.add(e); } }, threadName); writers[i].start(); @@ -678,14 +677,14 @@ public class TranslogTests extends ESTestCase { Set writtenOpsAtView; @Override - public void onFailure(Throwable t) { - logger.error("--> reader [{}] had an error", t, threadId); - errors.add(t); + public void onFailure(Exception e) { + logger.error("--> reader [{}] had an error", e, threadId); + errors.add(e); try { closeView(); - } catch (IOException e) { - logger.error("unexpected error while closing view, after failure"); - t.addSuppressed(e); + } catch (IOException inner) { + inner.addSuppressed(e); + logger.error("unexpected error while closing view, after failure", inner); } } @@ -1240,7 +1239,7 @@ public class TranslogTests extends ESTestCase { final BlockingQueue writtenOperations = new ArrayBlockingQueue<>(threadCount * opsPerThread); Thread[] threads = new Thread[threadCount]; - final Throwable[] threadExceptions = new Throwable[threadCount]; + final Exception[] threadExceptions = new Exception[threadCount]; final CountDownLatch downLatch = new CountDownLatch(1); for (int i = 0; i < threadCount; i++) { final int threadId = i; @@ -1267,10 +1266,10 @@ public class TranslogTests extends ESTestCase { private final int opsPerThread; private final int threadId; private final Collection writtenOperations; - private final Throwable[] threadExceptions; + private final Exception[] threadExceptions; private final Translog translog; - public TranslogThread(Translog translog, CountDownLatch downLatch, int opsPerThread, int threadId, Collection writtenOperations, Throwable[] threadExceptions) { + public TranslogThread(Translog translog, CountDownLatch downLatch, int opsPerThread, int threadId, Collection writtenOperations, Exception[] threadExceptions) { this.translog = translog; this.downLatch = downLatch; this.opsPerThread = opsPerThread; @@ -1304,7 +1303,7 @@ public class TranslogTests extends ESTestCase { writtenOperations.add(new LocationOperation(op, loc)); afterAdd(); } - } catch (Throwable t) { + } catch (Exception t) { threadExceptions[threadId] = t; } } @@ -1446,7 +1445,7 @@ public class TranslogTests extends ESTestCase { final int threadCount = randomIntBetween(1, 5); Thread[] threads = new Thread[threadCount]; - final Throwable[] threadExceptions = new Throwable[threadCount]; + final Exception[] threadExceptions = new Exception[threadCount]; final CountDownLatch downLatch = new CountDownLatch(1); final CountDownLatch added = new CountDownLatch(randomIntBetween(10, 100)); List writtenOperations = Collections.synchronizedList(new ArrayList<>()); diff --git a/core/src/test/java/org/elasticsearch/indexing/IndexActionIT.java b/core/src/test/java/org/elasticsearch/indexing/IndexActionIT.java index 23925f574ff..60e062c0d1c 100644 --- a/core/src/test/java/org/elasticsearch/indexing/IndexActionIT.java +++ b/core/src/test/java/org/elasticsearch/indexing/IndexActionIT.java @@ -50,7 +50,7 @@ public class IndexActionIT extends ESIntegTestCase { public void testAutoGenerateIdNoDuplicates() throws Exception { int numberOfIterations = scaledRandomIntBetween(10, 50); for (int i = 0; i < numberOfIterations; i++) { - Throwable firstError = null; + Exception firstError = null; createIndex("test"); int numOfDocs = randomIntBetween(10, 100); logger.info("indexing [{}] docs", numOfDocs); @@ -66,19 +66,19 @@ public class IndexActionIT extends ESIntegTestCase { try { logger.debug("running search with all types"); assertHitCount(client().prepareSearch("test").get(), numOfDocs); - } catch (Throwable t) { - logger.error("search for all docs types failed", t); + } catch (Exception e) { + logger.error("search for all docs types failed", e); if (firstError == null) { - firstError = t; + firstError = e; } } try { logger.debug("running search with a specific type"); assertHitCount(client().prepareSearch("test").setTypes("type").get(), numOfDocs); - } catch (Throwable t) { - logger.error("search for all docs of a specific type failed", t); + } catch (Exception e) { + logger.error("search for all docs of a specific type failed", e); if (firstError == null) { - firstError = t; + firstError = e; } } } diff --git a/core/src/test/java/org/elasticsearch/indices/analyze/AnalyzeActionIT.java b/core/src/test/java/org/elasticsearch/indices/analyze/AnalyzeActionIT.java index 4312dd6105e..5e636bed939 100644 --- a/core/src/test/java/org/elasticsearch/indices/analyze/AnalyzeActionIT.java +++ b/core/src/test/java/org/elasticsearch/indices/analyze/AnalyzeActionIT.java @@ -456,9 +456,9 @@ public class AnalyzeActionIT extends ESIntegTestCase { .setAnalyzer("not_exist_analyzer") .get(); fail("shouldn't get here"); - } catch (Throwable t) { - assertThat(t, instanceOf(IllegalArgumentException.class)); - assertThat(t.getMessage(), startsWith("failed to find global analyzer")); + } catch (Exception e) { + assertThat(e, instanceOf(IllegalArgumentException.class)); + assertThat(e.getMessage(), startsWith("failed to find global analyzer")); } diff --git a/core/src/test/java/org/elasticsearch/indices/flush/FlushIT.java b/core/src/test/java/org/elasticsearch/indices/flush/FlushIT.java index 8c724efdfc7..5f7f26cd38c 100644 --- a/core/src/test/java/org/elasticsearch/indices/flush/FlushIT.java +++ b/core/src/test/java/org/elasticsearch/indices/flush/FlushIT.java @@ -68,14 +68,14 @@ public class FlushIT extends ESIntegTestCase { // don't use assertAllSuccessful it uses a randomized context that belongs to a different thread assertThat("Unexpected ShardFailures: " + Arrays.toString(flushResponse.getShardFailures()), flushResponse.getFailedShards(), equalTo(0)); latch.countDown(); - } catch (Throwable ex) { + } catch (Exception ex) { onFailure(ex); } } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { errors.add(e); latch.countDown(); } diff --git a/core/src/test/java/org/elasticsearch/indices/flush/SyncedFlushUtil.java b/core/src/test/java/org/elasticsearch/indices/flush/SyncedFlushUtil.java index 485ec020c3f..b71ba63a157 100644 --- a/core/src/test/java/org/elasticsearch/indices/flush/SyncedFlushUtil.java +++ b/core/src/test/java/org/elasticsearch/indices/flush/SyncedFlushUtil.java @@ -57,7 +57,7 @@ public class SyncedFlushUtil { public static final class LatchedListener implements ActionListener { public volatile T result; - public volatile Throwable error; + public volatile Exception error; public final CountDownLatch latch = new CountDownLatch(1); @Override @@ -67,7 +67,7 @@ public class SyncedFlushUtil { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { error = e; latch.countDown(); } diff --git a/core/src/test/java/org/elasticsearch/indices/mapping/ConcurrentDynamicTemplateIT.java b/core/src/test/java/org/elasticsearch/indices/mapping/ConcurrentDynamicTemplateIT.java index 2981f2d110c..eeaeb84d9a9 100644 --- a/core/src/test/java/org/elasticsearch/indices/mapping/ConcurrentDynamicTemplateIT.java +++ b/core/src/test/java/org/elasticsearch/indices/mapping/ConcurrentDynamicTemplateIT.java @@ -69,7 +69,7 @@ public class ConcurrentDynamicTemplateIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { throwable.add(e); latch.countDown(); } @@ -83,4 +83,4 @@ public class ConcurrentDynamicTemplateIT extends ESIntegTestCase { } } -} \ No newline at end of file +} diff --git a/core/src/test/java/org/elasticsearch/indices/mapping/UpdateMappingIntegrationIT.java b/core/src/test/java/org/elasticsearch/indices/mapping/UpdateMappingIntegrationIT.java index 68a176e22c3..91fd7bb972b 100644 --- a/core/src/test/java/org/elasticsearch/indices/mapping/UpdateMappingIntegrationIT.java +++ b/core/src/test/java/org/elasticsearch/indices/mapping/UpdateMappingIntegrationIT.java @@ -43,6 +43,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_BLOCKS_METADATA; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_BLOCKS_READ; @@ -258,7 +259,7 @@ public class UpdateMappingIntegrationIT extends ESIntegTestCase { // not all shards are allocated with the initial create index. Wait for it.. ensureYellow(); - final Throwable[] threadException = new Throwable[1]; + final AtomicReference threadException = new AtomicReference<>(); final AtomicBoolean stop = new AtomicBoolean(false); Thread[] threads = new Thread[3]; final CyclicBarrier barrier = new CyclicBarrier(threads.length); @@ -298,8 +299,8 @@ public class UpdateMappingIntegrationIT extends ESIntegTestCase { assertThat(mappings.containsKey(typeName), equalTo(true)); assertThat(((Map) mappings.get(typeName).getSourceAsMap().get("properties")).keySet(), Matchers.hasItem(fieldName)); } - } catch (Throwable t) { - threadException[0] = t; + } catch (Exception e) { + threadException.set(e); stop.set(true); } } @@ -311,8 +312,8 @@ public class UpdateMappingIntegrationIT extends ESIntegTestCase { for (Thread t : threads) t.join(); - if (threadException[0] != null) { - throw threadException[0]; + if (threadException.get() != null) { + throw threadException.get(); } } diff --git a/core/src/test/java/org/elasticsearch/indices/recovery/RecoveryTargetTests.java b/core/src/test/java/org/elasticsearch/indices/recovery/RecoveryTargetTests.java index bcd614121b6..c59eea6af6d 100644 --- a/core/src/test/java/org/elasticsearch/indices/recovery/RecoveryTargetTests.java +++ b/core/src/test/java/org/elasticsearch/indices/recovery/RecoveryTargetTests.java @@ -59,7 +59,7 @@ public class RecoveryTargetTests extends ESTestCase { private T lastRead; private final AtomicBoolean shouldStop; private final T source; - final AtomicReference error = new AtomicReference<>(); + final AtomicReference error = new AtomicReference<>(); final Version streamVersion; Streamer(AtomicBoolean shouldStop, T source) { @@ -73,7 +73,7 @@ public class RecoveryTargetTests extends ESTestCase { } public T lastRead() throws Throwable { - Throwable t = error.get(); + Exception t = error.get(); if (t != null) { throw t; } @@ -105,8 +105,8 @@ public class RecoveryTargetTests extends ESTestCase { serializeDeserialize(); } serializeDeserialize(); - } catch (Throwable t) { - error.set(t); + } catch (Exception e) { + error.set(e); } } } diff --git a/core/src/test/java/org/elasticsearch/indices/state/RareClusterStateIT.java b/core/src/test/java/org/elasticsearch/indices/state/RareClusterStateIT.java index 81c50cc4f9c..a5b8bf63422 100644 --- a/core/src/test/java/org/elasticsearch/indices/state/RareClusterStateIT.java +++ b/core/src/test/java/org/elasticsearch/indices/state/RareClusterStateIT.java @@ -145,7 +145,7 @@ public class RareClusterStateIT extends ESIntegTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { } }); @@ -165,7 +165,7 @@ public class RareClusterStateIT extends ESIntegTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { } }); @@ -260,7 +260,7 @@ public class RareClusterStateIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { putMappingResponse.set(e); } }); @@ -292,7 +292,7 @@ public class RareClusterStateIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { docIndexResponse.set(e); } }); @@ -376,7 +376,7 @@ public class RareClusterStateIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { putMappingResponse.set(e); } }); @@ -403,7 +403,7 @@ public class RareClusterStateIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { docIndexResponse.set(e); } }); diff --git a/core/src/test/java/org/elasticsearch/indices/store/IndicesStoreIntegrationIT.java b/core/src/test/java/org/elasticsearch/indices/store/IndicesStoreIntegrationIT.java index b4f66c2e17b..ad26ec71226 100644 --- a/core/src/test/java/org/elasticsearch/indices/store/IndicesStoreIntegrationIT.java +++ b/core/src/test/java/org/elasticsearch/indices/store/IndicesStoreIntegrationIT.java @@ -426,7 +426,7 @@ public class IndicesStoreIntegrationIT extends ESIntegTestCase { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { } }); waitNoPendingTasksOnAll(); diff --git a/core/src/test/java/org/elasticsearch/ingest/PipelineExecutionServiceTests.java b/core/src/test/java/org/elasticsearch/ingest/PipelineExecutionServiceTests.java index fcc6e04c6c1..53964132abe 100644 --- a/core/src/test/java/org/elasticsearch/ingest/PipelineExecutionServiceTests.java +++ b/core/src/test/java/org/elasticsearch/ingest/PipelineExecutionServiceTests.java @@ -74,7 +74,7 @@ public class PipelineExecutionServiceTests extends ESTestCase { public void testExecuteIndexPipelineDoesNotExist() { IndexRequest indexRequest = new IndexRequest("_index", "_type", "_id").source(Collections.emptyMap()).setPipeline("_id"); @SuppressWarnings("unchecked") - Consumer failureHandler = mock(Consumer.class); + Consumer failureHandler = mock(Consumer.class); @SuppressWarnings("unchecked") Consumer completionHandler = mock(Consumer.class); try { @@ -83,7 +83,7 @@ public class PipelineExecutionServiceTests extends ESTestCase { } catch (IllegalArgumentException e) { assertThat(e.getMessage(), equalTo("pipeline with id [_id] does not exist")); } - verify(failureHandler, never()).accept(any(Throwable.class)); + verify(failureHandler, never()).accept(any(Exception.class)); verify(completionHandler, never()).accept(anyBoolean()); } @@ -98,9 +98,9 @@ public class PipelineExecutionServiceTests extends ESTestCase { new IndexRequest("_index", "_type", "_id").source(Collections.emptyMap()).setPipeline("does_not_exist"); bulkRequest.add(indexRequest2); @SuppressWarnings("unchecked") - BiConsumer failureHandler = mock(BiConsumer.class); + BiConsumer failureHandler = mock(BiConsumer.class); @SuppressWarnings("unchecked") - Consumer completionHandler = mock(Consumer.class); + Consumer completionHandler = mock(Consumer.class); executionService.executeBulkRequest(bulkRequest.requests(), failureHandler, completionHandler); verify(failureHandler, times(1)).accept( argThat(new CustomTypeSafeMatcher("failure handler was not called with the expected arguments") { @@ -126,7 +126,7 @@ public class PipelineExecutionServiceTests extends ESTestCase { IndexRequest indexRequest = new IndexRequest("_index", "_type", "_id").source(Collections.emptyMap()).setPipeline("_id"); @SuppressWarnings("unchecked") - Consumer failureHandler = mock(Consumer.class); + Consumer failureHandler = mock(Consumer.class); @SuppressWarnings("unchecked") Consumer completionHandler = mock(Consumer.class); executionService.executeIndexRequest(indexRequest, failureHandler, completionHandler); @@ -141,7 +141,7 @@ public class PipelineExecutionServiceTests extends ESTestCase { IndexRequest indexRequest = new IndexRequest("_index", "_type", "_id").source(Collections.emptyMap()).setPipeline("_id"); @SuppressWarnings("unchecked") - Consumer failureHandler = mock(Consumer.class); + Consumer failureHandler = mock(Consumer.class); @SuppressWarnings("unchecked") Consumer completionHandler = mock(Consumer.class); executionService.executeIndexRequest(indexRequest, failureHandler, completionHandler); @@ -169,7 +169,7 @@ public class PipelineExecutionServiceTests extends ESTestCase { IndexRequest indexRequest = new IndexRequest("_index", "_type", "_id").source(Collections.emptyMap()).setPipeline("_id"); @SuppressWarnings("unchecked") - Consumer failureHandler = mock(Consumer.class); + Consumer failureHandler = mock(Consumer.class); @SuppressWarnings("unchecked") Consumer completionHandler = mock(Consumer.class); executionService.executeIndexRequest(indexRequest, failureHandler, completionHandler); @@ -193,7 +193,7 @@ public class PipelineExecutionServiceTests extends ESTestCase { IndexRequest indexRequest = new IndexRequest("_index", "_type", "_id").source(Collections.emptyMap()).setPipeline("_id"); doThrow(new RuntimeException()).when(processor).execute(eqID("_index", "_type", "_id", Collections.emptyMap())); @SuppressWarnings("unchecked") - Consumer failureHandler = mock(Consumer.class); + Consumer failureHandler = mock(Consumer.class); @SuppressWarnings("unchecked") Consumer completionHandler = mock(Consumer.class); executionService.executeIndexRequest(indexRequest, failureHandler, completionHandler); @@ -213,7 +213,7 @@ public class PipelineExecutionServiceTests extends ESTestCase { IndexRequest indexRequest = new IndexRequest("_index", "_type", "_id").source(Collections.emptyMap()).setPipeline("_id"); doThrow(new RuntimeException()).when(processor).execute(eqID("_index", "_type", "_id", Collections.emptyMap())); @SuppressWarnings("unchecked") - Consumer failureHandler = mock(Consumer.class); + Consumer failureHandler = mock(Consumer.class); @SuppressWarnings("unchecked") Consumer completionHandler = mock(Consumer.class); executionService.executeIndexRequest(indexRequest, failureHandler, completionHandler); @@ -231,7 +231,7 @@ public class PipelineExecutionServiceTests extends ESTestCase { doThrow(new RuntimeException()).when(processor).execute(eqID("_index", "_type", "_id", Collections.emptyMap())); doThrow(new RuntimeException()).when(onFailureProcessor).execute(eqID("_index", "_type", "_id", Collections.emptyMap())); @SuppressWarnings("unchecked") - Consumer failureHandler = mock(Consumer.class); + Consumer failureHandler = mock(Consumer.class); @SuppressWarnings("unchecked") Consumer completionHandler = mock(Consumer.class); executionService.executeIndexRequest(indexRequest, failureHandler, completionHandler); @@ -253,7 +253,7 @@ public class PipelineExecutionServiceTests extends ESTestCase { doThrow(new RuntimeException()).when(onFailureProcessor).execute(eqID("_index", "_type", "_id", Collections.emptyMap())); doThrow(new RuntimeException()).when(processor).execute(eqID("_index", "_type", "_id", Collections.emptyMap())); @SuppressWarnings("unchecked") - Consumer failureHandler = mock(Consumer.class); + Consumer failureHandler = mock(Consumer.class); @SuppressWarnings("unchecked") Consumer completionHandler = mock(Consumer.class); executionService.executeIndexRequest(indexRequest, failureHandler, completionHandler); @@ -268,7 +268,7 @@ public class PipelineExecutionServiceTests extends ESTestCase { IndexRequest indexRequest = new IndexRequest("_index", "_type", "_id").source(Collections.emptyMap()).setPipeline("_id"); @SuppressWarnings("unchecked") - Consumer failureHandler = mock(Consumer.class); + Consumer failureHandler = mock(Consumer.class); @SuppressWarnings("unchecked") Consumer completionHandler = mock(Consumer.class); executionService.executeIndexRequest(indexRequest, failureHandler, completionHandler); @@ -284,7 +284,7 @@ public class PipelineExecutionServiceTests extends ESTestCase { IndexRequest indexRequest = new IndexRequest("_index", "_type", "_id").source(Collections.emptyMap()).setPipeline("_id"); @SuppressWarnings("unchecked") - Consumer failureHandler = mock(Consumer.class); + Consumer failureHandler = mock(Consumer.class); @SuppressWarnings("unchecked") Consumer completionHandler = mock(Consumer.class); executionService.executeIndexRequest(indexRequest, failureHandler, completionHandler); @@ -298,7 +298,7 @@ public class PipelineExecutionServiceTests extends ESTestCase { IndexRequest indexRequest = new IndexRequest("_index", "_type", "_id").setPipeline("_id") .source(Collections.emptyMap()) .ttl(1000L); - Consumer failureHandler = mock(Consumer.class); + Consumer failureHandler = mock(Consumer.class); Consumer completionHandler = mock(Consumer.class); executionService.executeIndexRequest(indexRequest, failureHandler, completionHandler); @@ -336,8 +336,8 @@ public class PipelineExecutionServiceTests extends ESTestCase { doThrow(error).when(processor).execute(any()); when(store.get(pipelineId)).thenReturn(new Pipeline(pipelineId, null, processor)); - BiConsumer requestItemErrorHandler = mock(BiConsumer.class); - Consumer completionHandler = mock(Consumer.class); + BiConsumer requestItemErrorHandler = mock(BiConsumer.class); + Consumer completionHandler = mock(Consumer.class); executionService.executeBulkRequest(bulkRequest.requests(), requestItemErrorHandler, completionHandler); verify(requestItemErrorHandler, times(numIndexRequests)).accept(any(IndexRequest.class), eq(error)); @@ -358,9 +358,9 @@ public class PipelineExecutionServiceTests extends ESTestCase { when(store.get(pipelineId)).thenReturn(new Pipeline(pipelineId, null, new CompoundProcessor())); @SuppressWarnings("unchecked") - BiConsumer requestItemErrorHandler = mock(BiConsumer.class); + BiConsumer requestItemErrorHandler = mock(BiConsumer.class); @SuppressWarnings("unchecked") - Consumer completionHandler = mock(Consumer.class); + Consumer completionHandler = mock(Consumer.class); executionService.executeBulkRequest(bulkRequest.requests(), requestItemErrorHandler, completionHandler); verify(requestItemErrorHandler, never()).accept(any(), any()); @@ -383,7 +383,7 @@ public class PipelineExecutionServiceTests extends ESTestCase { configurationMap.put("_id2", new PipelineConfiguration("_id2", new BytesArray("{}"))); executionService.updatePipelineStats(new IngestMetadata(configurationMap)); - Consumer failureHandler = mock(Consumer.class); + Consumer failureHandler = mock(Consumer.class); Consumer completionHandler = mock(Consumer.class); IndexRequest indexRequest = new IndexRequest("_index"); diff --git a/core/src/test/java/org/elasticsearch/monitor/jvm/JvmGcMonitorServiceSettingsTests.java b/core/src/test/java/org/elasticsearch/monitor/jvm/JvmGcMonitorServiceSettingsTests.java index a1f4d381911..94a56d11933 100644 --- a/core/src/test/java/org/elasticsearch/monitor/jvm/JvmGcMonitorServiceSettingsTests.java +++ b/core/src/test/java/org/elasticsearch/monitor/jvm/JvmGcMonitorServiceSettingsTests.java @@ -54,9 +54,9 @@ public class JvmGcMonitorServiceSettingsTests extends ESTestCase { public void testNegativeSetting() throws InterruptedException { String collector = randomAsciiOfLength(5); Settings settings = Settings.builder().put("monitor.jvm.gc.collector." + collector + ".warn", "-" + randomTimeValue()).build(); - execute(settings, (command, interval) -> null, t -> { - assertThat(t, instanceOf(IllegalArgumentException.class)); - assertThat(t.getMessage(), allOf(containsString("invalid gc_threshold"), containsString("for [monitor.jvm.gc.collector." + collector + "."))); + execute(settings, (command, interval) -> null, e -> { + assertThat(e, instanceOf(IllegalArgumentException.class)); + assertThat(e.getMessage(), allOf(containsString("invalid gc_threshold"), containsString("for [monitor.jvm.gc.collector." + collector + "."))); }, true, null); } @@ -74,9 +74,9 @@ public class JvmGcMonitorServiceSettingsTests extends ESTestCase { } // we should get an exception that a setting is missing - execute(builder.build(), (command, interval) -> null, t -> { - assertThat(t, instanceOf(IllegalArgumentException.class)); - assertThat(t.getMessage(), containsString("missing gc_threshold for [monitor.jvm.gc.collector." + collector + ".")); + execute(builder.build(), (command, interval) -> null, e -> { + assertThat(e, instanceOf(IllegalArgumentException.class)); + assertThat(e.getMessage(), containsString("missing gc_threshold for [monitor.jvm.gc.collector." + collector + ".")); }, true, null); } @@ -84,18 +84,18 @@ public class JvmGcMonitorServiceSettingsTests extends ESTestCase { for (final String threshold : new String[] { "warn", "info", "debug" }) { final Settings.Builder builder = Settings.builder(); builder.put("monitor.jvm.gc.overhead." + threshold, randomIntBetween(Integer.MIN_VALUE, -1)); - execute(builder.build(), (command, interval) -> null, t -> { - assertThat(t, instanceOf(IllegalArgumentException.class)); - assertThat(t.getMessage(), containsString("setting [monitor.jvm.gc.overhead." + threshold + "] must be >= 0")); + execute(builder.build(), (command, interval) -> null, e -> { + assertThat(e, instanceOf(IllegalArgumentException.class)); + assertThat(e.getMessage(), containsString("setting [monitor.jvm.gc.overhead." + threshold + "] must be >= 0")); }, true, null); } for (final String threshold : new String[] { "warn", "info", "debug" }) { final Settings.Builder builder = Settings.builder(); builder.put("monitor.jvm.gc.overhead." + threshold, randomIntBetween(100 + 1, Integer.MAX_VALUE)); - execute(builder.build(), (command, interval) -> null, t -> { - assertThat(t, instanceOf(IllegalArgumentException.class)); - assertThat(t.getMessage(), containsString("setting [monitor.jvm.gc.overhead." + threshold + "] must be <= 100")); + execute(builder.build(), (command, interval) -> null, e -> { + assertThat(e, instanceOf(IllegalArgumentException.class)); + assertThat(e.getMessage(), containsString("setting [monitor.jvm.gc.overhead." + threshold + "] must be <= 100")); }, true, null); } @@ -104,9 +104,9 @@ public class JvmGcMonitorServiceSettingsTests extends ESTestCase { infoWarnOutOfOrderBuilder.put("monitor.jvm.gc.overhead.info", info); final int warn = randomIntBetween(1, info - 1); infoWarnOutOfOrderBuilder.put("monitor.jvm.gc.overhead.warn", warn); - execute(infoWarnOutOfOrderBuilder.build(), (command, interval) -> null, t -> { - assertThat(t, instanceOf(IllegalArgumentException.class)); - assertThat(t.getMessage(), containsString("[monitor.jvm.gc.overhead.warn] must be greater than [monitor.jvm.gc.overhead.info] [" + info + "] but was [" + warn + "]")); + execute(infoWarnOutOfOrderBuilder.build(), (command, interval) -> null, e -> { + assertThat(e, instanceOf(IllegalArgumentException.class)); + assertThat(e.getMessage(), containsString("[monitor.jvm.gc.overhead.warn] must be greater than [monitor.jvm.gc.overhead.info] [" + info + "] but was [" + warn + "]")); }, true, null); final Settings.Builder debugInfoOutOfOrderBuilder = Settings.builder(); @@ -114,9 +114,9 @@ public class JvmGcMonitorServiceSettingsTests extends ESTestCase { final int debug = randomIntBetween(info + 1, 99); debugInfoOutOfOrderBuilder.put("monitor.jvm.gc.overhead.debug", debug); debugInfoOutOfOrderBuilder.put("monitor.jvm.gc.overhead.warn", randomIntBetween(debug + 1, 100)); // or the test will fail for the wrong reason - execute(debugInfoOutOfOrderBuilder.build(), (command, interval) -> null, t -> { - assertThat(t, instanceOf(IllegalArgumentException.class)); - assertThat(t.getMessage(), containsString("[monitor.jvm.gc.overhead.info] must be greater than [monitor.jvm.gc.overhead.debug] [" + debug + "] but was [" + info + "]")); + execute(debugInfoOutOfOrderBuilder.build(), (command, interval) -> null, e -> { + assertThat(e, instanceOf(IllegalArgumentException.class)); + assertThat(e.getMessage(), containsString("[monitor.jvm.gc.overhead.info] must be greater than [monitor.jvm.gc.overhead.debug] [" + debug + "] but was [" + info + "]")); }, true, null); } @@ -124,7 +124,7 @@ public class JvmGcMonitorServiceSettingsTests extends ESTestCase { execute(settings, scheduler, null, false, asserts); } - private static void execute(Settings settings, BiFunction> scheduler, Consumer consumer, boolean constructionShouldFail, Runnable asserts) throws InterruptedException { + private static void execute(Settings settings, BiFunction> scheduler, Consumer consumer, boolean constructionShouldFail, Runnable asserts) throws InterruptedException { assert constructionShouldFail == (consumer != null); assert constructionShouldFail == (asserts == null); ThreadPool threadPool = null; @@ -143,7 +143,7 @@ public class JvmGcMonitorServiceSettingsTests extends ESTestCase { service.doStart(); asserts.run(); service.doStop(); - } catch (Throwable t) { + } catch (Exception t) { consumer.accept(t); } } finally { diff --git a/core/src/test/java/org/elasticsearch/monitor/jvm/JvmMonitorTests.java b/core/src/test/java/org/elasticsearch/monitor/jvm/JvmMonitorTests.java index 91862e9cd18..278a47ed21f 100644 --- a/core/src/test/java/org/elasticsearch/monitor/jvm/JvmMonitorTests.java +++ b/core/src/test/java/org/elasticsearch/monitor/jvm/JvmMonitorTests.java @@ -48,10 +48,10 @@ public class JvmMonitorTests extends ESTestCase { AtomicBoolean invoked = new AtomicBoolean(); JvmGcMonitorService.JvmMonitor monitor = new JvmGcMonitorService.JvmMonitor(Collections.emptyMap(), IGNORE) { @Override - void onMonitorFailure(Throwable t) { + void onMonitorFailure(Exception e) { invoked.set(true); - assertThat(t, instanceOf(RuntimeException.class)); - assertThat(t, hasToString(containsString("simulated"))); + assertThat(e, instanceOf(RuntimeException.class)); + assertThat(e, hasToString(containsString("simulated"))); } @Override @@ -174,7 +174,7 @@ public class JvmMonitorTests extends ESTestCase { JvmGcMonitorService.JvmMonitor monitor = new JvmGcMonitorService.JvmMonitor(gcThresholds, IGNORE) { @Override - void onMonitorFailure(Throwable t) { + void onMonitorFailure(Exception e) { } @Override @@ -284,7 +284,7 @@ public class JvmMonitorTests extends ESTestCase { final JvmGcMonitorService.JvmMonitor monitor = new JvmGcMonitorService.JvmMonitor(Collections.emptyMap(), IGNORE) { @Override - void onMonitorFailure(Throwable t) { + void onMonitorFailure(Exception e) { } @Override @@ -358,7 +358,7 @@ public class JvmMonitorTests extends ESTestCase { final JvmGcMonitorService.JvmMonitor monitor = new JvmGcMonitorService.JvmMonitor(Collections.emptyMap(), gcOverheadThreshold) { @Override - void onMonitorFailure(final Throwable t) { + void onMonitorFailure(final Exception e) { } @Override diff --git a/core/src/test/java/org/elasticsearch/rest/BytesRestResponseTests.java b/core/src/test/java/org/elasticsearch/rest/BytesRestResponseTests.java index 6bb1716cb0f..051159b448b 100644 --- a/core/src/test/java/org/elasticsearch/rest/BytesRestResponseTests.java +++ b/core/src/test/java/org/elasticsearch/rest/BytesRestResponseTests.java @@ -41,11 +41,16 @@ import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -/** - * - */ public class BytesRestResponseTests extends ESTestCase { + class UnknownException extends Exception { + + public UnknownException(final String message, final Throwable cause) { + super(message, cause); + } + + } + public void testWithHeaders() throws Exception { RestRequest request = new FakeRestRequest(); RestChannel channel = randomBoolean() ? new DetailedExceptionRestChannel(request) : new SimpleExceptionRestChannel(request); @@ -61,7 +66,7 @@ public class BytesRestResponseTests extends ESTestCase { RestRequest request = new FakeRestRequest(); RestChannel channel = new SimpleExceptionRestChannel(request); - Throwable t = new ElasticsearchException("an error occurred reading data", new FileNotFoundException("/foo/bar")); + Exception t = new ElasticsearchException("an error occurred reading data", new FileNotFoundException("/foo/bar")); BytesRestResponse response = new BytesRestResponse(channel, t); String text = response.content().utf8ToString(); assertThat(text, containsString("ElasticsearchException[an error occurred reading data]")); @@ -74,7 +79,7 @@ public class BytesRestResponseTests extends ESTestCase { RestRequest request = new FakeRestRequest(); RestChannel channel = new DetailedExceptionRestChannel(request); - Throwable t = new ElasticsearchException("an error occurred reading data", new FileNotFoundException("/foo/bar")); + Exception t = new ElasticsearchException("an error occurred reading data", new FileNotFoundException("/foo/bar")); BytesRestResponse response = new BytesRestResponse(channel, t); String text = response.content().utf8ToString(); assertThat(text, containsString("{\"type\":\"exception\",\"reason\":\"an error occurred reading data\"}")); @@ -85,10 +90,10 @@ public class BytesRestResponseTests extends ESTestCase { RestRequest request = new FakeRestRequest(); RestChannel channel = new SimpleExceptionRestChannel(request); - Throwable t = new Throwable("an error occurred reading data", new FileNotFoundException("/foo/bar")); + Exception t = new UnknownException("an error occurred reading data", new FileNotFoundException("/foo/bar")); BytesRestResponse response = new BytesRestResponse(channel, t); String text = response.content().utf8ToString(); - assertThat(text, not(containsString("Throwable[an error occurred reading data]"))); + assertThat(text, not(containsString("UnknownException[an error occurred reading data]"))); assertThat(text, not(containsString("FileNotFoundException[/foo/bar]"))); assertThat(text, not(containsString("error_trace"))); assertThat(text, containsString("\"error\":\"No ElasticsearchException found\"")); @@ -99,10 +104,10 @@ public class BytesRestResponseTests extends ESTestCase { request.params().put("error_trace", "true"); RestChannel channel = new DetailedExceptionRestChannel(request); - Throwable t = new Throwable("an error occurred reading data", new FileNotFoundException("/foo/bar")); + Exception t = new UnknownException("an error occurred reading data", new FileNotFoundException("/foo/bar")); BytesRestResponse response = new BytesRestResponse(channel, t); String text = response.content().utf8ToString(); - assertThat(text, containsString("\"type\":\"throwable\",\"reason\":\"an error occurred reading data\"")); + assertThat(text, containsString("\"type\":\"unknown_exception\",\"reason\":\"an error occurred reading data\"")); assertThat(text, containsString("{\"type\":\"file_not_found_exception\"")); assertThat(text, containsString("\"stack_trace\":\"[an error occurred reading data]")); } @@ -111,14 +116,14 @@ public class BytesRestResponseTests extends ESTestCase { RestRequest request = new FakeRestRequest(); RestChannel channel = new DetailedExceptionRestChannel(request); { - Throwable t = new ElasticsearchException("an error occurred reading data", new FileNotFoundException("/foo/bar")); - BytesRestResponse response = new BytesRestResponse(channel, t); + Exception e = new ElasticsearchException("an error occurred reading data", new FileNotFoundException("/foo/bar")); + BytesRestResponse response = new BytesRestResponse(channel, e); String text = response.content().utf8ToString(); assertThat(text, containsString("{\"root_cause\":[{\"type\":\"exception\",\"reason\":\"an error occurred reading data\"}]")); } { - Throwable t = new FileNotFoundException("/foo/bar"); - BytesRestResponse response = new BytesRestResponse(channel, t); + Exception e = new FileNotFoundException("/foo/bar"); + BytesRestResponse response = new BytesRestResponse(channel, e); String text = response.content().utf8ToString(); assertThat(text, containsString("{\"root_cause\":[{\"type\":\"file_not_found_exception\",\"reason\":\"/foo/bar\"}]")); } diff --git a/core/src/test/java/org/elasticsearch/search/SearchWithRejectionsIT.java b/core/src/test/java/org/elasticsearch/search/SearchWithRejectionsIT.java index 2bb39ad10ea..6542bad5b8a 100644 --- a/core/src/test/java/org/elasticsearch/search/SearchWithRejectionsIT.java +++ b/core/src/test/java/org/elasticsearch/search/SearchWithRejectionsIT.java @@ -65,7 +65,7 @@ public class SearchWithRejectionsIT extends ESIntegTestCase { for (int i = 0; i < numSearches; i++) { try { responses[i].get(); - } catch (Throwable t) { + } catch (Exception t) { } } awaitBusy(() -> client().admin().indices().prepareStats().execute().actionGet().getTotal().getSearch().getOpenContexts() == 0, 1, TimeUnit.SECONDS); diff --git a/core/src/test/java/org/elasticsearch/search/aggregations/bucket/FilterIT.java b/core/src/test/java/org/elasticsearch/search/aggregations/bucket/FilterIT.java index a48facc4d66..0c8b9a22c37 100644 --- a/core/src/test/java/org/elasticsearch/search/aggregations/bucket/FilterIT.java +++ b/core/src/test/java/org/elasticsearch/search/aggregations/bucket/FilterIT.java @@ -52,9 +52,6 @@ import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.core.IsNull.notNullValue; -/** - * - */ @ESIntegTestCase.SuiteScopeTestCase public class FilterIT extends ESIntegTestCase { diff --git a/core/src/test/java/org/elasticsearch/search/aggregations/bucket/FiltersIT.java b/core/src/test/java/org/elasticsearch/search/aggregations/bucket/FiltersIT.java index a95df3ff5e6..592861ccce2 100644 --- a/core/src/test/java/org/elasticsearch/search/aggregations/bucket/FiltersIT.java +++ b/core/src/test/java/org/elasticsearch/search/aggregations/bucket/FiltersIT.java @@ -58,9 +58,6 @@ import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.core.IsNull.notNullValue; -/** - * - */ @ESIntegTestCase.SuiteScopeTestCase public class FiltersIT extends ESIntegTestCase { diff --git a/core/src/test/java/org/elasticsearch/search/basic/SearchWhileRelocatingIT.java b/core/src/test/java/org/elasticsearch/search/basic/SearchWhileRelocatingIT.java index 98ae3241dbb..eb6322c151e 100644 --- a/core/src/test/java/org/elasticsearch/search/basic/SearchWhileRelocatingIT.java +++ b/core/src/test/java/org/elasticsearch/search/basic/SearchWhileRelocatingIT.java @@ -98,11 +98,11 @@ public class SearchWhileRelocatingIT extends ESIntegTestCase { if (numberOfReplicas == 1 || !ex.getMessage().contains("all shards failed")) { thrownExceptions.add(ex); } - } catch (Throwable t) { + } catch (Exception ex) { if (!criticalException) { - nonCriticalExceptions.add(t); + nonCriticalExceptions.add(ex); } else { - thrownExceptions.add(t); + thrownExceptions.add(ex); } } } diff --git a/core/src/test/java/org/elasticsearch/snapshots/AbstractSnapshotIntegTestCase.java b/core/src/test/java/org/elasticsearch/snapshots/AbstractSnapshotIntegTestCase.java index 50fb3f9074b..bbd1bec1d45 100644 --- a/core/src/test/java/org/elasticsearch/snapshots/AbstractSnapshotIntegTestCase.java +++ b/core/src/test/java/org/elasticsearch/snapshots/AbstractSnapshotIntegTestCase.java @@ -279,8 +279,8 @@ public abstract class AbstractSnapshotIntegTestCase extends ESIntegTestCase { } @Override - public void onFailure(String source, Throwable t) { - logger.warn("failed to execute [{}]", t, source); + public void onFailure(String source, Exception e) { + logger.warn("failed to execute [{}]", e, source); } }); diff --git a/core/src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreIT.java b/core/src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreIT.java index a25c8e0593e..9d571c02c90 100644 --- a/core/src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreIT.java +++ b/core/src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreIT.java @@ -272,7 +272,7 @@ public class DedicatedClusterSnapshotRestoreIT extends AbstractSnapshotIntegTest } @Override - public void onFailure(String source, @Nullable Throwable t) { + public void onFailure(String source, @Nullable Exception e) { countDownLatch.countDown(); } diff --git a/core/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java b/core/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java index e1efbdfaf81..f6049002852 100644 --- a/core/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java +++ b/core/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java @@ -2042,7 +2042,7 @@ public class SharedClusterSnapshotRestoreIT extends AbstractSnapshotIntegTestCas } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { fail(); } diff --git a/core/src/test/java/org/elasticsearch/test/geo/RandomShapeGenerator.java b/core/src/test/java/org/elasticsearch/test/geo/RandomShapeGenerator.java index 897fa44b593..20c82e6f518 100644 --- a/core/src/test/java/org/elasticsearch/test/geo/RandomShapeGenerator.java +++ b/core/src/test/java/org/elasticsearch/test/geo/RandomShapeGenerator.java @@ -20,16 +20,9 @@ package org.elasticsearch.test.geo; import com.carrotsearch.randomizedtesting.generators.RandomInts; -import org.locationtech.spatial4j.context.jts.JtsSpatialContext; -import org.locationtech.spatial4j.distance.DistanceUtils; -import org.locationtech.spatial4j.exception.InvalidShapeException; -import org.locationtech.spatial4j.shape.Point; -import org.locationtech.spatial4j.shape.Rectangle; -import org.locationtech.spatial4j.shape.impl.Range; import com.vividsolutions.jts.algorithm.ConvexHull; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; - import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.geo.builders.CoordinateCollection; import org.elasticsearch.common.geo.builders.CoordinatesBuilder; @@ -42,6 +35,12 @@ import org.elasticsearch.common.geo.builders.PolygonBuilder; import org.elasticsearch.common.geo.builders.ShapeBuilder; import org.elasticsearch.search.geo.GeoShapeQueryTests; import org.junit.Assert; +import org.locationtech.spatial4j.context.jts.JtsSpatialContext; +import org.locationtech.spatial4j.distance.DistanceUtils; +import org.locationtech.spatial4j.exception.InvalidShapeException; +import org.locationtech.spatial4j.shape.Point; +import org.locationtech.spatial4j.shape.Rectangle; +import org.locationtech.spatial4j.shape.impl.Range; import java.util.Random; @@ -230,14 +229,10 @@ public class RandomShapeGenerator extends RandomGeoGenerator { // The validate flag will check for these possibilities and bail if an incorrect geometry is created try { pgb.build(); - } catch (Throwable e) { + } catch (AssertionError | InvalidShapeException e) { // jts bug may occasionally misinterpret coordinate order causing an unhelpful ('geom' assertion) // or InvalidShapeException - if (e instanceof InvalidShapeException || e instanceof AssertionError) { - return null; - } - // throw any other exception - throw e; + return null; } } return pgb; diff --git a/core/src/test/java/org/elasticsearch/threadpool/SimpleThreadPoolIT.java b/core/src/test/java/org/elasticsearch/threadpool/SimpleThreadPoolIT.java index 28267e9beb7..974929dddf2 100644 --- a/core/src/test/java/org/elasticsearch/threadpool/SimpleThreadPoolIT.java +++ b/core/src/test/java/org/elasticsearch/threadpool/SimpleThreadPoolIT.java @@ -19,8 +19,6 @@ package org.elasticsearch.threadpool; -import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; -import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.ToXContent; @@ -36,7 +34,6 @@ import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; import org.elasticsearch.test.InternalTestCluster; import org.elasticsearch.test.hamcrest.RegexMatcher; -import org.elasticsearch.threadpool.ThreadPool.Names; import org.elasticsearch.tribe.TribeIT; import java.io.IOException; @@ -46,19 +43,11 @@ import java.lang.management.ThreadMXBean; import java.util.HashSet; import java.util.Map; import java.util.Set; -import java.util.concurrent.BrokenBarrierException; -import java.util.concurrent.CyclicBarrier; -import java.util.concurrent.Executor; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.sameInstance; /** */ @@ -136,9 +125,9 @@ public class SimpleThreadPoolIT extends ESIntegTestCase { try { new Node(settings); fail("The node startup is supposed to fail"); - } catch(Throwable t) { + } catch(Exception e) { //all good - assertThat(t.getMessage(), containsString("mandatory plugins [non_existing]")); + assertThat(e.getMessage(), containsString("mandatory plugins [non_existing]")); } } diff --git a/core/src/test/java/org/elasticsearch/update/UpdateIT.java b/core/src/test/java/org/elasticsearch/update/UpdateIT.java index 55834c181b0..c8cacbc36c3 100644 --- a/core/src/test/java/org/elasticsearch/update/UpdateIT.java +++ b/core/src/test/java/org/elasticsearch/update/UpdateIT.java @@ -65,11 +65,8 @@ import java.util.concurrent.TimeUnit; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows; -import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; @@ -800,7 +797,7 @@ public class UpdateIT extends ESIntegTestCase { final CountDownLatch latch = new CountDownLatch(numberOfThreads); final CountDownLatch startLatch = new CountDownLatch(1); final int numberOfUpdatesPerThread = scaledRandomIntBetween(100, 500); - final List failures = new CopyOnWriteArrayList<>(); + final List failures = new CopyOnWriteArrayList<>(); for (int i = 0; i < numberOfThreads; i++) { Runnable r = new Runnable() { @@ -832,7 +829,7 @@ public class UpdateIT extends ESIntegTestCase { logger.warn("Test was forcefully stopped. Client [{}] may still have outstanding requests.", Thread.currentThread().getName()); failures.add(e); Thread.currentThread().interrupt(); - } catch (Throwable e) { + } catch (Exception e) { failures.add(e); } finally { latch.countDown(); @@ -900,7 +897,7 @@ public class UpdateIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { synchronized (failedMap) { incrementMapValue(id, failedMap); } @@ -922,7 +919,7 @@ public class UpdateIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { synchronized (failedMap) { incrementMapValue(id, failedMap); } @@ -976,7 +973,7 @@ public class UpdateIT extends ESIntegTestCase { } } } - } catch (Throwable e) { + } catch (Exception e) { logger.error("Something went wrong", e); failures.add(e); } finally { diff --git a/core/src/test/java/org/elasticsearch/versioning/ConcurrentDocumentOperationIT.java b/core/src/test/java/org/elasticsearch/versioning/ConcurrentDocumentOperationIT.java index b2cc794ac6c..e2c572f783a 100644 --- a/core/src/test/java/org/elasticsearch/versioning/ConcurrentDocumentOperationIT.java +++ b/core/src/test/java/org/elasticsearch/versioning/ConcurrentDocumentOperationIT.java @@ -53,7 +53,7 @@ public class ConcurrentDocumentOperationIT extends ESIntegTestCase { } @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { logger.error("Unexpected exception while indexing", e); failure.set(e); latch.countDown(); diff --git a/modules/lang-groovy/src/main/java/org/elasticsearch/script/groovy/GroovyScriptEngineService.java b/modules/lang-groovy/src/main/java/org/elasticsearch/script/groovy/GroovyScriptEngineService.java index 105d42c8c86..a83dd93a17e 100644 --- a/modules/lang-groovy/src/main/java/org/elasticsearch/script/groovy/GroovyScriptEngineService.java +++ b/modules/lang-groovy/src/main/java/org/elasticsearch/script/groovy/GroovyScriptEngineService.java @@ -155,7 +155,7 @@ public class GroovyScriptEngineService extends AbstractComponent implements Scri GroovyClassLoader groovyClassLoader = new GroovyClassLoader(loader, configuration); return groovyClassLoader.parseClass(codeSource); - } catch (Throwable e) { + } catch (Exception e) { if (logger.isTraceEnabled()) { logger.trace("Exception compiling Groovy script:", e); } @@ -293,7 +293,7 @@ public class GroovyScriptEngineService extends AbstractComponent implements Scri // NOTE: we truncate the stack because IndyInterface has security issue (needs getClassLoader) // we don't do a security check just as a tradeoff, it cannot really escalate to anything. return AccessController.doPrivileged((PrivilegedAction) script::run); - } catch (Throwable e) { + } catch (Exception e) { if (logger.isTraceEnabled()) { logger.trace("failed to run {}", e, compiledScript); } diff --git a/modules/lang-groovy/src/test/java/org/elasticsearch/messy/tests/MinDocCountTests.java b/modules/lang-groovy/src/test/java/org/elasticsearch/messy/tests/MinDocCountTests.java index 662d4d2f30c..640c00b291d 100644 --- a/modules/lang-groovy/src/test/java/org/elasticsearch/messy/tests/MinDocCountTests.java +++ b/modules/lang-groovy/src/test/java/org/elasticsearch/messy/tests/MinDocCountTests.java @@ -22,7 +22,6 @@ package org.elasticsearch.messy.tests; import com.carrotsearch.hppc.LongHashSet; import com.carrotsearch.hppc.LongSet; import com.carrotsearch.randomizedtesting.generators.RandomStrings; - import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; @@ -316,7 +315,8 @@ public class MinDocCountTests extends AbstractTermsTestCase { Thread.sleep(60000); logger.debug("1m passed. retrying."); testMinDocCountOnTerms(field, script, order, include, false); - } catch (Throwable secondFailure) { + } catch (Exception secondFailure) { + secondFailure.addSuppressed(ae); logger.error("exception on retry (will re-throw the original in a sec)", secondFailure); } throw ae; diff --git a/modules/lang-groovy/src/test/java/org/elasticsearch/script/groovy/GroovyScriptTests.java b/modules/lang-groovy/src/test/java/org/elasticsearch/script/groovy/GroovyScriptTests.java index 4a7b4350d23..f2eee2bb408 100644 --- a/modules/lang-groovy/src/test/java/org/elasticsearch/script/groovy/GroovyScriptTests.java +++ b/modules/lang-groovy/src/test/java/org/elasticsearch/script/groovy/GroovyScriptTests.java @@ -99,15 +99,15 @@ public class GroovyScriptTests extends ESIntegTestCase { try { client().prepareSearch("test") - .setQuery(constantScoreQuery(scriptQuery(new Script("assert false", ScriptType.INLINE, "groovy", null)))).get(); + .setQuery(constantScoreQuery(scriptQuery(new Script("null.foo", ScriptType.INLINE, "groovy", null)))).get(); fail("should have thrown an exception"); } catch (SearchPhaseExecutionException e) { assertThat(e.toString() + "should not contained NotSerializableTransportException", e.toString().contains("NotSerializableTransportException"), equalTo(false)); assertThat(e.toString() + "should have contained ScriptException", e.toString().contains("ScriptException"), equalTo(true)); - assertThat(e.toString()+ "should have contained an assert error", - e.toString().contains("AssertionError[assert false"), equalTo(true)); + assertThat(e.toString()+ "should have contained a NullPointerException", + e.toString().contains("NullPointerException[Cannot get property 'foo' on null object]"), equalTo(true)); } } diff --git a/modules/lang-mustache/src/main/java/org/elasticsearch/action/search/template/MultiSearchTemplateResponse.java b/modules/lang-mustache/src/main/java/org/elasticsearch/action/search/template/MultiSearchTemplateResponse.java index c779757f61b..5ca5078661c 100644 --- a/modules/lang-mustache/src/main/java/org/elasticsearch/action/search/template/MultiSearchTemplateResponse.java +++ b/modules/lang-mustache/src/main/java/org/elasticsearch/action/search/template/MultiSearchTemplateResponse.java @@ -40,21 +40,21 @@ public class MultiSearchTemplateResponse extends ActionResponse implements Itera */ public static class Item implements Streamable { private SearchTemplateResponse response; - private Throwable throwable; + private Exception exception; Item() { } - public Item(SearchTemplateResponse response, Throwable throwable) { + public Item(SearchTemplateResponse response, Exception exception) { this.response = response; - this.throwable = throwable; + this.exception = exception; } /** * Is it a failed search? */ public boolean isFailure() { - return throwable != null; + return exception != null; } /** @@ -62,7 +62,7 @@ public class MultiSearchTemplateResponse extends ActionResponse implements Itera */ @Nullable public String getFailureMessage() { - return throwable == null ? null : throwable.getMessage(); + return exception == null ? null : exception.getMessage(); } /** @@ -85,7 +85,7 @@ public class MultiSearchTemplateResponse extends ActionResponse implements Itera this.response = new SearchTemplateResponse(); response.readFrom(in); } else { - throwable = in.readThrowable(); + exception = in.readException(); } } @@ -96,12 +96,12 @@ public class MultiSearchTemplateResponse extends ActionResponse implements Itera response.writeTo(out); } else { out.writeBoolean(false); - out.writeThrowable(throwable); + out.writeThrowable(exception); } } - public Throwable getFailure() { - return throwable; + public Exception getFailure() { + return exception; } } @@ -150,7 +150,7 @@ public class MultiSearchTemplateResponse extends ActionResponse implements Itera for (Item item : items) { builder.startObject(); if (item.isFailure()) { - ElasticsearchException.renderThrowable(builder, params, item.getFailure()); + ElasticsearchException.renderException(builder, params, item.getFailure()); } else { item.getResponse().toXContent(builder, params); } diff --git a/modules/lang-mustache/src/main/java/org/elasticsearch/action/search/template/TransportMultiSearchTemplateAction.java b/modules/lang-mustache/src/main/java/org/elasticsearch/action/search/template/TransportMultiSearchTemplateAction.java index 1ffb19b5fc4..642fe7648da 100644 --- a/modules/lang-mustache/src/main/java/org/elasticsearch/action/search/template/TransportMultiSearchTemplateAction.java +++ b/modules/lang-mustache/src/main/java/org/elasticsearch/action/search/template/TransportMultiSearchTemplateAction.java @@ -61,7 +61,7 @@ public class TransportMultiSearchTemplateAction extends HandledTransportActionfalse is returned. */ public boolean isFailure() { - return throwable != null; + return exception != null; } - public Throwable getFailure() { - return throwable; + public Exception getFailure() { + return exception; } @Override @@ -161,7 +161,7 @@ public class MultiPercolateResponse extends ActionResponse implements Iterable client.search(firstSearchRequest, listener), (SearchResponse response) -> { @@ -185,8 +185,8 @@ public abstract class AbstractAsyncBulkByScrollAction indexingFailures, List searchFailures, boolean timedOut) { + void finishHim(Exception failure, List indexingFailures, List searchFailures, boolean timedOut) { String scrollId = scroll.get(); if (Strings.hasLength(scrollId)) { /* @@ -403,7 +402,7 @@ public abstract class AbstractAsyncBulkByScrollAction value = new AtomicReference<>(randomSimpleString(random())); indexRandom(true, client().prepareIndex("test", "test", "test").setSource("test", value.get())); - AtomicReference failure = new AtomicReference<>(); + AtomicReference failure = new AtomicReference<>(); AtomicBoolean keepUpdating = new AtomicBoolean(true); Thread updater = new Thread(() -> { while (keepUpdating.get()) { @@ -52,8 +52,8 @@ public class UpdateByQueryWhileModifyingTests extends ReindexTestCase { BulkIndexByScrollResponse response = updateByQuery().source("test").refresh(true).abortOnVersionConflict(false).get(); assertThat(response, matcher().updated(either(equalTo(0L)).or(equalTo(1L))) .versionConflicts(either(equalTo(0L)).or(equalTo(1L)))); - } catch (Throwable t) { - failure.set(t); + } catch (Exception e) { + failure.set(e); } } }); diff --git a/plugins/analysis-icu/src/main/java/org/elasticsearch/index/analysis/IcuTokenizerFactory.java b/plugins/analysis-icu/src/main/java/org/elasticsearch/index/analysis/IcuTokenizerFactory.java index e04724ee370..eac3ceebc16 100644 --- a/plugins/analysis-icu/src/main/java/org/elasticsearch/index/analysis/IcuTokenizerFactory.java +++ b/plugins/analysis-icu/src/main/java/org/elasticsearch/index/analysis/IcuTokenizerFactory.java @@ -40,9 +40,6 @@ import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; - -/** - */ public class IcuTokenizerFactory extends AbstractTokenizerFactory { private final ICUTokenizerConfig config; @@ -101,8 +98,8 @@ public class IcuTokenizerFactory extends AbstractTokenizerFactory { }; return config; } - } catch (Throwable t) { - throw new ElasticsearchException("failed to load ICU rule files", t); + } catch (Exception e) { + throw new ElasticsearchException("failed to load ICU rule files", e); } } diff --git a/plugins/discovery-gce/src/main/java/org/elasticsearch/discovery/gce/GceUnicastHostsProvider.java b/plugins/discovery-gce/src/main/java/org/elasticsearch/discovery/gce/GceUnicastHostsProvider.java index c9dd2263245..be3d737b919 100644 --- a/plugins/discovery-gce/src/main/java/org/elasticsearch/discovery/gce/GceUnicastHostsProvider.java +++ b/plugins/discovery-gce/src/main/java/org/elasticsearch/discovery/gce/GceUnicastHostsProvider.java @@ -249,8 +249,8 @@ public class GceUnicastHostsProvider extends AbstractComponent implements Unicas } } - } catch (Throwable e) { - logger.warn("Exception caught during discovery: {}", e, e.getMessage()); + } catch (Exception e) { + logger.warn("exception caught during discovery", e); } logger.debug("{} node(s) added", cachedDiscoNodes.size()); diff --git a/plugins/ingest-attachment/src/main/java/org/elasticsearch/ingest/attachment/AttachmentProcessor.java b/plugins/ingest-attachment/src/main/java/org/elasticsearch/ingest/attachment/AttachmentProcessor.java index fb4dc37d641..b06232e1c41 100644 --- a/plugins/ingest-attachment/src/main/java/org/elasticsearch/ingest/attachment/AttachmentProcessor.java +++ b/plugins/ingest-attachment/src/main/java/org/elasticsearch/ingest/attachment/AttachmentProcessor.java @@ -122,7 +122,7 @@ public final class AttachmentProcessor extends AbstractProcessor { String length = Strings.hasLength(contentLength) ? contentLength : String.valueOf(parsedContent.length()); additionalFields.put(Property.CONTENT_LENGTH.toLowerCase(), length); } - } catch (Throwable e) { + } catch (Exception e) { throw new ElasticsearchParseException("Error parsing document in field [{}]", e, field); } diff --git a/plugins/ingest-attachment/src/test/java/org/elasticsearch/ingest/attachment/TikaDocTests.java b/plugins/ingest-attachment/src/test/java/org/elasticsearch/ingest/attachment/TikaDocTests.java index 0c63f65c247..4b9a40dd8a9 100644 --- a/plugins/ingest-attachment/src/test/java/org/elasticsearch/ingest/attachment/TikaDocTests.java +++ b/plugins/ingest-attachment/src/test/java/org/elasticsearch/ingest/attachment/TikaDocTests.java @@ -58,7 +58,7 @@ public class TikaDocTests extends ESTestCase { assertNotNull(parsedContent); assertFalse(parsedContent.isEmpty()); logger.debug("extracted content: {}", parsedContent); - } catch (Throwable e) { + } catch (Exception e) { throw new RuntimeException("parsing of filename: " + fileName.getFileName() + " failed", e); } } diff --git a/plugins/jvm-example/src/main/java/org/elasticsearch/plugin/example/ExampleCatAction.java b/plugins/jvm-example/src/main/java/org/elasticsearch/plugin/example/ExampleCatAction.java index 8bcc0ca1fc8..b27c3fad2b8 100644 --- a/plugins/jvm-example/src/main/java/org/elasticsearch/plugin/example/ExampleCatAction.java +++ b/plugins/jvm-example/src/main/java/org/elasticsearch/plugin/example/ExampleCatAction.java @@ -52,11 +52,12 @@ public class ExampleCatAction extends AbstractCatAction { table.endRow(); try { channel.sendResponse(RestTable.buildResponse(table, channel)); - } catch (Throwable e) { + } catch (Exception e) { try { channel.sendResponse(new BytesRestResponse(channel, e)); - } catch (Throwable e1) { - logger.error("failed to send failure response", e1); + } catch (Exception inner) { + inner.addSuppressed(e); + logger.error("failed to send failure response", inner); } } } diff --git a/plugins/lang-javascript/src/test/java/org/elasticsearch/script/javascript/JavaScriptScriptMultiThreadedTests.java b/plugins/lang-javascript/src/test/java/org/elasticsearch/script/javascript/JavaScriptScriptMultiThreadedTests.java index c2f1214e72b..634a4ca6dfa 100644 --- a/plugins/lang-javascript/src/test/java/org/elasticsearch/script/javascript/JavaScriptScriptMultiThreadedTests.java +++ b/plugins/lang-javascript/src/test/java/org/elasticsearch/script/javascript/JavaScriptScriptMultiThreadedTests.java @@ -35,9 +35,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import static org.hamcrest.Matchers.equalTo; -/** - * - */ public class JavaScriptScriptMultiThreadedTests extends ESTestCase { public void testExecutableNoRuntimeParams() throws Exception { final JavaScriptScriptEngineService se = new JavaScriptScriptEngineService(Settings.Builder.EMPTY_SETTINGS); @@ -64,9 +61,9 @@ public class JavaScriptScriptMultiThreadedTests extends ESTestCase { long result = ((Number) script.run()).longValue(); assertThat(result, equalTo(addition)); } - } catch (Throwable t) { + } catch (Exception e) { failed.set(true); - logger.error("failed", t); + logger.error("failed", e); } finally { latch.countDown(); } @@ -106,9 +103,9 @@ public class JavaScriptScriptMultiThreadedTests extends ESTestCase { long result = ((Number) script.run()).longValue(); assertThat(result, equalTo(addition)); } - } catch (Throwable t) { + } catch (Exception e) { failed.set(true); - logger.error("failed", t); + logger.error("failed", e); } finally { latch.countDown(); } @@ -147,9 +144,9 @@ public class JavaScriptScriptMultiThreadedTests extends ESTestCase { long result = ((Number) se.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "testExecutableNoRuntimeParams", "js", compiled), runtimeVars).run()).longValue(); assertThat(result, equalTo(addition)); } - } catch (Throwable t) { + } catch (Exception e) { failed.set(true); - logger.error("failed", t); + logger.error("failed", e); } finally { latch.countDown(); } diff --git a/plugins/lang-python/src/test/java/org/elasticsearch/script/python/PythonScriptMultiThreadedTests.java b/plugins/lang-python/src/test/java/org/elasticsearch/script/python/PythonScriptMultiThreadedTests.java index abf9f661a6d..0a887bc9a7e 100644 --- a/plugins/lang-python/src/test/java/org/elasticsearch/script/python/PythonScriptMultiThreadedTests.java +++ b/plugins/lang-python/src/test/java/org/elasticsearch/script/python/PythonScriptMultiThreadedTests.java @@ -66,9 +66,9 @@ public class PythonScriptMultiThreadedTests extends ESTestCase { long result = ((Number) script.run()).longValue(); assertThat(result, equalTo(addition)); } - } catch (Throwable t) { + } catch (Exception e) { failed.set(true); - logger.error("failed", t); + logger.error("failed", e); } finally { latch.countDown(); } @@ -109,9 +109,9 @@ public class PythonScriptMultiThreadedTests extends ESTestCase { // long result = ((Number) script.run(runtimeVars)).longValue(); // assertThat(result, equalTo(addition)); // } -// } catch (Throwable t) { +// } catch (Exception e) { // failed.set(true); -// logger.error("failed", t); +// logger.error("failed", e); // } finally { // latch.countDown(); // } @@ -151,9 +151,9 @@ public class PythonScriptMultiThreadedTests extends ESTestCase { long result = ((Number) se.executable(compiledScript, runtimeVars).run()).longValue(); assertThat(result, equalTo(addition)); } - } catch (Throwable t) { + } catch (Exception e) { failed.set(true); - logger.error("failed", t); + logger.error("failed", e); } finally { latch.countDown(); } diff --git a/plugins/mapper-attachments/src/main/java/org/elasticsearch/mapper/attachments/AttachmentMapper.java b/plugins/mapper-attachments/src/main/java/org/elasticsearch/mapper/attachments/AttachmentMapper.java index 79174e54c62..06e51686823 100644 --- a/plugins/mapper-attachments/src/main/java/org/elasticsearch/mapper/attachments/AttachmentMapper.java +++ b/plugins/mapper-attachments/src/main/java/org/elasticsearch/mapper/attachments/AttachmentMapper.java @@ -482,7 +482,7 @@ public class AttachmentMapper extends FieldMapper { String parsedContent; try { parsedContent = TikaImpl.parse(content, metadata, indexedChars); - } catch (Throwable e) { + } catch (Exception e) { // #18: we could ignore errors when Tika does not parse data if (!ignoreErrors) { logger.trace("exception caught", e); @@ -508,8 +508,8 @@ public class AttachmentMapper extends FieldMapper { } context = context.createExternalValueContext(language); languageMapper.parse(context); - } catch(Throwable t) { - logger.debug("Cannot detect language: [{}]", t.getMessage()); + } catch(Exception e) { + logger.debug("Cannot detect language: [{}]", e.getMessage()); } } diff --git a/plugins/mapper-attachments/src/test/java/org/elasticsearch/mapper/attachments/TikaDocTests.java b/plugins/mapper-attachments/src/test/java/org/elasticsearch/mapper/attachments/TikaDocTests.java index fbbdeb83a7d..b32a6ab79a0 100644 --- a/plugins/mapper-attachments/src/test/java/org/elasticsearch/mapper/attachments/TikaDocTests.java +++ b/plugins/mapper-attachments/src/test/java/org/elasticsearch/mapper/attachments/TikaDocTests.java @@ -58,7 +58,7 @@ public class TikaDocTests extends ESTestCase { assertNotNull(parsedContent); assertFalse(parsedContent.isEmpty()); logger.debug("extracted content: {}", parsedContent); - } catch (Throwable e) { + } catch (Exception e) { throw new RuntimeException("parsing of filename: " + fileName.getFileName() + " failed", e); } } diff --git a/plugins/repository-s3/src/main/java/org/elasticsearch/cloud/aws/blobstore/S3BlobContainer.java b/plugins/repository-s3/src/main/java/org/elasticsearch/cloud/aws/blobstore/S3BlobContainer.java index 7dc6f3b6a83..ea71dc152f9 100644 --- a/plugins/repository-s3/src/main/java/org/elasticsearch/cloud/aws/blobstore/S3BlobContainer.java +++ b/plugins/repository-s3/src/main/java/org/elasticsearch/cloud/aws/blobstore/S3BlobContainer.java @@ -46,9 +46,6 @@ import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.Map; -/** - * - */ public class S3BlobContainer extends AbstractBlobContainer { protected final S3BlobStore blobStore; @@ -74,7 +71,7 @@ public class S3BlobContainer extends AbstractBlobContainer { }); } catch (AmazonS3Exception e) { return false; - } catch (Throwable e) { + } catch (Exception e) { throw new BlobStoreException("failed to check if blob exists", e); } } diff --git a/plugins/repository-s3/src/test/java/org/elasticsearch/repositories/s3/AbstractS3SnapshotRestoreTest.java b/plugins/repository-s3/src/test/java/org/elasticsearch/repositories/s3/AbstractS3SnapshotRestoreTest.java index 93c19df9c04..d1c43f15adb 100644 --- a/plugins/repository-s3/src/test/java/org/elasticsearch/repositories/s3/AbstractS3SnapshotRestoreTest.java +++ b/plugins/repository-s3/src/test/java/org/elasticsearch/repositories/s3/AbstractS3SnapshotRestoreTest.java @@ -512,7 +512,7 @@ public abstract class AbstractS3SnapshotRestoreTest extends AbstractAwsTestCase multiObjectDeleteRequest.setKeys(keys); client.deleteObjects(multiObjectDeleteRequest); } - } catch (Throwable ex) { + } catch (Exception ex) { logger.warn("Failed to delete S3 repository [{}] in [{}]", ex, bucketName, region); } } diff --git a/qa/evil-tests/src/test/java/org/elasticsearch/bootstrap/SeccompTests.java b/qa/evil-tests/src/test/java/org/elasticsearch/bootstrap/SeccompTests.java index a319aaabb70..d028dfd573a 100644 --- a/qa/evil-tests/src/test/java/org/elasticsearch/bootstrap/SeccompTests.java +++ b/qa/evil-tests/src/test/java/org/elasticsearch/bootstrap/SeccompTests.java @@ -40,7 +40,7 @@ public class SeccompTests extends ESTestCase { if (!JNANatives.LOCAL_SECCOMP_ALL) { try { Seccomp.init(createTempDir()); - } catch (Throwable e) { + } catch (Exception e) { throw new RuntimeException("unable to forcefully apply seccomp to test thread", e); } } diff --git a/test/framework/src/main/java/org/elasticsearch/bootstrap/ESElasticsearchCliTestCase.java b/test/framework/src/main/java/org/elasticsearch/bootstrap/ESElasticsearchCliTestCase.java index aa327ae2546..f08f15f236b 100644 --- a/test/framework/src/main/java/org/elasticsearch/bootstrap/ESElasticsearchCliTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/bootstrap/ESElasticsearchCliTestCase.java @@ -53,12 +53,12 @@ abstract class ESElasticsearchCliTestCase extends ESTestCase { assertThat(status, equalTo(expectedStatus)); assertThat(init.get(), equalTo(expectedInit)); outputConsumer.accept(terminal.getOutput()); - } catch (Throwable t) { + } catch (Exception e) { // if an unexpected exception is thrown, we log // terminal output to aid debugging logger.info(terminal.getOutput()); // rethrow so the test fails - throw t; + throw e; } } diff --git a/test/framework/src/main/java/org/elasticsearch/test/BackgroundIndexer.java b/test/framework/src/main/java/org/elasticsearch/test/BackgroundIndexer.java index 933f26e6e81..4440fbe117d 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/BackgroundIndexer.java +++ b/test/framework/src/main/java/org/elasticsearch/test/BackgroundIndexer.java @@ -49,7 +49,7 @@ public class BackgroundIndexer implements AutoCloseable { final Thread[] writers; final CountDownLatch stopLatch; - final CopyOnWriteArrayList failures; + final CopyOnWriteArrayList failures; final AtomicBoolean stop = new AtomicBoolean(false); final AtomicLong idGenerator = new AtomicLong(); final AtomicLong indexCounter = new AtomicLong(); @@ -169,7 +169,7 @@ public class BackgroundIndexer implements AutoCloseable { } } logger.info("**** done indexing thread {} stop: {} numDocsIndexed: {}", indexerId, stop.get(), indexCounter.get()); - } catch (Throwable e) { + } catch (Exception e) { failures.add(e); logger.warn("**** failed indexing thread {} on doc id {}", e, indexerId, id); } finally { diff --git a/test/framework/src/main/java/org/elasticsearch/test/ClusterServiceUtils.java b/test/framework/src/main/java/org/elasticsearch/test/ClusterServiceUtils.java index fe7ba74a327..a86b55c81db 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/ClusterServiceUtils.java +++ b/test/framework/src/main/java/org/elasticsearch/test/ClusterServiceUtils.java @@ -21,7 +21,6 @@ package org.elasticsearch.test; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.Version; import org.elasticsearch.cluster.ClusterChangedEvent; -import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ClusterStateUpdateTask; import org.elasticsearch.cluster.NodeConnectionsService; @@ -98,8 +97,8 @@ public class ClusterServiceUtils { } @Override - public void onFailure(String source, Throwable t) { - fail("unexpected exception" + t); + public void onFailure(String source, Exception e) { + fail("unexpected exception" + e); } }); try { diff --git a/test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java b/test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java index d13f69a3765..6d07a85e50b 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java @@ -955,7 +955,7 @@ public abstract class ESIntegTestCase extends ESTestCase { client().admin().indices().prepareRefresh().get(); } lastKnownCount.set(count); - } catch (Throwable e) { // count now acts like search and barfs if all shards failed... + } catch (Exception e) { // count now acts like search and barfs if all shards failed... logger.debug("failed to executed count", e); return false; } @@ -1333,7 +1333,7 @@ public abstract class ESIntegTestCase extends ESTestCase { } final String[] indices = indicesSet.toArray(new String[indicesSet.size()]); Collections.shuffle(builders, random()); - final CopyOnWriteArrayList> errors = new CopyOnWriteArrayList<>(); + final CopyOnWriteArrayList> errors = new CopyOnWriteArrayList<>(); List inFlightAsyncOperations = new ArrayList<>(); // If you are indexing just a few documents then frequently do it one at a time. If many then frequently in bulk. if (builders.size() < FREQUENT_BULK_THRESHOLD ? frequently() : builders.size() < ALWAYS_BULK_THRESHOLD ? rarely() : false) { @@ -1366,8 +1366,8 @@ public abstract class ESIntegTestCase extends ESTestCase { for (CountDownLatch operation : inFlightAsyncOperations) { operation.await(); } - final List actualErrors = new ArrayList<>(); - for (Tuple tuple : errors) { + final List actualErrors = new ArrayList<>(); + for (Tuple tuple : errors) { if (ExceptionsHelper.unwrapCause(tuple.v2()) instanceof EsRejectedExecutionException) { tuple.v1().execute().actionGet(); // re-index if rejected } else { @@ -1525,7 +1525,7 @@ public abstract class ESIntegTestCase extends ESTestCase { } @Override - public final void onFailure(Throwable t) { + public final void onFailure(Exception t) { try { logger.info("Action Failed", t); addError(t); @@ -1534,24 +1534,24 @@ public abstract class ESIntegTestCase extends ESTestCase { } } - protected void addError(Throwable t) { + protected void addError(Exception e) { } } private class PayloadLatchedActionListener extends LatchedActionListener { - private final CopyOnWriteArrayList> errors; + private final CopyOnWriteArrayList> errors; private final T builder; - public PayloadLatchedActionListener(T builder, CountDownLatch latch, CopyOnWriteArrayList> errors) { + public PayloadLatchedActionListener(T builder, CountDownLatch latch, CopyOnWriteArrayList> errors) { super(latch); this.errors = errors; this.builder = builder; } @Override - protected void addError(Throwable t) { - errors.add(new Tuple<>(builder, t)); + protected void addError(Exception e) { + errors.add(new Tuple<>(builder, e)); } } diff --git a/test/framework/src/main/java/org/elasticsearch/test/InternalTestCluster.java b/test/framework/src/main/java/org/elasticsearch/test/InternalTestCluster.java index 11bad415764..489cad5b085 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/InternalTestCluster.java +++ b/test/framework/src/main/java/org/elasticsearch/test/InternalTestCluster.java @@ -1481,7 +1481,7 @@ public final class InternalTestCluster extends TestCluster { Client client = viaNode != null ? client(viaNode) : client(); ClusterState state = client.admin().cluster().prepareState().execute().actionGet().getState(); return state.nodes().getMasterNode().getName(); - } catch (Throwable e) { + } catch (Exception e) { logger.warn("Can't fetch cluster state", e); throw new RuntimeException("Can't get master node " + e.getMessage(), e); } diff --git a/test/framework/src/main/java/org/elasticsearch/test/VersionUtils.java b/test/framework/src/main/java/org/elasticsearch/test/VersionUtils.java index 5525baf4206..d09c763322c 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/VersionUtils.java +++ b/test/framework/src/main/java/org/elasticsearch/test/VersionUtils.java @@ -44,7 +44,7 @@ public class VersionUtils { try { Version object = (Version) field.get(null); ids.add(object.id); - } catch (Throwable e) { + } catch (IllegalAccessException e) { throw new RuntimeException(e); } } diff --git a/test/framework/src/main/java/org/elasticsearch/test/client/NoOpClient.java b/test/framework/src/main/java/org/elasticsearch/test/client/NoOpClient.java index 6ff45608700..1d91b0980e4 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/client/NoOpClient.java +++ b/test/framework/src/main/java/org/elasticsearch/test/client/NoOpClient.java @@ -50,8 +50,8 @@ public class NoOpClient extends AbstractClient { public void close() { try { ThreadPool.terminate(threadPool(), 10, TimeUnit.SECONDS); - } catch (Throwable t) { - throw new ElasticsearchException(t.getMessage(), t); + } catch (Exception e) { + throw new ElasticsearchException(e.getMessage(), e); } } } diff --git a/test/framework/src/main/java/org/elasticsearch/test/disruption/BlockClusterStateProcessing.java b/test/framework/src/main/java/org/elasticsearch/test/disruption/BlockClusterStateProcessing.java index cbcb9766943..956088f0fd1 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/disruption/BlockClusterStateProcessing.java +++ b/test/framework/src/main/java/org/elasticsearch/test/disruption/BlockClusterStateProcessing.java @@ -76,8 +76,8 @@ public class BlockClusterStateProcessing extends SingleNodeDisruption { } @Override - public void onFailure(String source, Throwable t) { - logger.error("unexpected error during disruption", t); + public void onFailure(String source, Exception e) { + logger.error("unexpected error during disruption", e); } }); try { diff --git a/test/framework/src/main/java/org/elasticsearch/test/disruption/SlowClusterStateProcessing.java b/test/framework/src/main/java/org/elasticsearch/test/disruption/SlowClusterStateProcessing.java index be0b69a8e8b..f69c0a3085d 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/disruption/SlowClusterStateProcessing.java +++ b/test/framework/src/main/java/org/elasticsearch/test/disruption/SlowClusterStateProcessing.java @@ -124,7 +124,7 @@ public class SlowClusterStateProcessing extends SingleNodeDisruption { } @Override - public void onFailure(String source, Throwable t) { + public void onFailure(String source, Exception e) { countDownLatch.countDown(); } }); diff --git a/test/framework/src/main/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java b/test/framework/src/main/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java index 82f2346c421..988d4b9bb87 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java +++ b/test/framework/src/main/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java @@ -95,9 +95,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -/** - * - */ public class ElasticsearchAssertions { public static void assertAcked(AcknowledgedRequestBuilder builder) { @@ -555,7 +552,6 @@ public class ElasticsearchAssertions { extraInfo += " with status [" + status + "]"; } - try { future.actionGet(); fail = true; @@ -565,7 +561,7 @@ public class ElasticsearchAssertions { if (status != null) { assertThat(extraInfo, ExceptionsHelper.status(esException), equalTo(status)); } - } catch (Throwable e) { + } catch (Exception e) { assertThat(extraInfo, e, instanceOf(exceptionClass)); if (status != null) { assertThat(extraInfo, ExceptionsHelper.status(e), equalTo(status)); @@ -597,7 +593,7 @@ public class ElasticsearchAssertions { try { future.actionGet(); fail = true; - } catch (Throwable e) { + } catch (Exception e) { assertThat(extraInfo, ExceptionsHelper.status(e), equalTo(status)); } // has to be outside catch clause to get a proper message @@ -657,35 +653,38 @@ public class ElasticsearchAssertions { equalTo(0)); assertThat("Serialization failed with version [" + version + "] bytes should be equal for streamable [" + streamable + "]", serialize(version, streamable), equalTo(orig)); - } catch (Throwable ex) { + } catch (Exception ex) { throw new RuntimeException("failed to check serialization - version [" + version + "] for streamable [" + streamable + "]", ex); } } - public static void assertVersionSerializable(Version version, final Throwable t) { - ElasticsearchAssertions.assertVersionSerializable(version, new ThrowableWrapper(t)); + public static void assertVersionSerializable(Version version, final Exception e) { + ElasticsearchAssertions.assertVersionSerializable(version, new ExceptionWrapper(e)); } - public static final class ThrowableWrapper implements Streamable { - Throwable throwable; - public ThrowableWrapper(Throwable t) { - throwable = t; + public static final class ExceptionWrapper implements Streamable { + + private Exception exception; + + public ExceptionWrapper(Exception e) { + exception = e; } - public ThrowableWrapper() { - throwable = null; + public ExceptionWrapper() { + exception = null; } @Override public void readFrom(StreamInput in) throws IOException { - throwable = in.readThrowable(); + exception = in.readException(); } @Override public void writeTo(StreamOutput out) throws IOException { - out.writeThrowable(throwable); + out.writeThrowable(exception); } + } @@ -697,7 +696,7 @@ public class ElasticsearchAssertions { assertThat(constructor, Matchers.notNullValue()); Streamable newInstance = constructor.newInstance(); return newInstance; - } catch (Throwable e) { + } catch (Exception e) { return null; } } diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/spec/RestSpec.java b/test/framework/src/main/java/org/elasticsearch/test/rest/spec/RestSpec.java index 106ff5176c7..c6ea48fd6ef 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/spec/RestSpec.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/spec/RestSpec.java @@ -75,7 +75,7 @@ public class RestSpec { } restSpec.addApi(restApi); } - } catch (Throwable ex) { + } catch (Exception ex) { throw new IOException("Can't parse rest spec file: [" + jsonFile + "]", ex); } } diff --git a/test/framework/src/main/java/org/elasticsearch/test/tasks/MockTaskManager.java b/test/framework/src/main/java/org/elasticsearch/test/tasks/MockTaskManager.java index b0d16d10c49..ec695e8bd41 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/tasks/MockTaskManager.java +++ b/test/framework/src/main/java/org/elasticsearch/test/tasks/MockTaskManager.java @@ -50,8 +50,8 @@ public class MockTaskManager extends TaskManager { for (MockTaskManagerListener listener : listeners) { try { listener.onTaskRegistered(task); - } catch (Throwable t) { - logger.warn("failed to notify task manager listener about unregistering the task with id {}", t, task.getId()); + } catch (Exception e) { + logger.warn("failed to notify task manager listener about unregistering the task with id {}", e, task.getId()); } } } @@ -65,8 +65,8 @@ public class MockTaskManager extends TaskManager { for (MockTaskManagerListener listener : listeners) { try { listener.onTaskUnregistered(task); - } catch (Throwable t) { - logger.warn("failed to notify task manager listener about unregistering the task with id {}", t, task.getId()); + } catch (Exception e) { + logger.warn("failed to notify task manager listener about unregistering the task with id {}", e, task.getId()); } } } else { @@ -80,8 +80,8 @@ public class MockTaskManager extends TaskManager { for (MockTaskManagerListener listener : listeners) { try { listener.waitForTaskCompletion(task); - } catch (Throwable t) { - logger.warn("failed to notify task manager listener about waitForTaskCompletion the task with id {}", t, task.getId()); + } catch (Exception e) { + logger.warn("failed to notify task manager listener about waitForTaskCompletion the task with id {}", e, task.getId()); } } super.waitForTaskCompletion(task, untilInNanos); diff --git a/test/framework/src/main/java/org/elasticsearch/test/transport/MockTransportService.java b/test/framework/src/main/java/org/elasticsearch/test/transport/MockTransportService.java index 41c27ecbf97..bc371ca02d1 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/transport/MockTransportService.java +++ b/test/framework/src/main/java/org/elasticsearch/test/transport/MockTransportService.java @@ -20,7 +20,6 @@ package org.elasticsearch.test.transport; import org.elasticsearch.Version; -import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.transport.TransportService; @@ -34,7 +33,6 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.network.NetworkService; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.settings.SettingsModule; import org.elasticsearch.common.transport.BoundTransportAddress; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.unit.TimeValue; @@ -52,7 +50,6 @@ import org.elasticsearch.transport.Transport; import org.elasticsearch.transport.TransportException; import org.elasticsearch.transport.TransportRequest; import org.elasticsearch.transport.TransportRequestOptions; -import org.elasticsearch.transport.TransportService; import org.elasticsearch.transport.TransportServiceAdapter; import org.elasticsearch.transport.local.LocalTransport; import org.elasticsearch.transport.netty.NettyTransport; @@ -387,7 +384,7 @@ public class MockTransportService extends TransportService { threadPool.schedule(delay, ThreadPool.Names.GENERIC, new AbstractRunnable() { @Override - public void onFailure(Throwable e) { + public void onFailure(Exception e) { logger.debug("failed to send delayed request", e); } @@ -639,10 +636,10 @@ public class MockTransportService extends TransportService { } @Override - protected void traceResponseSent(long requestId, String action, Throwable t) { - super.traceResponseSent(requestId, action, t); + protected void traceResponseSent(long requestId, String action, Exception e) { + super.traceResponseSent(requestId, action, e); for (Tracer tracer : activeTracers) { - tracer.responseSent(requestId, action, t); + tracer.responseSent(requestId, action, e); } }