diff --git a/core/src/main/java/org/elasticsearch/action/ActionRequest.java b/core/src/main/java/org/elasticsearch/action/ActionRequest.java index 45e7e76ca0b..eedcff04ae3 100644 --- a/core/src/main/java/org/elasticsearch/action/ActionRequest.java +++ b/core/src/main/java/org/elasticsearch/action/ActionRequest.java @@ -34,13 +34,6 @@ public abstract class ActionRequest extends TransportRe super(); } - protected ActionRequest(ActionRequest request) { - super(request); - // this does not set the listenerThreaded API, if needed, its up to the caller to set it - // since most times, we actually want it to not be threaded... - // this.listenerThreaded = request.listenerThreaded(); - } - public abstract ActionRequestValidationException validate(); @Override diff --git a/core/src/main/java/org/elasticsearch/action/ActionRequestBuilder.java b/core/src/main/java/org/elasticsearch/action/ActionRequestBuilder.java index 9ad449f1f45..8cbc405dafb 100644 --- a/core/src/main/java/org/elasticsearch/action/ActionRequestBuilder.java +++ b/core/src/main/java/org/elasticsearch/action/ActionRequestBuilder.java @@ -49,12 +49,6 @@ public abstract class ActionRequestBuilder execute() { PlainListenableActionFuture future = new PlainListenableActionFuture<>(threadPool); execute(future); 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 79adbafa9bb..b5c9577aff7 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 @@ -141,7 +141,7 @@ public class TransportClusterHealthAction extends TransportMasterNodeReadAction< } assert waitFor >= 0; - final ClusterStateObserver observer = new ClusterStateObserver(clusterService, logger); + final ClusterStateObserver observer = new ClusterStateObserver(clusterService, logger, threadPool.getThreadContext()); final ClusterState state = observer.observedState(); if (waitFor == 0 || request.timeout().millis() == 0) { listener.onResponse(getResponse(request, state, waitFor, request.timeout().millis() == 0)); diff --git a/core/src/main/java/org/elasticsearch/action/admin/cluster/node/hotthreads/TransportNodesHotThreadsAction.java b/core/src/main/java/org/elasticsearch/action/admin/cluster/node/hotthreads/TransportNodesHotThreadsAction.java index f26177a0ce7..c743a1d2a91 100644 --- a/core/src/main/java/org/elasticsearch/action/admin/cluster/node/hotthreads/TransportNodesHotThreadsAction.java +++ b/core/src/main/java/org/elasticsearch/action/admin/cluster/node/hotthreads/TransportNodesHotThreadsAction.java @@ -102,7 +102,7 @@ public class TransportNodesHotThreadsAction extends TransportNodesAction() { @Override diff --git a/core/src/main/java/org/elasticsearch/action/admin/cluster/stats/TransportClusterStatsAction.java b/core/src/main/java/org/elasticsearch/action/admin/cluster/stats/TransportClusterStatsAction.java index 3e4880d0a68..3fc2f4b631e 100644 --- a/core/src/main/java/org/elasticsearch/action/admin/cluster/stats/TransportClusterStatsAction.java +++ b/core/src/main/java/org/elasticsearch/action/admin/cluster/stats/TransportClusterStatsAction.java @@ -132,7 +132,7 @@ public class TransportClusterStatsAction extends TransportNodesAction public CreateIndexRequest() { } - /** - * Constructs a new request to create an index that was triggered by a different request, - * provided as an argument so that its headers and context can be copied to the new request. - */ - public CreateIndexRequest(ActionRequest request) { - super(request); - } - /** * Constructs a new request to create an index with the specified name. */ diff --git a/core/src/main/java/org/elasticsearch/action/admin/indices/flush/FlushRequest.java b/core/src/main/java/org/elasticsearch/action/admin/indices/flush/FlushRequest.java index 0152254d22a..7dc55c08fac 100644 --- a/core/src/main/java/org/elasticsearch/action/admin/indices/flush/FlushRequest.java +++ b/core/src/main/java/org/elasticsearch/action/admin/indices/flush/FlushRequest.java @@ -42,17 +42,6 @@ public class FlushRequest extends BroadcastRequest { private boolean force = false; private boolean waitIfOngoing = false; - public FlushRequest() { - } - - /** - * Copy constructor that creates a new flush request that is a copy of the one provided as an argument. - * The new request will inherit though headers and context from the original request that caused it. - */ - public FlushRequest(ActionRequest originalRequest) { - super(originalRequest); - } - /** * Constructs a new flush request against one or more indices. If nothing is provided, all indices will * be flushed. diff --git a/core/src/main/java/org/elasticsearch/action/admin/indices/flush/ShardFlushRequest.java b/core/src/main/java/org/elasticsearch/action/admin/indices/flush/ShardFlushRequest.java index ccf06be8bd0..3a9ec89db5d 100644 --- a/core/src/main/java/org/elasticsearch/action/admin/indices/flush/ShardFlushRequest.java +++ b/core/src/main/java/org/elasticsearch/action/admin/indices/flush/ShardFlushRequest.java @@ -31,7 +31,7 @@ public class ShardFlushRequest extends ReplicationRequest { private FlushRequest request = new FlushRequest(); public ShardFlushRequest(FlushRequest request, ShardId shardId) { - super(request, shardId); + super(shardId); this.request = request; } diff --git a/core/src/main/java/org/elasticsearch/action/admin/indices/flush/SyncedFlushRequest.java b/core/src/main/java/org/elasticsearch/action/admin/indices/flush/SyncedFlushRequest.java index 59719fe8877..2a14d66a765 100644 --- a/core/src/main/java/org/elasticsearch/action/admin/indices/flush/SyncedFlushRequest.java +++ b/core/src/main/java/org/elasticsearch/action/admin/indices/flush/SyncedFlushRequest.java @@ -36,17 +36,6 @@ import java.util.Arrays; */ public class SyncedFlushRequest extends BroadcastRequest { - public SyncedFlushRequest() { - } - - /** - * Copy constructor that creates a new synced flush request that is a copy of the one provided as an argument. - * The new request will inherit though headers and context from the original request that caused it. - */ - public SyncedFlushRequest(ActionRequest originalRequest) { - super(originalRequest); - } - /** * Constructs a new synced flush request against one or more indices. If nothing is provided, all indices will * be sync flushed. diff --git a/core/src/main/java/org/elasticsearch/action/admin/indices/mapping/get/GetFieldMappingsIndexRequest.java b/core/src/main/java/org/elasticsearch/action/admin/indices/mapping/get/GetFieldMappingsIndexRequest.java index 59844430b36..149cba9a33e 100644 --- a/core/src/main/java/org/elasticsearch/action/admin/indices/mapping/get/GetFieldMappingsIndexRequest.java +++ b/core/src/main/java/org/elasticsearch/action/admin/indices/mapping/get/GetFieldMappingsIndexRequest.java @@ -42,7 +42,6 @@ public class GetFieldMappingsIndexRequest extends SingleShardRequest { - public RefreshRequest() { - } - - /** - * Copy constructor that creates a new refresh request that is a copy of the one provided as an argument. - * The new request will inherit though headers and context from the original request that caused it. - */ - public RefreshRequest(ActionRequest originalRequest) { - super(originalRequest); - } - public RefreshRequest(String... indices) { super(indices); } diff --git a/core/src/main/java/org/elasticsearch/action/admin/indices/refresh/TransportRefreshAction.java b/core/src/main/java/org/elasticsearch/action/admin/indices/refresh/TransportRefreshAction.java index a76b714b31d..61aa4a86fc0 100644 --- a/core/src/main/java/org/elasticsearch/action/admin/indices/refresh/TransportRefreshAction.java +++ b/core/src/main/java/org/elasticsearch/action/admin/indices/refresh/TransportRefreshAction.java @@ -54,7 +54,7 @@ public class TransportRefreshAction extends TransportBroadcastReplicationAction< @Override protected ReplicationRequest newShardRequest(RefreshRequest request, ShardId shardId) { - return new ReplicationRequest(request, shardId); + return new ReplicationRequest(shardId); } @Override diff --git a/core/src/main/java/org/elasticsearch/action/bulk/BulkRequest.java b/core/src/main/java/org/elasticsearch/action/bulk/BulkRequest.java index 02e0ea40d65..8ddb8c32983 100644 --- a/core/src/main/java/org/elasticsearch/action/bulk/BulkRequest.java +++ b/core/src/main/java/org/elasticsearch/action/bulk/BulkRequest.java @@ -68,14 +68,6 @@ public class BulkRequest extends ActionRequest implements Composite public BulkRequest() { } - /** - * Creates a bulk request caused by some other request, which is provided as an - * argument so that its headers and context can be copied to the new request - */ - public BulkRequest(ActionRequest request) { - super(request); - } - /** * Adds a list of requests to be executed. Either index or delete requests. */ diff --git a/core/src/main/java/org/elasticsearch/action/bulk/BulkShardRequest.java b/core/src/main/java/org/elasticsearch/action/bulk/BulkShardRequest.java index 1edba16220a..275e2819cf6 100644 --- a/core/src/main/java/org/elasticsearch/action/bulk/BulkShardRequest.java +++ b/core/src/main/java/org/elasticsearch/action/bulk/BulkShardRequest.java @@ -41,7 +41,7 @@ public class BulkShardRequest extends ReplicationRequest { } BulkShardRequest(BulkRequest bulkRequest, ShardId shardId, boolean refresh, BulkItemRequest[] items) { - super(bulkRequest, shardId); + super(shardId); this.items = items; this.refresh = refresh; } diff --git a/core/src/main/java/org/elasticsearch/action/bulk/TransportBulkAction.java b/core/src/main/java/org/elasticsearch/action/bulk/TransportBulkAction.java index 7252993427f..4750d9fb646 100644 --- a/core/src/main/java/org/elasticsearch/action/bulk/TransportBulkAction.java +++ b/core/src/main/java/org/elasticsearch/action/bulk/TransportBulkAction.java @@ -114,7 +114,7 @@ public class TransportBulkAction extends HandledTransportAction> entry : indicesAndTypes.entrySet()) { final String index = entry.getKey(); if (autoCreateIndex.shouldAutoCreate(index, state)) { - CreateIndexRequest createIndexRequest = new CreateIndexRequest(bulkRequest); + CreateIndexRequest createIndexRequest = new CreateIndexRequest(); createIndexRequest.index(index); for (String type : entry.getValue()) { createIndexRequest.mapping(type); diff --git a/core/src/main/java/org/elasticsearch/action/delete/DeleteRequest.java b/core/src/main/java/org/elasticsearch/action/delete/DeleteRequest.java index ba63f33ee17..6c609eb9f31 100644 --- a/core/src/main/java/org/elasticsearch/action/delete/DeleteRequest.java +++ b/core/src/main/java/org/elasticsearch/action/delete/DeleteRequest.java @@ -92,7 +92,7 @@ public class DeleteRequest extends ReplicationRequest implements * The new request will inherit though headers and context from the original request that caused it. */ public DeleteRequest(DeleteRequest request, ActionRequest originalRequest) { - super(request, originalRequest); + super(request); this.type = request.type(); this.id = request.id(); this.routing = request.routing(); @@ -102,14 +102,6 @@ public class DeleteRequest extends ReplicationRequest implements this.versionType = request.versionType(); } - /** - * Creates a delete request caused by some other request, which is provided as an - * argument so that its headers and context can be copied to the new request - */ - public DeleteRequest(ActionRequest request) { - super(request); - } - @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = super.validate(); diff --git a/core/src/main/java/org/elasticsearch/action/delete/TransportDeleteAction.java b/core/src/main/java/org/elasticsearch/action/delete/TransportDeleteAction.java index f80b1a24396..c235144c662 100644 --- a/core/src/main/java/org/elasticsearch/action/delete/TransportDeleteAction.java +++ b/core/src/main/java/org/elasticsearch/action/delete/TransportDeleteAction.java @@ -72,7 +72,7 @@ public class TransportDeleteAction extends TransportReplicationAction listener) { ClusterState state = clusterService.state(); if (autoCreateIndex.shouldAutoCreate(request.index(), state)) { - createIndexAction.execute(new CreateIndexRequest(request).index(request.index()).cause("auto(delete api)").masterNodeTimeout(request.timeout()), new ActionListener() { + createIndexAction.execute(new CreateIndexRequest().index(request.index()).cause("auto(delete api)").masterNodeTimeout(request.timeout()), new ActionListener() { @Override public void onResponse(CreateIndexResponse result) { innerExecute(request, listener); diff --git a/core/src/main/java/org/elasticsearch/action/get/GetRequest.java b/core/src/main/java/org/elasticsearch/action/get/GetRequest.java index c6919e858d1..1c83cbeb631 100644 --- a/core/src/main/java/org/elasticsearch/action/get/GetRequest.java +++ b/core/src/main/java/org/elasticsearch/action/get/GetRequest.java @@ -19,7 +19,6 @@ package org.elasticsearch.action.get; -import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.RealtimeRequest; import org.elasticsearch.action.ValidateActions; @@ -72,8 +71,7 @@ public class GetRequest extends SingleShardRequest implements Realti * Copy constructor that creates a new get request that is a copy of the one provided as an argument. * The new request will inherit though headers and context from the original request that caused it. */ - public GetRequest(GetRequest getRequest, ActionRequest originalRequest) { - super(originalRequest); + public GetRequest(GetRequest getRequest) { this.index = getRequest.index; this.type = getRequest.type; this.id = getRequest.id; @@ -98,14 +96,6 @@ public class GetRequest extends SingleShardRequest implements Realti this.type = "_all"; } - /** - * Constructs a new get request starting from the provided request, meaning that it will - * inherit its headers and context, and against the specified index. - */ - public GetRequest(ActionRequest request, String index) { - super(request, index); - } - /** * Constructs a new get request against the specified index with the type and id. * diff --git a/core/src/main/java/org/elasticsearch/action/get/MultiGetRequest.java b/core/src/main/java/org/elasticsearch/action/get/MultiGetRequest.java index db3c0f72bfd..f67e2b27b56 100644 --- a/core/src/main/java/org/elasticsearch/action/get/MultiGetRequest.java +++ b/core/src/main/java/org/elasticsearch/action/get/MultiGetRequest.java @@ -266,18 +266,6 @@ public class MultiGetRequest extends ActionRequest implements I List items = new ArrayList<>(); - public MultiGetRequest() { - - } - - /** - * Creates a multi get request caused by some other request, which is provided as an - * argument so that its headers and context can be copied to the new request - */ - public MultiGetRequest(ActionRequest request) { - super(request); - } - public List getItems() { return this.items; } diff --git a/core/src/main/java/org/elasticsearch/action/get/MultiGetShardRequest.java b/core/src/main/java/org/elasticsearch/action/get/MultiGetShardRequest.java index 6715319bc32..9250204858f 100644 --- a/core/src/main/java/org/elasticsearch/action/get/MultiGetShardRequest.java +++ b/core/src/main/java/org/elasticsearch/action/get/MultiGetShardRequest.java @@ -45,7 +45,7 @@ public class MultiGetShardRequest extends SingleShardRequest(); diff --git a/core/src/main/java/org/elasticsearch/action/index/IndexRequest.java b/core/src/main/java/org/elasticsearch/action/index/IndexRequest.java index 9899a5493aa..5057fdb829c 100644 --- a/core/src/main/java/org/elasticsearch/action/index/IndexRequest.java +++ b/core/src/main/java/org/elasticsearch/action/index/IndexRequest.java @@ -21,7 +21,6 @@ package org.elasticsearch.action.index; import org.elasticsearch.ElasticsearchGenerationException; import org.elasticsearch.Version; -import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.DocumentRequest; import org.elasticsearch.action.RoutingMissingException; @@ -158,20 +157,12 @@ public class IndexRequest extends ReplicationRequest implements Do public IndexRequest() { } - /** - * Creates an index request caused by some other request, which is provided as an - * argument so that its headers and context can be copied to the new request - */ - public IndexRequest(ActionRequest request) { - super(request); - } - /** * Copy constructor that creates a new index request that is a copy of the one provided as an argument. * The new request will inherit though headers and context from the original request that caused it. */ - public IndexRequest(IndexRequest indexRequest, ActionRequest originalRequest) { - super(indexRequest, originalRequest); + public IndexRequest(IndexRequest indexRequest) { + super(indexRequest); this.type = indexRequest.type; this.id = indexRequest.id; this.routing = indexRequest.routing; diff --git a/core/src/main/java/org/elasticsearch/action/index/TransportIndexAction.java b/core/src/main/java/org/elasticsearch/action/index/TransportIndexAction.java index 620056ded4e..4ae522d29ca 100644 --- a/core/src/main/java/org/elasticsearch/action/index/TransportIndexAction.java +++ b/core/src/main/java/org/elasticsearch/action/index/TransportIndexAction.java @@ -88,7 +88,7 @@ public class TransportIndexAction extends TransportReplicationAction impleme } PercolateRequest(PercolateRequest request, BytesReference docSource) { - super(request); this.indices = request.indices(); this.documentType = request.documentType(); this.routing = request.routing(); @@ -274,7 +273,7 @@ public class PercolateRequest extends BroadcastRequest impleme source = in.readBytesReference(); docSource = in.readBytesReference(); if (in.readBoolean()) { - getRequest = new GetRequest(null); + getRequest = new GetRequest(); getRequest.readFrom(in); } onlyCount = in.readBoolean(); diff --git a/core/src/main/java/org/elasticsearch/action/percolate/TransportMultiPercolateAction.java b/core/src/main/java/org/elasticsearch/action/percolate/TransportMultiPercolateAction.java index bf7b9e5307b..987ca3c4cd9 100644 --- a/core/src/main/java/org/elasticsearch/action/percolate/TransportMultiPercolateAction.java +++ b/core/src/main/java/org/elasticsearch/action/percolate/TransportMultiPercolateAction.java @@ -97,7 +97,7 @@ public class TransportMultiPercolateAction extends HandledTransportAction() { @Override public void onResponse(GetResponse getResponse) { @@ -150,7 +150,7 @@ public class TransportPercolateAction extends TransportBroadcastAction(); diff --git a/core/src/main/java/org/elasticsearch/action/search/ClearScrollRequest.java b/core/src/main/java/org/elasticsearch/action/search/ClearScrollRequest.java index b390b77504a..17343e86912 100644 --- a/core/src/main/java/org/elasticsearch/action/search/ClearScrollRequest.java +++ b/core/src/main/java/org/elasticsearch/action/search/ClearScrollRequest.java @@ -37,17 +37,6 @@ public class ClearScrollRequest extends ActionRequest { private List scrollIds; - public ClearScrollRequest() { - } - - /** - * Creates a clear scroll request caused by some other request, which is provided as an - * argument so that its headers and context can be copied to the new request - */ - public ClearScrollRequest(ActionRequest request) { - super(request); - } - public List getScrollIds() { return scrollIds; } diff --git a/core/src/main/java/org/elasticsearch/action/search/SearchRequest.java b/core/src/main/java/org/elasticsearch/action/search/SearchRequest.java index 8014e4acb6c..10a1ad2efce 100644 --- a/core/src/main/java/org/elasticsearch/action/search/SearchRequest.java +++ b/core/src/main/java/org/elasticsearch/action/search/SearchRequest.java @@ -80,8 +80,7 @@ public class SearchRequest extends ActionRequest implements Indic * Copy constructor that creates a new search request that is a copy of the one provided as an argument. * The new request will inherit though headers and context from the original request that caused it. */ - public SearchRequest(SearchRequest searchRequest, ActionRequest originalRequest) { - super(originalRequest); + public SearchRequest(SearchRequest searchRequest) { this.searchType = searchRequest.searchType; this.indices = searchRequest.indices; this.routing = searchRequest.routing; @@ -94,15 +93,6 @@ public class SearchRequest extends ActionRequest implements Indic this.indicesOptions = searchRequest.indicesOptions; } - /** - * Constructs a new search request starting from the provided request, meaning that it will - * inherit its headers and context - */ - public SearchRequest(ActionRequest request) { - super(request); - this.source = new SearchSourceBuilder(); - } - /** * Constructs a new search request against the indices. No indices provided here means that search * will run against all indices. diff --git a/core/src/main/java/org/elasticsearch/action/search/SearchScrollRequest.java b/core/src/main/java/org/elasticsearch/action/search/SearchScrollRequest.java index 537d61ac558..c1ff788dae5 100644 --- a/core/src/main/java/org/elasticsearch/action/search/SearchScrollRequest.java +++ b/core/src/main/java/org/elasticsearch/action/search/SearchScrollRequest.java @@ -46,14 +46,6 @@ public class SearchScrollRequest extends ActionRequest { this.scrollId = scrollId; } - /** - * Creates a scroll request caused by some other request, which is provided as an - * argument so that its headers and context can be copied to the new request - */ - public SearchScrollRequest(ActionRequest request) { - super(request); - } - @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; diff --git a/core/src/main/java/org/elasticsearch/action/search/TransportMultiSearchAction.java b/core/src/main/java/org/elasticsearch/action/search/TransportMultiSearchAction.java index fd2b257e53e..18490735631 100644 --- a/core/src/main/java/org/elasticsearch/action/search/TransportMultiSearchAction.java +++ b/core/src/main/java/org/elasticsearch/action/search/TransportMultiSearchAction.java @@ -59,7 +59,7 @@ public class TransportMultiSearchAction extends HandledTransportAction() { @Override public void onResponse(SearchResponse searchResponse) { diff --git a/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryAndFetchAction.java b/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryAndFetchAction.java index 7244a1ff58a..6d22264815b 100644 --- a/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryAndFetchAction.java +++ b/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryAndFetchAction.java @@ -135,7 +135,7 @@ public class TransportSearchDfsQueryAndFetchAction extends TransportSearchTypeAc public void doRun() throws IOException { sortedShardList = searchPhaseController.sortDocs(true, queryFetchResults); final InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, queryFetchResults, - queryFetchResults, request); + queryFetchResults); String scrollId = null; if (request.scroll() != null) { scrollId = TransportSearchHelper.buildScrollId(request.searchType(), firstResults, null); diff --git a/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryThenFetchAction.java b/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryThenFetchAction.java index faaf1215542..31128cea961 100644 --- a/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryThenFetchAction.java +++ b/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchDfsQueryThenFetchAction.java @@ -211,7 +211,7 @@ public class TransportSearchDfsQueryThenFetchAction extends TransportSearchTypeA @Override public void doRun() throws IOException { final InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, queryResults, - fetchResults, request); + fetchResults); String scrollId = null; if (request.scroll() != null) { scrollId = TransportSearchHelper.buildScrollId(request.searchType(), firstResults, null); diff --git a/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryAndFetchAction.java b/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryAndFetchAction.java index 3c4f5419f00..0e1e8db5519 100644 --- a/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryAndFetchAction.java +++ b/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryAndFetchAction.java @@ -82,7 +82,7 @@ public class TransportSearchQueryAndFetchAction extends TransportSearchTypeActio boolean useScroll = request.scroll() != null; sortedShardList = searchPhaseController.sortDocs(useScroll, firstResults); final InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, firstResults, - firstResults, request); + firstResults); String scrollId = null; if (request.scroll() != null) { scrollId = buildScrollId(request.searchType(), firstResults, null); diff --git a/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryThenFetchAction.java b/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryThenFetchAction.java index 1d8589e7a96..c63287d9956 100644 --- a/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryThenFetchAction.java +++ b/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryThenFetchAction.java @@ -146,7 +146,7 @@ public class TransportSearchQueryThenFetchAction extends TransportSearchTypeActi @Override public void doRun() throws IOException { final InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, firstResults, - fetchResults, request); + fetchResults); String scrollId = null; if (request.scroll() != null) { scrollId = TransportSearchHelper.buildScrollId(request.searchType(), firstResults, null); diff --git a/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryAndFetchAction.java b/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryAndFetchAction.java index 2a953f9b732..b718baaa294 100644 --- a/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryAndFetchAction.java +++ b/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryAndFetchAction.java @@ -193,7 +193,7 @@ public class TransportSearchScrollQueryAndFetchAction extends AbstractComponent private void innerFinishHim() throws Exception { ScoreDoc[] sortedShardList = searchPhaseController.sortDocs(true, queryFetchResults); final InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, queryFetchResults, - queryFetchResults, request); + queryFetchResults); String scrollId = null; if (request.scroll() != null) { scrollId = request.scrollId(); diff --git a/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryThenFetchAction.java b/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryThenFetchAction.java index 8dd9c139c33..93a28b29aa1 100644 --- a/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryThenFetchAction.java +++ b/core/src/main/java/org/elasticsearch/action/search/type/TransportSearchScrollQueryThenFetchAction.java @@ -208,7 +208,7 @@ public class TransportSearchScrollQueryThenFetchAction extends AbstractComponent IntArrayList docIds = entry.value; final QuerySearchResult querySearchResult = queryResults.get(entry.index); ScoreDoc lastEmittedDoc = lastEmittedDocPerShard[entry.index]; - ShardFetchRequest shardFetchRequest = new ShardFetchRequest(request, querySearchResult.id(), docIds, lastEmittedDoc); + ShardFetchRequest shardFetchRequest = new ShardFetchRequest(querySearchResult.id(), docIds, lastEmittedDoc); DiscoveryNode node = nodes.get(querySearchResult.shardTarget().nodeId()); searchService.sendExecuteFetchScroll(node, shardFetchRequest, new ActionListener() { @Override @@ -243,7 +243,7 @@ public class TransportSearchScrollQueryThenFetchAction extends AbstractComponent } private void innerFinishHim() { - InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, queryResults, fetchResults, request); + InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, queryResults, fetchResults); String scrollId = null; if (request.scroll() != null) { scrollId = request.scrollId(); diff --git a/core/src/main/java/org/elasticsearch/action/suggest/TransportSuggestAction.java b/core/src/main/java/org/elasticsearch/action/suggest/TransportSuggestAction.java index 6bc62cf83bb..424d1b6a48d 100644 --- a/core/src/main/java/org/elasticsearch/action/suggest/TransportSuggestAction.java +++ b/core/src/main/java/org/elasticsearch/action/suggest/TransportSuggestAction.java @@ -143,7 +143,7 @@ public class TransportSuggestAction extends TransportBroadcastAction extends ActionRequest< private IndicesOptions indicesOptions = IndicesOptions.strictExpandOpenAndForbidClosed(); public BroadcastRequest() { - - } - - protected BroadcastRequest(ActionRequest originalRequest) { - super(originalRequest); } protected BroadcastRequest(String[] indices) { diff --git a/core/src/main/java/org/elasticsearch/action/support/broadcast/BroadcastShardRequest.java b/core/src/main/java/org/elasticsearch/action/support/broadcast/BroadcastShardRequest.java index 8e22a90b9d7..921724e6572 100644 --- a/core/src/main/java/org/elasticsearch/action/support/broadcast/BroadcastShardRequest.java +++ b/core/src/main/java/org/elasticsearch/action/support/broadcast/BroadcastShardRequest.java @@ -42,7 +42,6 @@ public abstract class BroadcastShardRequest extends TransportRequest implements } protected BroadcastShardRequest(ShardId shardId, BroadcastRequest request) { - super(request); this.shardId = shardId; this.originalIndices = new OriginalIndices(request); } diff --git a/core/src/main/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeAction.java b/core/src/main/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeAction.java index e8f4a0d83cd..30aeb86e136 100644 --- a/core/src/main/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeAction.java +++ b/core/src/main/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeAction.java @@ -433,7 +433,6 @@ public abstract class TransportBroadcastByNodeAction shards) { - super(request); this.indicesLevelRequest = request; this.shards = shards; this.nodeId = nodeId; diff --git a/core/src/main/java/org/elasticsearch/action/support/master/AcknowledgedRequest.java b/core/src/main/java/org/elasticsearch/action/support/master/AcknowledgedRequest.java index 156016e9599..d8b1e104fa2 100644 --- a/core/src/main/java/org/elasticsearch/action/support/master/AcknowledgedRequest.java +++ b/core/src/main/java/org/elasticsearch/action/support/master/AcknowledgedRequest.java @@ -42,10 +42,6 @@ public abstract class AcknowledgedRequest extends M protected AcknowledgedRequest() { } - protected AcknowledgedRequest(ActionRequest request) { - super(request); - } - /** * Allows to set the timeout * @param timeout timeout as a string (e.g. 1s) diff --git a/core/src/main/java/org/elasticsearch/action/support/master/MasterNodeRequest.java b/core/src/main/java/org/elasticsearch/action/support/master/MasterNodeRequest.java index d791354d809..500c6184675 100644 --- a/core/src/main/java/org/elasticsearch/action/support/master/MasterNodeRequest.java +++ b/core/src/main/java/org/elasticsearch/action/support/master/MasterNodeRequest.java @@ -36,11 +36,6 @@ public abstract class MasterNodeRequest extends Act protected TimeValue masterNodeTimeout = DEFAULT_MASTER_NODE_TIMEOUT; protected MasterNodeRequest() { - - } - - protected MasterNodeRequest(ActionRequest request) { - super(request); } /** diff --git a/core/src/main/java/org/elasticsearch/action/support/master/TransportMasterNodeAction.java b/core/src/main/java/org/elasticsearch/action/support/master/TransportMasterNodeAction.java index 60064a5ff46..d35bf300cc2 100644 --- a/core/src/main/java/org/elasticsearch/action/support/master/TransportMasterNodeAction.java +++ b/core/src/main/java/org/elasticsearch/action/support/master/TransportMasterNodeAction.java @@ -121,7 +121,7 @@ public abstract class TransportMasterNodeAction extends Actio } - protected BaseNodesRequest(ActionRequest request, String... nodesIds) { - super(request); - this.nodesIds = nodesIds; - } - protected BaseNodesRequest(String... nodesIds) { this.nodesIds = nodesIds; } diff --git a/core/src/main/java/org/elasticsearch/action/support/replication/ReplicationRequest.java b/core/src/main/java/org/elasticsearch/action/support/replication/ReplicationRequest.java index adbe199824e..61d2a5ab890 100644 --- a/core/src/main/java/org/elasticsearch/action/support/replication/ReplicationRequest.java +++ b/core/src/main/java/org/elasticsearch/action/support/replication/ReplicationRequest.java @@ -58,35 +58,20 @@ public class ReplicationRequest extends ActionRequ } - /** - * Creates a new request that inherits headers and context from the request provided as argument. - */ - public ReplicationRequest(ActionRequest request) { - super(request); - } /** * Creates a new request with resolved shard id */ - public ReplicationRequest(ActionRequest request, ShardId shardId) { - super(request); + public ReplicationRequest(ShardId shardId) { this.index = shardId.getIndex(); this.shardId = shardId; } - /** - * Copy constructor that creates a new request that is a copy of the one provided as an argument. - */ - protected ReplicationRequest(T request) { - this(request, request); - } - /** * Copy constructor that creates a new request that is a copy of the one provided as an argument. * The new request will inherit though headers and context from the original request that caused it. */ - protected ReplicationRequest(T request, ActionRequest originalRequest) { - super(originalRequest); + protected ReplicationRequest(T request) { this.timeout = request.timeout(); this.index = request.index(); this.consistencyLevel = request.consistencyLevel(); diff --git a/core/src/main/java/org/elasticsearch/action/support/replication/TransportReplicationAction.java b/core/src/main/java/org/elasticsearch/action/support/replication/TransportReplicationAction.java index 0014404057f..3c3ed714b55 100644 --- a/core/src/main/java/org/elasticsearch/action/support/replication/TransportReplicationAction.java +++ b/core/src/main/java/org/elasticsearch/action/support/replication/TransportReplicationAction.java @@ -52,6 +52,7 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.engine.VersionConflictEngineException; import org.elasticsearch.index.shard.IndexShard; @@ -302,7 +303,7 @@ public abstract class TransportReplicationAction listener) { this.request = request; this.listener = listener; - this.observer = new ClusterStateObserver(clusterService, request.timeout(), logger); + this.observer = new ClusterStateObserver(clusterService, request.timeout(), logger, threadPool.getThreadContext()); } @Override @@ -515,9 +519,12 @@ public abstract class TransportReplicationAction extends A public SingleShardRequest() { } - protected SingleShardRequest(String index) { - this.index = index; - } - - protected SingleShardRequest(ActionRequest request) { - super(request); - } - - protected SingleShardRequest(ActionRequest request, String index) { - super(request); + public SingleShardRequest(String index) { this.index = index; } diff --git a/core/src/main/java/org/elasticsearch/action/support/tasks/BaseTasksRequest.java b/core/src/main/java/org/elasticsearch/action/support/tasks/BaseTasksRequest.java index a1e485bb64f..ea6698d439f 100644 --- a/core/src/main/java/org/elasticsearch/action/support/tasks/BaseTasksRequest.java +++ b/core/src/main/java/org/elasticsearch/action/support/tasks/BaseTasksRequest.java @@ -61,15 +61,6 @@ public class BaseTasksRequest extends ActionRequest< return null; } - /** - * Get information about tasks from nodes based on the nodes ids specified. - * If none are passed, information for all nodes will be returned. - */ - public BaseTasksRequest(ActionRequest request, String... nodesIds) { - super(request); - this.nodesIds = nodesIds; - } - /** * Get information about tasks from nodes based on the nodes ids specified. * If none are passed, information for all nodes will be returned. diff --git a/core/src/main/java/org/elasticsearch/action/support/tasks/TransportTasksAction.java b/core/src/main/java/org/elasticsearch/action/support/tasks/TransportTasksAction.java index 42be7e4eefc..d2ce298565f 100644 --- a/core/src/main/java/org/elasticsearch/action/support/tasks/TransportTasksAction.java +++ b/core/src/main/java/org/elasticsearch/action/support/tasks/TransportTasksAction.java @@ -291,7 +291,7 @@ public abstract class TransportTasksAction< } protected NodeTaskRequest(TasksRequest tasksRequest) { - super(tasksRequest); + super(); this.tasksRequest = tasksRequest; } diff --git a/core/src/main/java/org/elasticsearch/action/termvectors/MultiTermVectorsShardRequest.java b/core/src/main/java/org/elasticsearch/action/termvectors/MultiTermVectorsShardRequest.java index 5f541b02c71..6356c554991 100644 --- a/core/src/main/java/org/elasticsearch/action/termvectors/MultiTermVectorsShardRequest.java +++ b/core/src/main/java/org/elasticsearch/action/termvectors/MultiTermVectorsShardRequest.java @@ -41,8 +41,8 @@ public class MultiTermVectorsShardRequest extends SingleShardRequest(); diff --git a/core/src/main/java/org/elasticsearch/action/termvectors/TransportMultiTermVectorsAction.java b/core/src/main/java/org/elasticsearch/action/termvectors/TransportMultiTermVectorsAction.java index 3943d2e6a67..535d89c101c 100644 --- a/core/src/main/java/org/elasticsearch/action/termvectors/TransportMultiTermVectorsAction.java +++ b/core/src/main/java/org/elasticsearch/action/termvectors/TransportMultiTermVectorsAction.java @@ -82,7 +82,7 @@ public class TransportMultiTermVectorsAction extends HandledTransportAction listener) { // if we don't have a master, we don't have metadata, that's fine, let it find a master using create index API if (autoCreateIndex.shouldAutoCreate(request.index(), clusterService.state())) { - createIndexAction.execute(new CreateIndexRequest(request).index(request.index()).cause("auto(update api)").masterNodeTimeout(request.timeout()), new ActionListener() { + createIndexAction.execute(new CreateIndexRequest().index(request.index()).cause("auto(update api)").masterNodeTimeout(request.timeout()), new ActionListener() { @Override public void onResponse(CreateIndexResponse result) { innerExecute(request, listener); @@ -164,12 +164,12 @@ public class TransportUpdateAction extends TransportInstanceSingleOperationActio } protected void shardOperation(final UpdateRequest request, final ActionListener listener, final int retryCount) { - IndexService indexService = indicesService.indexServiceSafe(request.concreteIndex()); - IndexShard indexShard = indexService.getShard(request.shardId()); + final IndexService indexService = indicesService.indexServiceSafe(request.concreteIndex()); + final IndexShard indexShard = indexService.getShard(request.shardId()); final UpdateHelper.Result result = updateHelper.prepare(request, indexShard); switch (result.operation()) { case UPSERT: - IndexRequest upsertRequest = new IndexRequest(result.action(), request); + IndexRequest upsertRequest = new IndexRequest((IndexRequest)result.action()); // we fetch it from the index request so we don't generate the bytes twice, its already done in the index request final BytesReference upsertSourceBytes = upsertRequest.source(); indexAction.execute(upsertRequest, new ActionListener() { @@ -206,7 +206,7 @@ public class TransportUpdateAction extends TransportInstanceSingleOperationActio }); break; case INDEX: - IndexRequest indexRequest = new IndexRequest(result.action(), request); + IndexRequest indexRequest = new IndexRequest((IndexRequest)result.action()); // we fetch it from the index request so we don't generate the bytes twice, its already done in the index request final BytesReference indexSourceBytes = indexRequest.source(); indexAction.execute(indexRequest, new ActionListener() { diff --git a/core/src/main/java/org/elasticsearch/action/update/UpdateHelper.java b/core/src/main/java/org/elasticsearch/action/update/UpdateHelper.java index d28ba2986e2..48cf8a294c1 100644 --- a/core/src/main/java/org/elasticsearch/action/update/UpdateHelper.java +++ b/core/src/main/java/org/elasticsearch/action/update/UpdateHelper.java @@ -44,6 +44,7 @@ import org.elasticsearch.index.mapper.internal.TimestampFieldMapper; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.script.ExecutableScript; +import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptContext; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.fetch.source.FetchSourceContext; @@ -99,7 +100,7 @@ public class UpdateHelper extends AbstractComponent { // Tell the script that this is a create and not an update ctx.put("op", "create"); ctx.put("_source", upsertDoc); - ctx = executeScript(request, ctx); + ctx = executeScript(request.script, ctx); //Allow the script to set TTL using ctx._ttl if (ttl == null) { ttl = getTTLFromScriptContext(ctx); @@ -193,7 +194,7 @@ public class UpdateHelper extends AbstractComponent { ctx.put("_ttl", originalTtl); ctx.put("_source", sourceAndContent.v2()); - ctx = executeScript(request, ctx); + ctx = executeScript(request.script, ctx); operation = (String) ctx.get("op"); @@ -243,14 +244,14 @@ public class UpdateHelper extends AbstractComponent { } } - private Map executeScript(UpdateRequest request, Map ctx) { + private Map executeScript(Script script, Map ctx) { try { if (scriptService != null) { - ExecutableScript script = scriptService.executable(request.script, ScriptContext.Standard.UPDATE, request, Collections.emptyMap()); - script.setNextVar("ctx", ctx); - script.run(); + ExecutableScript executableScript = scriptService.executable(script, ScriptContext.Standard.UPDATE, Collections.emptyMap()); + executableScript.setNextVar("ctx", ctx); + executableScript.run(); // we need to unwrap the ctx... - ctx = (Map) script.unwrap(ctx); + ctx = (Map) executableScript.unwrap(ctx); } } catch (Exception e) { throw new IllegalArgumentException("failed to execute script", e); diff --git a/core/src/main/java/org/elasticsearch/client/Client.java b/core/src/main/java/org/elasticsearch/client/Client.java index e7461dabfe1..e1bcaf3ef5a 100644 --- a/core/src/main/java/org/elasticsearch/client/Client.java +++ b/core/src/main/java/org/elasticsearch/client/Client.java @@ -19,8 +19,12 @@ package org.elasticsearch.client; +import org.elasticsearch.action.Action; import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.ActionListener; +import org.elasticsearch.action.ActionRequest; +import org.elasticsearch.action.ActionRequestBuilder; +import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; @@ -80,11 +84,12 @@ import org.elasticsearch.action.termvectors.TermVectorsResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateRequestBuilder; import org.elasticsearch.action.update.UpdateResponse; -import org.elasticsearch.client.support.Headers; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.lease.Releasable; import org.elasticsearch.common.settings.Settings; +import java.util.Map; + /** * A client provides a one stop interface for performing actions/operations against the cluster. *

@@ -597,5 +602,5 @@ public interface Client extends ElasticsearchClient, Releasable { */ Settings settings(); - Headers headers(); + Client filterWithHeader(Map headers); } diff --git a/core/src/main/java/org/elasticsearch/client/FilterClient.java b/core/src/main/java/org/elasticsearch/client/FilterClient.java index 06d81f0c9d5..be7160fca06 100644 --- a/core/src/main/java/org/elasticsearch/client/FilterClient.java +++ b/core/src/main/java/org/elasticsearch/client/FilterClient.java @@ -42,7 +42,7 @@ public abstract class FilterClient extends AbstractClient { * @see #in() */ public FilterClient(Client in) { - super(in.settings(), in.threadPool(), in.headers()); + super(in.settings(), in.threadPool()); this.in = in; } diff --git a/core/src/main/java/org/elasticsearch/client/node/NodeClient.java b/core/src/main/java/org/elasticsearch/client/node/NodeClient.java index 65adfad64dc..350b452dc21 100644 --- a/core/src/main/java/org/elasticsearch/client/node/NodeClient.java +++ b/core/src/main/java/org/elasticsearch/client/node/NodeClient.java @@ -27,7 +27,6 @@ import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.GenericAction; import org.elasticsearch.action.support.TransportAction; import org.elasticsearch.client.support.AbstractClient; -import org.elasticsearch.client.support.Headers; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.threadpool.ThreadPool; @@ -44,8 +43,8 @@ public class NodeClient extends AbstractClient { private final Map actions; @Inject - public NodeClient(Settings settings, ThreadPool threadPool, Headers headers, Map actions) { - super(settings, threadPool, headers); + public NodeClient(Settings settings, ThreadPool threadPool, Map actions) { + super(settings, threadPool); this.actions = unmodifiableMap(actions); } diff --git a/core/src/main/java/org/elasticsearch/client/node/NodeClientModule.java b/core/src/main/java/org/elasticsearch/client/node/NodeClientModule.java index fb0891da8cc..de134887303 100644 --- a/core/src/main/java/org/elasticsearch/client/node/NodeClientModule.java +++ b/core/src/main/java/org/elasticsearch/client/node/NodeClientModule.java @@ -20,7 +20,6 @@ package org.elasticsearch.client.node; import org.elasticsearch.client.Client; -import org.elasticsearch.client.support.Headers; import org.elasticsearch.common.inject.AbstractModule; /** @@ -30,7 +29,6 @@ public class NodeClientModule extends AbstractModule { @Override protected void configure() { - bind(Headers.class).asEagerSingleton(); bind(Client.class).to(NodeClient.class).asEagerSingleton(); } } diff --git a/core/src/main/java/org/elasticsearch/client/support/AbstractClient.java b/core/src/main/java/org/elasticsearch/client/support/AbstractClient.java index e5a465442bb..53681025301 100644 --- a/core/src/main/java/org/elasticsearch/client/support/AbstractClient.java +++ b/core/src/main/java/org/elasticsearch/client/support/AbstractClient.java @@ -317,12 +317,16 @@ import org.elasticsearch.client.AdminClient; import org.elasticsearch.client.Client; import org.elasticsearch.client.ClusterAdminClient; import org.elasticsearch.client.ElasticsearchClient; +import org.elasticsearch.client.FilterClient; import org.elasticsearch.client.IndicesAdminClient; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.threadpool.ThreadPool; +import java.util.Map; + /** * */ @@ -330,23 +334,15 @@ public abstract class AbstractClient extends AbstractComponent implements Client private final ThreadPool threadPool; private final Admin admin; - - private final Headers headers; private final ThreadedActionListener.Wrapper threadedWrapper; - public AbstractClient(Settings settings, ThreadPool threadPool, Headers headers) { + public AbstractClient(Settings settings, ThreadPool threadPool) { super(settings); this.threadPool = threadPool; - this.headers = headers; this.admin = new Admin(this); this.threadedWrapper = new ThreadedActionListener.Wrapper(logger, settings, threadPool); } - @Override - public Headers headers() { - return this.headers; - } - @Override public final Settings settings() { return this.settings; @@ -379,7 +375,6 @@ public abstract class AbstractClient extends AbstractComponent implements Client */ @Override public final > void execute(Action action, Request request, ActionListener listener) { - headers.applyTo(request); listener = threadedWrapper.wrap(listener); doExecute(action, request, listener); } @@ -1672,4 +1667,18 @@ public abstract class AbstractClient extends AbstractComponent implements Client execute(GetSettingsAction.INSTANCE, request, listener); } } + + @Override + public Client filterWithHeader(Map headers) { + return new FilterClient(this) { + @Override + protected > void doExecute(Action action, Request request, ActionListener listener) { + ThreadContext threadContext = threadPool().getThreadContext(); + try (ThreadContext.StoredContext ctx = threadContext.stashContext()) { + threadContext.putHeader(headers); + super.doExecute(action, request, listener); + } + } + }; + } } diff --git a/core/src/main/java/org/elasticsearch/client/support/Headers.java b/core/src/main/java/org/elasticsearch/client/support/Headers.java deleted file mode 100644 index f46bd0a1c9d..00000000000 --- a/core/src/main/java/org/elasticsearch/client/support/Headers.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.client.support; - -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.transport.TransportMessage; - -/** - * Client request headers picked up from the client settings. Applied to every - * request sent by the client (both transport and node clients) - */ -public class Headers { - - public static final String PREFIX = "request.headers"; - - public static final Headers EMPTY = new Headers(Settings.EMPTY) { - @Override - public > M applyTo(M message) { - return message; - } - }; - - private final Settings headers; - - @Inject - public Headers(Settings settings) { - headers = resolveHeaders(settings); - } - - public > M applyTo(M message) { - for (String key : headers.names()) { - if (!message.hasHeader(key)) { - message.putHeader(key, headers.get(key)); - } - } - return message; - } - - public Settings headers() { - return headers; - } - - static Settings resolveHeaders(Settings settings) { - Settings headers = settings.getAsSettings(PREFIX); - return headers != null ? headers : Settings.EMPTY; - } -} diff --git a/core/src/main/java/org/elasticsearch/client/transport/TransportClient.java b/core/src/main/java/org/elasticsearch/client/transport/TransportClient.java index 3b8be668f43..1a380c7ab37 100644 --- a/core/src/main/java/org/elasticsearch/client/transport/TransportClient.java +++ b/core/src/main/java/org/elasticsearch/client/transport/TransportClient.java @@ -28,7 +28,6 @@ import org.elasticsearch.action.ActionRequestBuilder; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.cache.recycler.PageCacheRecycler; import org.elasticsearch.client.support.AbstractClient; -import org.elasticsearch.client.support.Headers; import org.elasticsearch.client.transport.support.TransportProxyClient; import org.elasticsearch.cluster.ClusterNameModule; import org.elasticsearch.cluster.node.DiscoveryNode; @@ -173,7 +172,7 @@ public class TransportClient extends AbstractClient { private final TransportProxyClient proxy; private TransportClient(Injector injector) { - super(injector.getInstance(Settings.class), injector.getInstance(ThreadPool.class), injector.getInstance(Headers.class)); + super(injector.getInstance(Settings.class), injector.getInstance(ThreadPool.class)); this.injector = injector; nodesService = injector.getInstance(TransportClientNodesService.class); proxy = injector.getInstance(TransportProxyClient.class); 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 56befbb9b84..fcbd122ef78 100644 --- a/core/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java +++ b/core/src/main/java/org/elasticsearch/client/transport/TransportClientNodesService.java @@ -29,7 +29,6 @@ import org.elasticsearch.action.admin.cluster.node.liveness.TransportLivenessAct import org.elasticsearch.action.admin.cluster.state.ClusterStateAction; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.client.Requests; -import org.elasticsearch.client.support.Headers; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.component.AbstractComponent; @@ -79,8 +78,6 @@ public class TransportClientNodesService extends AbstractComponent { private final Version minCompatibilityVersion; - private final Headers headers; - // nodes that are added to be discovered private volatile List listedNodes = Collections.emptyList(); @@ -103,13 +100,12 @@ public class TransportClientNodesService extends AbstractComponent { @Inject public TransportClientNodesService(Settings settings, ClusterName clusterName, TransportService transportService, - ThreadPool threadPool, Headers headers, Version version) { + ThreadPool threadPool, Version version) { super(settings); this.clusterName = clusterName; this.transportService = transportService; this.threadPool = threadPool; this.minCompatibilityVersion = version.minimumCompatibilityVersion(); - this.headers = headers; this.nodesSamplerInterval = this.settings.getAsTime("client.transport.nodes_sampler_interval", timeValueSeconds(5)); this.pingTimeout = this.settings.getAsTime("client.transport.ping_timeout", timeValueSeconds(5)).millis(); @@ -358,7 +354,7 @@ public class TransportClientNodesService extends AbstractComponent { } try { LivenessResponse livenessResponse = transportService.submitRequest(listedNode, TransportLivenessAction.NAME, - headers.applyTo(new LivenessRequest()), + new LivenessRequest(), TransportRequestOptions.builder().withType(TransportRequestOptions.Type.STATE).withTimeout(pingTimeout).build(), new FutureTransportResponseHandler() { @Override @@ -428,8 +424,7 @@ public class TransportClientNodesService extends AbstractComponent { return; } } - transportService.sendRequest(listedNode, ClusterStateAction.NAME, - headers.applyTo(Requests.clusterStateRequest().clear().nodes(true).local(true)), + transportService.sendRequest(listedNode, ClusterStateAction.NAME, Requests.clusterStateRequest().clear().nodes(true).local(true), TransportRequestOptions.builder().withType(TransportRequestOptions.Type.STATE).withTimeout(pingTimeout).build(), new BaseTransportResponseHandler() { diff --git a/core/src/main/java/org/elasticsearch/cluster/ClusterStateObserver.java b/core/src/main/java/org/elasticsearch/cluster/ClusterStateObserver.java index df857623570..dd30a711688 100644 --- a/core/src/main/java/org/elasticsearch/cluster/ClusterStateObserver.java +++ b/core/src/main/java/org/elasticsearch/cluster/ClusterStateObserver.java @@ -23,6 +23,7 @@ import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.common.util.concurrent.ThreadContext; import java.util.concurrent.atomic.AtomicReference; @@ -44,6 +45,7 @@ public class ClusterStateObserver { }; private final ClusterService clusterService; + private final ThreadContext contextHolder; volatile TimeValue timeOutValue; @@ -55,8 +57,8 @@ public class ClusterStateObserver { volatile boolean timedOut; - public ClusterStateObserver(ClusterService clusterService, ESLogger logger) { - this(clusterService, new TimeValue(60000), logger); + public ClusterStateObserver(ClusterService clusterService, ESLogger logger, ThreadContext contextHolder) { + this(clusterService, new TimeValue(60000), logger, contextHolder); } /** @@ -64,7 +66,7 @@ public class ClusterStateObserver { * will fail any existing or new #waitForNextChange calls. Set to null * to wait indefinitely */ - public ClusterStateObserver(ClusterService clusterService, @Nullable TimeValue timeout, ESLogger logger) { + public ClusterStateObserver(ClusterService clusterService, @Nullable TimeValue timeout, ESLogger logger, ThreadContext contextHolder) { this.clusterService = clusterService; this.lastObservedState = new AtomicReference<>(new ObservedState(clusterService.state())); this.timeOutValue = timeout; @@ -72,6 +74,7 @@ public class ClusterStateObserver { this.startTimeNS = System.nanoTime(); } this.logger = logger; + this.contextHolder = contextHolder; } /** last cluster state observer by this observer. Note that this may not be the current one */ @@ -146,7 +149,7 @@ public class ClusterStateObserver { listener.onNewClusterState(newState.clusterState); } else { logger.trace("observer: sampled state rejected by predicate ({}). adding listener to ClusterService", newState); - ObservingContext context = new ObservingContext(listener, changePredicate); + ObservingContext context = new ObservingContext(new ContextPreservingListener(listener, contextHolder.newStoredContext()), changePredicate); if (!observingContext.compareAndSet(null, context)) { throw new ElasticsearchException("already waiting for a cluster state change"); } @@ -317,4 +320,33 @@ public class ClusterStateObserver { return "version [" + clusterState.version() + "], status [" + status + "]"; } } + + private final static class ContextPreservingListener implements Listener { + private final Listener delegate; + private final ThreadContext.StoredContext tempContext; + + + private ContextPreservingListener(Listener delegate, ThreadContext.StoredContext storedContext) { + this.tempContext = storedContext; + this.delegate = delegate; + } + + @Override + public void onNewClusterState(ClusterState state) { + tempContext.restore(); + delegate.onNewClusterState(state); + } + + @Override + public void onClusterServiceClose() { + tempContext.restore(); + delegate.onClusterServiceClose(); + } + + @Override + public void onTimeout(TimeValue timeout) { + tempContext.restore(); + delegate.onTimeout(timeout); + } + } } diff --git a/core/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java b/core/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java index ca135728b87..c814fb73ed9 100644 --- a/core/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java +++ b/core/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java @@ -190,7 +190,7 @@ public class InternalClusterService extends AbstractLifecycleComponent nodeAttributes = discoveryNodeService.buildAttributes(); // note, we rely on the fact that its a new id each time we start, see FD and "kill -9" handling diff --git a/core/src/main/java/org/elasticsearch/common/ContextAndHeaderHolder.java b/core/src/main/java/org/elasticsearch/common/ContextAndHeaderHolder.java deleted file mode 100644 index 9a3140dba1a..00000000000 --- a/core/src/main/java/org/elasticsearch/common/ContextAndHeaderHolder.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.common; - -import com.carrotsearch.hppc.ObjectObjectAssociativeContainer; -import com.carrotsearch.hppc.ObjectObjectHashMap; -import org.elasticsearch.common.collect.ImmutableOpenMap; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -/** - * - */ -public class ContextAndHeaderHolder implements HasContextAndHeaders { - - private ObjectObjectHashMap context; - protected Map headers; - - @SuppressWarnings("unchecked") - @Override - public final synchronized V putInContext(Object key, Object value) { - if (context == null) { - context = new ObjectObjectHashMap<>(2); - } - return (V) context.put(key, value); - } - - @Override - public final synchronized void putAllInContext(ObjectObjectAssociativeContainer map) { - if (map == null) { - return; - } - if (context == null) { - context = new ObjectObjectHashMap<>(map); - } else { - context.putAll(map); - } - } - - @SuppressWarnings("unchecked") - @Override - public final synchronized V getFromContext(Object key) { - return context != null ? (V) context.get(key) : null; - } - - @SuppressWarnings("unchecked") - @Override - public final synchronized V getFromContext(Object key, V defaultValue) { - V value = getFromContext(key); - return value == null ? defaultValue : value; - } - - @Override - public final synchronized boolean hasInContext(Object key) { - return context != null && context.containsKey(key); - } - - @Override - public final synchronized int contextSize() { - return context != null ? context.size() : 0; - } - - @Override - public final synchronized boolean isContextEmpty() { - return context == null || context.isEmpty(); - } - - @Override - public synchronized ImmutableOpenMap getContext() { - return context != null ? ImmutableOpenMap.copyOf(context) : ImmutableOpenMap.of(); - } - - @Override - public synchronized void copyContextFrom(HasContext other) { - if (other == null) { - return; - } - - synchronized (other) { - ImmutableOpenMap otherContext = other.getContext(); - if (otherContext == null) { - return; - } - if (context == null) { - ObjectObjectHashMap map = new ObjectObjectHashMap<>(other.getContext().size()); - map.putAll(otherContext); - this.context = map; - } else { - context.putAll(otherContext); - } - } - } - - @SuppressWarnings("unchecked") - @Override - public final void putHeader(String key, Object value) { - if (headers == null) { - headers = new HashMap<>(); - } - headers.put(key, value); - } - - @SuppressWarnings("unchecked") - @Override - public final V getHeader(String key) { - return headers != null ? (V) headers.get(key) : null; - } - - @Override - public final boolean hasHeader(String key) { - return headers != null && headers.containsKey(key); - } - - @Override - public Set getHeaders() { - return headers != null ? headers.keySet() : Collections.emptySet(); - } - - @Override - public void copyHeadersFrom(HasHeaders from) { - if (from != null && from.getHeaders() != null && !from.getHeaders().isEmpty()) { - for (String headerName : from.getHeaders()) { - putHeader(headerName, from.getHeader(headerName)); - } - } - } - - @Override - public void copyContextAndHeadersFrom(HasContextAndHeaders other) { - copyContextFrom(other); - copyHeadersFrom(other); - } -} diff --git a/core/src/main/java/org/elasticsearch/common/DelegatingHasContextAndHeaders.java b/core/src/main/java/org/elasticsearch/common/DelegatingHasContextAndHeaders.java deleted file mode 100644 index 52d5af5e334..00000000000 --- a/core/src/main/java/org/elasticsearch/common/DelegatingHasContextAndHeaders.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.common; - -import com.carrotsearch.hppc.ObjectObjectAssociativeContainer; -import org.elasticsearch.common.collect.ImmutableOpenMap; - -import java.util.Set; - -public class DelegatingHasContextAndHeaders implements HasContextAndHeaders { - - private HasContextAndHeaders delegate; - - public DelegatingHasContextAndHeaders(HasContextAndHeaders delegate) { - this.delegate = delegate; - } - - @Override - public void putHeader(String key, V value) { - delegate.putHeader(key, value); - } - - @Override - public void copyContextAndHeadersFrom(HasContextAndHeaders other) { - delegate.copyContextAndHeadersFrom(other); - } - - @Override - public V getHeader(String key) { - return delegate.getHeader(key); - } - - @Override - public boolean hasHeader(String key) { - return delegate.hasHeader(key); - } - - @Override - public V putInContext(Object key, Object value) { - return delegate.putInContext(key, value); - } - - @Override - public Set getHeaders() { - return delegate.getHeaders(); - } - - @Override - public void copyHeadersFrom(HasHeaders from) { - delegate.copyHeadersFrom(from); - } - - @Override - public void putAllInContext(ObjectObjectAssociativeContainer map) { - delegate.putAllInContext(map); - } - - @Override - public V getFromContext(Object key) { - return delegate.getFromContext(key); - } - - @Override - public V getFromContext(Object key, V defaultValue) { - return delegate.getFromContext(key, defaultValue); - } - - @Override - public boolean hasInContext(Object key) { - return delegate.hasInContext(key); - } - - @Override - public int contextSize() { - return delegate.contextSize(); - } - - @Override - public boolean isContextEmpty() { - return delegate.isContextEmpty(); - } - - @Override - public ImmutableOpenMap getContext() { - return delegate.getContext(); - } - - @Override - public void copyContextFrom(HasContext other) { - delegate.copyContextFrom(other); - } - - -} diff --git a/core/src/main/java/org/elasticsearch/common/HasContext.java b/core/src/main/java/org/elasticsearch/common/HasContext.java deleted file mode 100644 index 6a303e39bae..00000000000 --- a/core/src/main/java/org/elasticsearch/common/HasContext.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.common; - -import com.carrotsearch.hppc.ObjectObjectAssociativeContainer; -import org.elasticsearch.common.collect.ImmutableOpenMap; - -public interface HasContext { - - /** - * Attaches the given value to the context. - * - * @return The previous value that was associated with the given key in the context, or - * {@code null} if there was none. - */ - V putInContext(Object key, Object value); - - /** - * Attaches the given values to the context - */ - void putAllInContext(ObjectObjectAssociativeContainer map); - - /** - * @return The context value that is associated with the given key - * - * @see #putInContext(Object, Object) - */ - V getFromContext(Object key); - - /** - * @param defaultValue The default value that should be returned for the given key, if no - * value is currently associated with it. - * - * @return The value that is associated with the given key in the context - * - * @see #putInContext(Object, Object) - */ - V getFromContext(Object key, V defaultValue); - - /** - * Checks if the context contains an entry with the given key - */ - boolean hasInContext(Object key); - - /** - * @return The number of values attached in the context. - */ - int contextSize(); - - /** - * Checks if the context is empty. - */ - boolean isContextEmpty(); - - /** - * @return A safe immutable copy of the current context. - */ - ImmutableOpenMap getContext(); - - /** - * Copies the context from the given context holder to this context holder. Any shared keys between - * the two context will be overridden by the given context holder. - */ - void copyContextFrom(HasContext other); -} diff --git a/core/src/main/java/org/elasticsearch/common/HasContextAndHeaders.java b/core/src/main/java/org/elasticsearch/common/HasContextAndHeaders.java deleted file mode 100644 index 35bea9a7778..00000000000 --- a/core/src/main/java/org/elasticsearch/common/HasContextAndHeaders.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.common; - -/** - * marker interface - */ -public interface HasContextAndHeaders extends HasContext, HasHeaders { - - /** - * copies over the context and the headers - * @param other another object supporting headers and context - */ - void copyContextAndHeadersFrom(HasContextAndHeaders other); - -} diff --git a/core/src/main/java/org/elasticsearch/common/HasHeaders.java b/core/src/main/java/org/elasticsearch/common/HasHeaders.java deleted file mode 100644 index ab3a7da643e..00000000000 --- a/core/src/main/java/org/elasticsearch/common/HasHeaders.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.common; - -import java.util.Set; - -/** - * - */ -public interface HasHeaders { - - void putHeader(String key, V value); - - V getHeader(String key); - - boolean hasHeader(String key); - - Set getHeaders(); - - void copyHeadersFrom(HasHeaders from); -} diff --git a/core/src/main/java/org/elasticsearch/common/network/NetworkModule.java b/core/src/main/java/org/elasticsearch/common/network/NetworkModule.java index b3abed6e230..089e67d8f64 100644 --- a/core/src/main/java/org/elasticsearch/common/network/NetworkModule.java +++ b/core/src/main/java/org/elasticsearch/common/network/NetworkModule.java @@ -19,7 +19,6 @@ package org.elasticsearch.common.network; -import org.elasticsearch.client.support.Headers; import org.elasticsearch.client.transport.TransportClientNodesService; import org.elasticsearch.client.transport.support.TransportProxyClient; import org.elasticsearch.cluster.node.DiscoveryNode; @@ -361,7 +360,6 @@ public class NetworkModule extends AbstractModule { transportTypes.bindType(binder(), settings, TRANSPORT_TYPE_KEY, defaultTransport); if (transportClient) { - bind(Headers.class).asEagerSingleton(); bind(TransportProxyClient.class).asEagerSingleton(); bind(TransportClientNodesService.class).asEagerSingleton(); } else { diff --git a/core/src/main/java/org/elasticsearch/common/util/concurrent/EsExecutors.java b/core/src/main/java/org/elasticsearch/common/util/concurrent/EsExecutors.java index 140f026c357..6111028580a 100644 --- a/core/src/main/java/org/elasticsearch/common/util/concurrent/EsExecutors.java +++ b/core/src/main/java/org/elasticsearch/common/util/concurrent/EsExecutors.java @@ -60,30 +60,30 @@ public class EsExecutors { return settings.getAsInt(PROCESSORS, defaultValue); } - public static PrioritizedEsThreadPoolExecutor newSinglePrioritizing(String name, ThreadFactory threadFactory) { - return new PrioritizedEsThreadPoolExecutor(name, 1, 1, 0L, TimeUnit.MILLISECONDS, threadFactory); + public static PrioritizedEsThreadPoolExecutor newSinglePrioritizing(String name, ThreadFactory threadFactory, ThreadContext contextHolder) { + return new PrioritizedEsThreadPoolExecutor(name, 1, 1, 0L, TimeUnit.MILLISECONDS, threadFactory, contextHolder); } - public static EsThreadPoolExecutor newScaling(String name, int min, int max, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory) { + public static EsThreadPoolExecutor newScaling(String name, int min, int max, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory, ThreadContext contextHolder) { ExecutorScalingQueue queue = new ExecutorScalingQueue<>(); // we force the execution, since we might run into concurrency issues in offer for ScalingBlockingQueue - EsThreadPoolExecutor executor = new EsThreadPoolExecutor(name, min, max, keepAliveTime, unit, queue, threadFactory, new ForceQueuePolicy()); + EsThreadPoolExecutor executor = new EsThreadPoolExecutor(name, min, max, keepAliveTime, unit, queue, threadFactory, new ForceQueuePolicy(), contextHolder); queue.executor = executor; return executor; } - public static EsThreadPoolExecutor newCached(String name, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory) { - return new EsThreadPoolExecutor(name, 0, Integer.MAX_VALUE, keepAliveTime, unit, new SynchronousQueue(), threadFactory, new EsAbortPolicy()); + public static EsThreadPoolExecutor newCached(String name, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory, ThreadContext contextHolder) { + return new EsThreadPoolExecutor(name, 0, Integer.MAX_VALUE, keepAliveTime, unit, new SynchronousQueue(), threadFactory, new EsAbortPolicy(), contextHolder); } - public static EsThreadPoolExecutor newFixed(String name, int size, int queueCapacity, ThreadFactory threadFactory) { + public static EsThreadPoolExecutor newFixed(String name, int size, int queueCapacity, ThreadFactory threadFactory, ThreadContext contextHolder) { BlockingQueue queue; if (queueCapacity < 0) { queue = ConcurrentCollections.newBlockingQueue(); } else { queue = new SizeBlockingQueue<>(ConcurrentCollections.newBlockingQueue(), queueCapacity); } - return new EsThreadPoolExecutor(name, size, size, 0, TimeUnit.MILLISECONDS, queue, threadFactory, new EsAbortPolicy()); + return new EsThreadPoolExecutor(name, size, size, 0, TimeUnit.MILLISECONDS, queue, threadFactory, new EsAbortPolicy(), contextHolder); } public static String threadName(Settings settings, String ... names) { diff --git a/core/src/main/java/org/elasticsearch/common/util/concurrent/EsThreadPoolExecutor.java b/core/src/main/java/org/elasticsearch/common/util/concurrent/EsThreadPoolExecutor.java index 4c02aab1fe8..b5417aa2380 100644 --- a/core/src/main/java/org/elasticsearch/common/util/concurrent/EsThreadPoolExecutor.java +++ b/core/src/main/java/org/elasticsearch/common/util/concurrent/EsThreadPoolExecutor.java @@ -30,6 +30,7 @@ import java.util.concurrent.TimeUnit; */ public class EsThreadPoolExecutor extends ThreadPoolExecutor { + private final ThreadContext contextHolder; private volatile ShutdownListener listener; private final Object monitor = new Object(); @@ -38,13 +39,14 @@ public class EsThreadPoolExecutor extends ThreadPoolExecutor { */ private final String name; - EsThreadPoolExecutor(String name, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory) { - this(name, corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, new EsAbortPolicy()); + EsThreadPoolExecutor(String name, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, ThreadContext contextHolder) { + this(name, corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, new EsAbortPolicy(), contextHolder); } - EsThreadPoolExecutor(String name, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, XRejectedExecutionHandler handler) { + EsThreadPoolExecutor(String name, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, XRejectedExecutionHandler handler, ThreadContext contextHolder) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); this.name = name; + this.contextHolder = contextHolder; } public void shutdown(ShutdownListener listener) { @@ -80,7 +82,11 @@ public class EsThreadPoolExecutor extends ThreadPoolExecutor { } @Override - public void execute(Runnable command) { + public void execute(final Runnable command) { + doExecute(wrapRunnable(command)); + } + + protected void doExecute(final Runnable command) { try { super.execute(command); } catch (EsRejectedExecutionException ex) { @@ -116,4 +122,94 @@ public class EsThreadPoolExecutor extends ThreadPoolExecutor { b.append(super.toString()).append(']'); return b.toString(); } + + protected Runnable wrapRunnable(Runnable command) { + final Runnable wrappedCommand; + if (command instanceof AbstractRunnable) { + wrappedCommand = new FilterAbstractRunnable(contextHolder, (AbstractRunnable) command); + } else { + wrappedCommand = new FilterRunnable(contextHolder, command); + } + return wrappedCommand; + } + + protected Runnable unwrap(Runnable runnable) { + if (runnable instanceof FilterAbstractRunnable) { + return ((FilterAbstractRunnable) runnable).in; + } else if (runnable instanceof FilterRunnable) { + return ((FilterRunnable) runnable).in; + } + return runnable; + } + + private static class FilterAbstractRunnable extends AbstractRunnable { + private final ThreadContext contextHolder; + private final AbstractRunnable in; + private final ThreadContext.StoredContext ctx; + + FilterAbstractRunnable(ThreadContext contextHolder, AbstractRunnable in) { + this.contextHolder = contextHolder; + ctx = contextHolder.newStoredContext(); + this.in = in; + } + + @Override + public boolean isForceExecution() { + return in.isForceExecution(); + } + + @Override + public void onAfter() { + in.onAfter(); + } + + @Override + public void onFailure(Throwable t) { + in.onFailure(t); + } + + @Override + public void onRejection(Throwable t) { + in.onRejection(t); + } + + @Override + protected void doRun() throws Exception { + try (ThreadContext.StoredContext ingore = contextHolder.stashContext()){ + ctx.restore(); + in.doRun(); + } + } + + @Override + public String toString() { + return in.toString(); + } + + } + + private static class FilterRunnable implements Runnable { + private final ThreadContext contextHolder; + private final Runnable in; + private final ThreadContext.StoredContext ctx; + + FilterRunnable(ThreadContext contextHolder, Runnable in) { + this.contextHolder = contextHolder; + ctx = contextHolder.newStoredContext(); + this.in = in; + } + + @Override + public void run() { + try (ThreadContext.StoredContext ingore = contextHolder.stashContext()){ + ctx.restore(); + in.run(); + } + } + @Override + public String toString() { + return in.toString(); + } + } + } diff --git a/core/src/main/java/org/elasticsearch/common/util/concurrent/PrioritizedEsThreadPoolExecutor.java b/core/src/main/java/org/elasticsearch/common/util/concurrent/PrioritizedEsThreadPoolExecutor.java index d0d2906deed..f55c84e943a 100644 --- a/core/src/main/java/org/elasticsearch/common/util/concurrent/PrioritizedEsThreadPoolExecutor.java +++ b/core/src/main/java/org/elasticsearch/common/util/concurrent/PrioritizedEsThreadPoolExecutor.java @@ -47,8 +47,8 @@ public class PrioritizedEsThreadPoolExecutor extends EsThreadPoolExecutor { private AtomicLong insertionOrder = new AtomicLong(); private Queue current = ConcurrentCollections.newQueue(); - PrioritizedEsThreadPoolExecutor(String name, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory) { - super(name, corePoolSize, maximumPoolSize, keepAliveTime, unit, new PriorityBlockingQueue(), threadFactory); + PrioritizedEsThreadPoolExecutor(String name, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory, ThreadContext contextHolder) { + super(name, corePoolSize, maximumPoolSize, keepAliveTime, unit, new PriorityBlockingQueue<>(), threadFactory, contextHolder); } public Pending[] getPending() { @@ -88,10 +88,14 @@ public class PrioritizedEsThreadPoolExecutor extends EsThreadPoolExecutor { for (Runnable runnable : runnables) { if (runnable instanceof TieBreakingPrioritizedRunnable) { TieBreakingPrioritizedRunnable t = (TieBreakingPrioritizedRunnable) runnable; - pending.add(new Pending(t.runnable, t.priority(), t.insertionOrder, executing)); + pending.add(new Pending(unwrap(t.runnable), t.priority(), t.insertionOrder, executing)); } else if (runnable instanceof PrioritizedFutureTask) { PrioritizedFutureTask t = (PrioritizedFutureTask) runnable; - pending.add(new Pending(t.task, t.priority, t.insertionOrder, executing)); + Object task = t.task; + if (t.task instanceof Runnable) { + task = unwrap((Runnable) t.task); + } + pending.add(new Pending(task, t.priority, t.insertionOrder, executing)); } } } @@ -107,12 +111,8 @@ public class PrioritizedEsThreadPoolExecutor extends EsThreadPoolExecutor { } public void execute(Runnable command, final ScheduledExecutorService timer, final TimeValue timeout, final Runnable timeoutCallback) { - if (command instanceof PrioritizedRunnable) { - command = new TieBreakingPrioritizedRunnable((PrioritizedRunnable) command, insertionOrder.incrementAndGet()); - } else if (!(command instanceof PrioritizedFutureTask)) { // it might be a callable wrapper... - command = new TieBreakingPrioritizedRunnable(command, Priority.NORMAL, insertionOrder.incrementAndGet()); - } - super.execute(command); + command = wrapRunnable(command); + doExecute(command); if (timeout.nanos() >= 0) { if (command instanceof TieBreakingPrioritizedRunnable) { ((TieBreakingPrioritizedRunnable) command).scheduleTimeout(timer, timeoutCallback, timeout); @@ -125,21 +125,31 @@ public class PrioritizedEsThreadPoolExecutor extends EsThreadPoolExecutor { } @Override - public void execute(Runnable command) { + protected Runnable wrapRunnable(Runnable command) { if (command instanceof PrioritizedRunnable) { - command = new TieBreakingPrioritizedRunnable((PrioritizedRunnable) command, insertionOrder.incrementAndGet()); - } else if (!(command instanceof PrioritizedFutureTask)) { // it might be a callable wrapper... - command = new TieBreakingPrioritizedRunnable(command, Priority.NORMAL, insertionOrder.incrementAndGet()); + if ((command instanceof TieBreakingPrioritizedRunnable)) { + return command; + } + Priority priority = ((PrioritizedRunnable) command).priority(); + return new TieBreakingPrioritizedRunnable(super.wrapRunnable(command), priority, insertionOrder.incrementAndGet()); + } else if (command instanceof PrioritizedFutureTask) { + return command; + } else { // it might be a callable wrapper... + if (command instanceof TieBreakingPrioritizedRunnable) { + return command; + } + return new TieBreakingPrioritizedRunnable(super.wrapRunnable(command), Priority.NORMAL, insertionOrder.incrementAndGet()); } - super.execute(command); } + @Override protected RunnableFuture newTaskFor(Runnable runnable, T value) { if (!(runnable instanceof PrioritizedRunnable)) { runnable = PrioritizedRunnable.wrap(runnable, Priority.NORMAL); } - return new PrioritizedFutureTask<>((PrioritizedRunnable) runnable, value, insertionOrder.incrementAndGet()); + Priority priority = ((PrioritizedRunnable) runnable).priority(); + return new PrioritizedFutureTask<>(runnable, priority, value, insertionOrder.incrementAndGet()); } @Override @@ -147,7 +157,7 @@ public class PrioritizedEsThreadPoolExecutor extends EsThreadPoolExecutor { if (!(callable instanceof PrioritizedCallable)) { callable = PrioritizedCallable.wrap(callable, Priority.NORMAL); } - return new PrioritizedFutureTask<>((PrioritizedCallable) callable, insertionOrder.incrementAndGet()); + return new PrioritizedFutureTask<>((PrioritizedCallable)callable, insertionOrder.incrementAndGet()); } public static class Pending { @@ -173,10 +183,6 @@ public class PrioritizedEsThreadPoolExecutor extends EsThreadPoolExecutor { private ScheduledFuture timeoutFuture; private boolean started = false; - TieBreakingPrioritizedRunnable(PrioritizedRunnable runnable, long insertionOrder) { - this(runnable, runnable.priority(), insertionOrder); - } - TieBreakingPrioritizedRunnable(Runnable runnable, Priority priority, long insertionOrder) { super(priority); this.runnable = runnable; @@ -233,6 +239,7 @@ public class PrioritizedEsThreadPoolExecutor extends EsThreadPoolExecutor { runnable = null; timeoutFuture = null; } + } } @@ -242,10 +249,10 @@ public class PrioritizedEsThreadPoolExecutor extends EsThreadPoolExecutor { final Priority priority; final long insertionOrder; - public PrioritizedFutureTask(PrioritizedRunnable runnable, T value, long insertionOrder) { + public PrioritizedFutureTask(Runnable runnable, Priority priority, T value, long insertionOrder) { super(runnable, value); this.task = runnable; - this.priority = runnable.priority(); + this.priority = priority; this.insertionOrder = insertionOrder; } @@ -265,4 +272,5 @@ public class PrioritizedEsThreadPoolExecutor extends EsThreadPoolExecutor { return insertionOrder < pft.insertionOrder ? -1 : 1; } } + } 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 new file mode 100644 index 00000000000..5b52771f035 --- /dev/null +++ b/core/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java @@ -0,0 +1,288 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.elasticsearch.common.util.concurrent; + +import org.apache.lucene.util.CloseableThreadLocal; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.common.io.stream.Writeable; +import org.elasticsearch.common.settings.Settings; + +import java.io.Closeable; +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * A ThreadContext a map of string headers and a transient map of keyed objects that are associated with + * a thread. It allows to store and retrieve header information across method calls, network calls as well as threads spawned from a + * thread that has a {@link ThreadContext} associated with. Threads spawned from a {@link org.elasticsearch.threadpool.ThreadPool} have out of the box + * support for {@link ThreadContext} and all threads spawned will inherit the {@link ThreadContext} from the thread that is forking off. + * Network calls will also preserve the senders heaaders automatically. + */ +public final class ThreadContext implements Closeable, Writeable{ + + public static final String PREFIX = "request.headers"; + private final ThreadContextStruct defaultContext; + private final ContextThreadLocal threadLocal; + + /** + * Creates a new ThreadContext instance + * @param settings the settings to read the default request headers from + */ + public ThreadContext(Settings settings) { + Settings headers = settings.getAsSettings(PREFIX); + if (headers == null) { + this.defaultContext = new ThreadContextStruct(Collections.emptyMap()); + } else { + Map defaultHeader = new HashMap<>(); + for (String key : headers.names()) { + defaultHeader.put(key, headers.get(key)); + } + this.defaultContext = new ThreadContextStruct(defaultHeader); + } + threadLocal = new ContextThreadLocal(defaultContext); + } + + @Override + public void close() throws IOException { + threadLocal.close(); + } + + /** + * Removes the current context and resets a default context. The removed context can be + * restored when closing the returned {@link StoredContext} + */ + public StoredContext stashContext() { + final ThreadContextStruct context = threadLocal.get(); + threadLocal.set(null); + return () -> { + threadLocal.set(context); + }; + } + + /** + * Just like {@link #stashContext()} but no default context is set. + */ + public StoredContext newStoredContext() { + final ThreadContextStruct context = threadLocal.get(); + return () -> { + threadLocal.set(context); + }; + } + + @Override + public void writeTo(StreamOutput out) throws IOException { + threadLocal.get().writeTo(out); + } + + @Override + public ThreadContextStruct readFrom(StreamInput in) throws IOException { + return defaultContext.readFrom(in); + } + + /** + * Reads the headers from the stream into the current context + */ + public void readHeaders(StreamInput in) throws IOException { + threadLocal.set(readFrom(in)); + } + + + /** + * Returns the header for the given key or null if not present + */ + public String getHeader(String key) { + return threadLocal.get().headers.get(key); + } + + /** + * Returns all of the current contexts headers + */ + public Map getHeaders() { + return threadLocal.get().headers; + } + + /** + * Copies all header key, value pairs into the current context + */ + public void copyHeaders(Iterable> headers) { + threadLocal.set(threadLocal.get().copyHeaders(headers)); + } + + /** + * Puts a header into the context + */ + public void putHeader(String key, String value) { + putHeader(Collections.singletonMap(key, value)); + } + + /** + * Puts all of the given headers into this context + */ + public void putHeader(Map header) { + threadLocal.set(threadLocal.get().putHeaders(header)); + } + + /** + * Puts a transient header object into this context + */ + public void putTransient(String key, Object value) { + threadLocal.set(threadLocal.get().putTransient(key, value)); + } + + /** + * Returns a transient header object or null if there is no header for the given key + */ + public T getTransient(String key) { + return (T) threadLocal.get().transientHeaders.get(key); + } + + public interface StoredContext extends AutoCloseable { + @Override + void close(); + + default void restore() { + close(); + } + } + + static final class ThreadContextStruct implements Writeable { + private final Map headers; + private final Map transientHeaders; + + private ThreadContextStruct(StreamInput in) throws IOException { + int numValues = in.readVInt(); + Map headers = numValues == 0 ? Collections.emptyMap() : new HashMap<>(numValues); + for (int i = 0; i < numValues; i++) { + headers.put(in.readString(), in.readString()); + } + this.headers = headers; + this.transientHeaders = Collections.emptyMap(); + } + + private ThreadContextStruct(Map headers, Map transientHeaders) { + this.headers = headers; + this.transientHeaders = transientHeaders; + } + + private ThreadContextStruct(Map headers) { + this(headers, Collections.emptyMap()); + } + + private ThreadContextStruct putHeaders(Map headers) { + if (headers.isEmpty()) { + return this; + } else { + Map newHeaders = new HashMap<>(this.headers); + newHeaders.putAll(headers); + return new ThreadContextStruct(newHeaders, transientHeaders); + } + } + + private ThreadContextStruct putTransient(String key, Object value) { + Map newTransient = new HashMap<>(this.transientHeaders); + if (newTransient.putIfAbsent(key, value) != null) { + throw new IllegalArgumentException("value for key [" + key + "] already present"); + } + return new ThreadContextStruct(headers, newTransient); + } + + boolean isEmpty() { + return headers.isEmpty() && transientHeaders.isEmpty(); + } + + + private ThreadContextStruct copyHeaders(Iterable> headers) { + Map newHeaders = new HashMap<>(); + for (Map.Entry header : headers) { + newHeaders.put(header.getKey(), header.getValue()); + } + return putHeaders(newHeaders); + } + + @Override + public ThreadContextStruct readFrom(StreamInput in) throws IOException { + return new ThreadContextStruct(in); + } + + @Override + public void writeTo(StreamOutput out) throws IOException { + int keys = headers.size(); + out.writeVInt(keys); + for (Map.Entry entry : headers.entrySet()) { + out.writeString(entry.getKey()); + out.writeString(entry.getValue()); + } + } + + } + + private static class ContextThreadLocal extends CloseableThreadLocal { + private final ThreadContextStruct defaultStruct; + private final AtomicBoolean closed = new AtomicBoolean(false); + + private ContextThreadLocal(ThreadContextStruct defaultStruct) { + this.defaultStruct = defaultStruct; + } + + @Override + public void set(ThreadContextStruct object) { + try { + if (object == defaultStruct) { + super.set(null); + } else { + super.set(object); + } + } catch (NullPointerException ex) { + ensureOpen(); + throw ex; + } + } + + @Override + public ThreadContextStruct get() { + try { + ThreadContextStruct threadContextStruct = super.get(); + if (threadContextStruct != null) { + return threadContextStruct; + } + return defaultStruct; + } catch (NullPointerException ex) { + ensureOpen(); + throw ex; + } + } + + private void ensureOpen() { + if (closed.get()) { + throw new IllegalStateException("threadcontext is already closed"); + } + } + + @Override + public void close() { + if (closed.compareAndSet(false, true)) { + super.close(); + } + } + } +} 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 99feb4b7f72..347229d8e41 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 @@ -170,7 +170,7 @@ public class UnicastZenPing extends AbstractLifecycleComponent implemen transportService.registerRequestHandler(ACTION_NAME, UnicastPingRequest::new, ThreadPool.Names.SAME, new UnicastPingRequestHandler()); ThreadFactory threadFactory = EsExecutors.daemonThreadFactory(settings, "[unicast_connect]"); - unicastConnectExecutor = EsExecutors.newScaling("unicast_connect", 0, concurrentConnects, 60, TimeUnit.SECONDS, threadFactory); + unicastConnectExecutor = EsExecutors.newScaling("unicast_connect", 0, concurrentConnects, 60, TimeUnit.SECONDS, threadFactory, threadPool.getThreadContext()); } @Override diff --git a/core/src/main/java/org/elasticsearch/gateway/TransportNodesListGatewayMetaState.java b/core/src/main/java/org/elasticsearch/gateway/TransportNodesListGatewayMetaState.java index a117eb709af..fb174f4bd45 100644 --- a/core/src/main/java/org/elasticsearch/gateway/TransportNodesListGatewayMetaState.java +++ b/core/src/main/java/org/elasticsearch/gateway/TransportNodesListGatewayMetaState.java @@ -183,7 +183,7 @@ public class TransportNodesListGatewayMetaState extends TransportNodesAction { +public class HttpServer extends AbstractLifecycleComponent implements HttpServerAdapter { private final Environment environment; @@ -79,23 +80,9 @@ public class HttpServer extends AbstractLifecycleComponent { nodeService.setHttpServer(this); this.disableSites = this.settings.getAsBoolean("http.disable_sites", false); - - transport.httpServerAdapter(new Dispatcher(this)); + transport.httpServerAdapter(this); } - static class Dispatcher implements HttpServerAdapter { - - private final HttpServer server; - - Dispatcher(HttpServer server) { - this.server = server; - } - - @Override - public void dispatchRequest(HttpRequest request, HttpChannel channel) { - server.internalDispatchRequest(request, channel); - } - } @Override protected void doStart() { @@ -125,7 +112,7 @@ public class HttpServer extends AbstractLifecycleComponent { return transport.stats(); } - public void internalDispatchRequest(final HttpRequest request, final HttpChannel channel) { + public void dispatchRequest(HttpRequest request, HttpChannel channel, ThreadContext threadContext) { String rawPath = request.rawPath(); if (rawPath.startsWith("/_plugin/")) { RestFilterChain filterChain = restController.filterChain(pluginSiteFilter); @@ -135,7 +122,7 @@ public class HttpServer extends AbstractLifecycleComponent { handleFavicon(request, channel); return; } - restController.dispatchRequest(request, channel); + restController.dispatchRequest(request, channel, threadContext); } diff --git a/core/src/main/java/org/elasticsearch/http/HttpServerAdapter.java b/core/src/main/java/org/elasticsearch/http/HttpServerAdapter.java index a73456f6b52..c49265cae8c 100644 --- a/core/src/main/java/org/elasticsearch/http/HttpServerAdapter.java +++ b/core/src/main/java/org/elasticsearch/http/HttpServerAdapter.java @@ -19,10 +19,12 @@ package org.elasticsearch.http; +import org.elasticsearch.common.util.concurrent.ThreadContext; + /** * */ public interface HttpServerAdapter { - void dispatchRequest(HttpRequest request, HttpChannel channel); + void dispatchRequest(HttpRequest request, HttpChannel channel, ThreadContext context); } diff --git a/core/src/main/java/org/elasticsearch/http/netty/HttpRequestHandler.java b/core/src/main/java/org/elasticsearch/http/netty/HttpRequestHandler.java index 5c05efcd170..71d63d8d1dc 100644 --- a/core/src/main/java/org/elasticsearch/http/netty/HttpRequestHandler.java +++ b/core/src/main/java/org/elasticsearch/http/netty/HttpRequestHandler.java @@ -19,6 +19,7 @@ package org.elasticsearch.http.netty; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.http.netty.pipelining.OrderedUpstreamMessageEvent; import org.elasticsearch.rest.support.RestUtils; import org.jboss.netty.channel.ChannelHandler; @@ -41,12 +42,14 @@ public class HttpRequestHandler extends SimpleChannelUpstreamHandler { private final Pattern corsPattern; private final boolean httpPipeliningEnabled; private final boolean detailedErrorsEnabled; + private final ThreadContext threadContext; - public HttpRequestHandler(NettyHttpServerTransport serverTransport, boolean detailedErrorsEnabled) { + public HttpRequestHandler(NettyHttpServerTransport serverTransport, boolean detailedErrorsEnabled, ThreadContext threadContext) { this.serverTransport = serverTransport; this.corsPattern = RestUtils.checkCorsSettingForRegex(serverTransport.settings().get(NettyHttpServerTransport.SETTING_CORS_ALLOW_ORIGIN)); this.httpPipeliningEnabled = serverTransport.pipelining; this.detailedErrorsEnabled = detailedErrorsEnabled; + this.threadContext = threadContext; } @Override @@ -60,6 +63,7 @@ public class HttpRequestHandler extends SimpleChannelUpstreamHandler { request = (HttpRequest) e.getMessage(); } + threadContext.copyHeaders(request.headers()); // the netty HTTP handling always copy over the buffer to its own buffer, either in NioWorker internally // when reading, or using a cumalation buffer NettyHttpRequest httpRequest = new NettyHttpRequest(request, e.getChannel()); diff --git a/core/src/main/java/org/elasticsearch/http/netty/NettyHttpServerTransport.java b/core/src/main/java/org/elasticsearch/http/netty/NettyHttpServerTransport.java index 899bbdc86e2..cbab8826351 100644 --- a/core/src/main/java/org/elasticsearch/http/netty/NettyHttpServerTransport.java +++ b/core/src/main/java/org/elasticsearch/http/netty/NettyHttpServerTransport.java @@ -38,6 +38,7 @@ import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.common.util.concurrent.EsExecutors; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.http.BindHttpException; import org.elasticsearch.http.HttpChannel; import org.elasticsearch.http.HttpInfo; @@ -47,6 +48,7 @@ import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.http.HttpStats; import org.elasticsearch.http.netty.pipelining.HttpPipeliningHandler; import org.elasticsearch.monitor.jvm.JvmInfo; +import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.BindTransportException; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.AdaptiveReceiveBufferSizePredictorFactory; @@ -139,6 +141,7 @@ public class NettyHttpServerTransport extends AbstractLifecycleComponent { List terms = new ArrayList<>(); GetRequest getRequest = new GetRequest(termsLookup.index(), termsLookup.type(), termsLookup.id()) .preference("_local").routing(termsLookup.routing()); - getRequest.copyContextAndHeadersFrom(SearchContext.current()); final GetResponse getResponse = client.get(getRequest).actionGet(); if (getResponse.isExists()) { List extractedValues = XContentMapValues.extractRawValues(termsLookup.path(), getResponse.getSourceAsMap()); diff --git a/core/src/main/java/org/elasticsearch/indices/IndicesService.java b/core/src/main/java/org/elasticsearch/indices/IndicesService.java index c3c0ffe4732..084f8424d59 100644 --- a/core/src/main/java/org/elasticsearch/indices/IndicesService.java +++ b/core/src/main/java/org/elasticsearch/indices/IndicesService.java @@ -740,5 +740,4 @@ public class IndicesService extends AbstractLifecycleComponent i public AnalysisRegistry getAnalysis() { return analysisRegistry; } - } diff --git a/core/src/main/java/org/elasticsearch/indices/recovery/RecoverySettings.java b/core/src/main/java/org/elasticsearch/indices/recovery/RecoverySettings.java index c86309db136..8d610dce05b 100644 --- a/core/src/main/java/org/elasticsearch/indices/recovery/RecoverySettings.java +++ b/core/src/main/java/org/elasticsearch/indices/recovery/RecoverySettings.java @@ -83,7 +83,6 @@ public class RecoverySettings extends AbstractComponent { this.internalActionLongTimeout = INDICES_RECOVERY_INTERNAL_LONG_ACTION_TIMEOUT_SETTING.get(settings); this.activityTimeout = INDICES_RECOVERY_ACTIVITY_TIMEOUT_SETTING.get(settings); - this.maxBytesPerSec = INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING.get(settings); if (maxBytesPerSec.bytes() <= 0) { rateLimiter = null; 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 f7e683b8f14..b25f16b3e44 100644 --- a/core/src/main/java/org/elasticsearch/indices/recovery/RecoveryTarget.java +++ b/core/src/main/java/org/elasticsearch/indices/recovery/RecoveryTarget.java @@ -308,7 +308,7 @@ public class RecoveryTarget extends AbstractComponent implements IndexEventListe @Override public void messageReceived(final RecoveryTranslogOperationsRequest request, final TransportChannel channel) throws Exception { try (RecoveriesCollection.StatusRef statusRef = onGoingRecoveries.getStatusSafe(request.recoveryId(), request.shardId())) { - final ClusterStateObserver observer = new ClusterStateObserver(clusterService, null, logger); + final ClusterStateObserver observer = new ClusterStateObserver(clusterService, null, logger, threadPool.getThreadContext()); final RecoveryStatus recoveryStatus = statusRef.status(); final RecoveryState.Translog translog = recoveryStatus.state().getTranslog(); translog.totalOperations(request.totalTranslogOps()); 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 4a76d262130..30571f09f22 100644 --- a/core/src/main/java/org/elasticsearch/indices/store/IndicesStore.java +++ b/core/src/main/java/org/elasticsearch/indices/store/IndicesStore.java @@ -74,27 +74,23 @@ public class IndicesStore extends AbstractComponent implements ClusterStateListe private final IndicesService indicesService; private final ClusterService clusterService; private final TransportService transportService; + private final ThreadPool threadPool; private TimeValue deleteShardTimeout; @Inject public IndicesStore(Settings settings, IndicesService indicesService, - ClusterService clusterService, TransportService transportService) { + ClusterService clusterService, TransportService transportService, ThreadPool threadPool) { super(settings); this.indicesService = indicesService; this.clusterService = clusterService; this.transportService = transportService; + this.threadPool = threadPool; transportService.registerRequestHandler(ACTION_SHARD_EXISTS, ShardActiveRequest::new, ThreadPool.Names.SAME, new ShardActiveRequestHandler()); this.deleteShardTimeout = settings.getAsTime(INDICES_STORE_DELETE_SHARD_TIMEOUT, new TimeValue(30, TimeUnit.SECONDS)); clusterService.addLast(this); } - IndicesStore() { - super(Settings.EMPTY); - indicesService = null; - this.clusterService = null; - this.transportService = null; - } @Override public void close() { clusterService.remove(this); @@ -278,6 +274,7 @@ public class IndicesStore extends AbstractComponent implements ClusterStateListe @Override public void messageReceived(final ShardActiveRequest request, final TransportChannel channel) throws Exception { IndexShard indexShard = getShard(request); + // make sure shard is really there before register cluster state observer if (indexShard == null) { channel.sendResponse(new ShardActiveResponse(false, clusterService.localNode())); @@ -288,7 +285,7 @@ public class IndicesStore extends AbstractComponent implements ClusterStateListe // in general, using a cluster state observer here is a workaround for the fact that we cannot listen on shard state changes explicitly. // instead we wait for the cluster state changes because we know any shard state change will trigger or be // triggered by a cluster state change. - ClusterStateObserver observer = new ClusterStateObserver(clusterService, request.timeout, logger); + ClusterStateObserver observer = new ClusterStateObserver(clusterService, request.timeout, logger, threadPool.getThreadContext()); // check if shard is active. if so, all is good boolean shardActive = shardActive(indexShard); if (shardActive) { @@ -348,7 +345,6 @@ public class IndicesStore extends AbstractComponent implements ClusterStateListe logger.trace("shard exists request meant for cluster[{}], but this is cluster[{}], ignoring request", request.clusterName, thisClusterName); return null; } - ShardId shardId = request.shardId; IndexService indexService = indicesService.indexService(shardId.index().getName()); if (indexService != null && indexService.indexUUID().equals(request.indexUUID)) { @@ -356,6 +352,7 @@ public class IndicesStore extends AbstractComponent implements ClusterStateListe } return null; } + } private static class ShardActiveRequest extends TransportRequest { diff --git a/core/src/main/java/org/elasticsearch/indices/store/TransportNodesListShardStoreMetaData.java b/core/src/main/java/org/elasticsearch/indices/store/TransportNodesListShardStoreMetaData.java index 65902b443e9..54068f19de8 100644 --- a/core/src/main/java/org/elasticsearch/indices/store/TransportNodesListShardStoreMetaData.java +++ b/core/src/main/java/org/elasticsearch/indices/store/TransportNodesListShardStoreMetaData.java @@ -344,7 +344,7 @@ public class TransportNodesListShardStoreMetaData extends TransportNodesAction V putInContext(Object key, Object value) { - assert false : "percolatecontext does not support contexts & headers"; - return null; - } - - @Override - public void putAllInContext(ObjectObjectAssociativeContainer map) { - assert false : "percolatocontext does not support contexts & headers"; - } - - @Override - public V getFromContext(Object key) { - return null; - } - - @Override - public V getFromContext(Object key, V defaultValue) { - return defaultValue; - } - - @Override - public boolean hasInContext(Object key) { - return false; - } - - @Override - public int contextSize() { - return 0; - } - - @Override - public boolean isContextEmpty() { - return true; - } - - @Override - public ImmutableOpenMap getContext() { - return ImmutableOpenMap.of(); - } - - @Override - public void copyContextFrom(HasContext other) { - assert false : "percolatecontext does not support contexts & headers"; - } - - @Override - public void putHeader(String key, V value) { - assert false : "percolatecontext does not support contexts & headers"; - } - - @Override - public V getHeader(String key) { - return null; - } - - @Override - public boolean hasHeader(String key) { - return false; - } - - @Override - public Set getHeaders() { - return Collections.emptySet(); - } - - @Override - public void copyHeadersFrom(HasHeaders from) { - assert false : "percolatecontext does not support contexts & headers"; - } - - @Override - public void copyContextAndHeadersFrom(HasContextAndHeaders other) { - assert false : "percolatecontext does not support contexts & headers"; - } - @Override public Map, Collector> queryCollectors() { return queryCollectors; diff --git a/core/src/main/java/org/elasticsearch/percolator/PercolatorService.java b/core/src/main/java/org/elasticsearch/percolator/PercolatorService.java index e6ffa313e83..cb5686ab453 100644 --- a/core/src/main/java/org/elasticsearch/percolator/PercolatorService.java +++ b/core/src/main/java/org/elasticsearch/percolator/PercolatorService.java @@ -39,7 +39,6 @@ import org.elasticsearch.cache.recycler.PageCacheRecycler; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; -import org.elasticsearch.common.HasContextAndHeaders; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.component.AbstractComponent; @@ -135,14 +134,14 @@ public class PercolatorService extends AbstractComponent { multi = new MultiDocumentPercolatorIndex(cache); } - public ReduceResult reduce(boolean onlyCount, List shardResponses, HasContextAndHeaders headersContext) throws IOException { + public ReduceResult reduce(boolean onlyCount, List shardResponses) throws IOException { if (onlyCount) { long finalCount = 0; for (PercolateShardResponse shardResponse : shardResponses) { finalCount += shardResponse.topDocs().totalHits; } - InternalAggregations reducedAggregations = reduceAggregations(shardResponses, headersContext); + InternalAggregations reducedAggregations = reduceAggregations(shardResponses); return new PercolatorService.ReduceResult(finalCount, reducedAggregations); } else { int requestedSize = shardResponses.get(0).requestedSize(); @@ -162,7 +161,7 @@ public class PercolatorService extends AbstractComponent { Map hl = shardResponse.hls().get(doc.doc); matches[i] = new PercolateResponse.Match(new Text(shardResponse.getIndex()), new Text(id), doc.score, hl); } - InternalAggregations reducedAggregations = reduceAggregations(shardResponses, headersContext); + InternalAggregations reducedAggregations = reduceAggregations(shardResponses); return new PercolatorService.ReduceResult(foundMatches, matches, reducedAggregations); } } @@ -307,7 +306,7 @@ public class PercolatorService extends AbstractComponent { cache.close(); } - private InternalAggregations reduceAggregations(List shardResults, HasContextAndHeaders headersContext) { + private InternalAggregations reduceAggregations(List shardResults) { if (shardResults.get(0).aggregations() == null) { return null; } @@ -316,7 +315,7 @@ public class PercolatorService extends AbstractComponent { for (PercolateShardResponse shardResult : shardResults) { aggregationsList.add(shardResult.aggregations()); } - InternalAggregations aggregations = InternalAggregations.reduce(aggregationsList, new InternalAggregation.ReduceContext(bigArrays, scriptService, headersContext)); + InternalAggregations aggregations = InternalAggregations.reduce(aggregationsList, new InternalAggregation.ReduceContext(bigArrays, scriptService)); if (aggregations != null) { List pipelineAggregators = shardResults.get(0).pipelineAggregators(); if (pipelineAggregators != null) { @@ -324,7 +323,7 @@ public class PercolatorService extends AbstractComponent { return (InternalAggregation) p; }).collect(Collectors.toList()); for (SiblingPipelineAggregator pipelineAggregator : pipelineAggregators) { - InternalAggregation newAgg = pipelineAggregator.doReduce(new InternalAggregations(newAggs), new InternalAggregation.ReduceContext(bigArrays, scriptService, headersContext)); + InternalAggregation newAgg = pipelineAggregator.doReduce(new InternalAggregations(newAggs), new InternalAggregation.ReduceContext(bigArrays, scriptService)); newAggs.add(newAgg); } aggregations = new InternalAggregations(newAggs); diff --git a/core/src/main/java/org/elasticsearch/rest/BaseRestHandler.java b/core/src/main/java/org/elasticsearch/rest/BaseRestHandler.java index 294338c0501..befa5c38b1a 100644 --- a/core/src/main/java/org/elasticsearch/rest/BaseRestHandler.java +++ b/core/src/main/java/org/elasticsearch/rest/BaseRestHandler.java @@ -19,19 +19,11 @@ package org.elasticsearch.rest; -import org.elasticsearch.action.Action; -import org.elasticsearch.action.ActionListener; -import org.elasticsearch.action.ActionRequest; -import org.elasticsearch.action.ActionRequestBuilder; -import org.elasticsearch.action.ActionResponse; import org.elasticsearch.client.Client; -import org.elasticsearch.client.FilterClient; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.settings.Settings; -import java.util.Set; - /** * Base handler for REST requests. *

@@ -42,49 +34,19 @@ import java.util.Set; */ public abstract class BaseRestHandler extends AbstractComponent implements RestHandler { - private final RestController controller; private final Client client; protected final ParseFieldMatcher parseFieldMatcher; - protected BaseRestHandler(Settings settings, RestController controller, Client client) { + protected BaseRestHandler(Settings settings, Client client) { super(settings); - this.controller = controller; this.client = client; this.parseFieldMatcher = new ParseFieldMatcher(settings); } @Override public final void handleRequest(RestRequest request, RestChannel channel) throws Exception { - handleRequest(request, channel, new HeadersAndContextCopyClient(client, request, controller.relevantHeaders())); + handleRequest(request, channel, client); } protected abstract void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception; - - static final class HeadersAndContextCopyClient extends FilterClient { - - private final RestRequest restRequest; - private final Set headers; - - HeadersAndContextCopyClient(Client in, RestRequest restRequest, Set headers) { - super(in); - this.restRequest = restRequest; - this.headers = headers; - } - - private static void copyHeadersAndContext(ActionRequest actionRequest, RestRequest restRequest, Set headers) { - for (String usefulHeader : headers) { - String headerValue = restRequest.header(usefulHeader); - if (headerValue != null) { - actionRequest.putHeader(usefulHeader, headerValue); - } - } - actionRequest.copyContextFrom(restRequest); - } - - @Override - protected > void doExecute(Action action, Request request, ActionListener listener) { - copyHeadersAndContext(request, restRequest, headers); - super.doExecute(action, request, listener); - } - } } diff --git a/core/src/main/java/org/elasticsearch/rest/RestController.java b/core/src/main/java/org/elasticsearch/rest/RestController.java index d0a46d29f65..64e21002d8c 100644 --- a/core/src/main/java/org/elasticsearch/rest/RestController.java +++ b/core/src/main/java/org/elasticsearch/rest/RestController.java @@ -24,13 +24,13 @@ import org.elasticsearch.common.component.AbstractLifecycleComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.path.PathTrie; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.support.RestUtils; import java.io.IOException; import java.util.Arrays; import java.util.Collections; -import java.util.Comparator; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; @@ -107,12 +107,7 @@ public class RestController extends AbstractLifecycleComponent { RestFilter[] copy = new RestFilter[filters.length + 1]; System.arraycopy(filters, 0, copy, 0, filters.length); copy[filters.length] = preProcessor; - Arrays.sort(copy, new Comparator() { - @Override - public int compare(RestFilter o1, RestFilter o2) { - return Integer.compare(o1.order(), o2.order()); - } - }); + Arrays.sort(copy, (o1, o2) -> Integer.compare(o1.order(), o2.order())); filters = copy; } @@ -163,24 +158,31 @@ public class RestController extends AbstractLifecycleComponent { return new ControllerFilterChain(executionFilter); } - public void dispatchRequest(final RestRequest request, final RestChannel channel) { + public void dispatchRequest(final RestRequest request, final RestChannel channel, ThreadContext threadContext) { if (!checkRequestParameters(request, channel)) { return; } - - if (filters.length == 0) { - try { - executeHandler(request, channel); - } catch (Throwable e) { - try { - channel.sendResponse(new BytesRestResponse(channel, e)); - } catch (Throwable e1) { - logger.error("failed to send failure response for uri [" + request.uri() + "]", e1); + try (ThreadContext.StoredContext t = threadContext.stashContext()){ + for (String key : relevantHeaders) { + String httpHeader = request.header(key); + if (httpHeader != null) { + threadContext.putHeader(key, httpHeader); } } - } else { - ControllerFilterChain filterChain = new ControllerFilterChain(handlerFilter); - filterChain.continueProcessing(request, channel); + if (filters.length == 0) { + try { + executeHandler(request, channel); + } catch (Throwable e) { + try { + channel.sendResponse(new BytesRestResponse(channel, e)); + } catch (Throwable e1) { + logger.error("failed to send failure response for uri [" + request.uri() + "]", e1); + } + } + } else { + ControllerFilterChain filterChain = new ControllerFilterChain(handlerFilter); + filterChain.continueProcessing(request, channel); + } } } diff --git a/core/src/main/java/org/elasticsearch/rest/RestRequest.java b/core/src/main/java/org/elasticsearch/rest/RestRequest.java index 81f6052db5c..8872484d589 100644 --- a/core/src/main/java/org/elasticsearch/rest/RestRequest.java +++ b/core/src/main/java/org/elasticsearch/rest/RestRequest.java @@ -20,7 +20,6 @@ package org.elasticsearch.rest; import org.elasticsearch.common.Booleans; -import org.elasticsearch.common.ContextAndHeaderHolder; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; @@ -38,7 +37,7 @@ import static org.elasticsearch.common.unit.TimeValue.parseTimeValue; /** * */ -public abstract class RestRequest extends ContextAndHeaderHolder implements ToXContent.Params { +public abstract class RestRequest implements ToXContent.Params { public enum Method { GET, POST, PUT, DELETE, OPTIONS, HEAD diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/health/RestClusterHealthAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/health/RestClusterHealthAction.java index badf6f6de58..ccd0f982597 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/health/RestClusterHealthAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/health/RestClusterHealthAction.java @@ -43,7 +43,7 @@ public class RestClusterHealthAction extends BaseRestHandler { @Inject public RestClusterHealthAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(RestRequest.Method.GET, "/_cluster/health", this); controller.registerHandler(RestRequest.Method.GET, "/_cluster/health/{index}", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/hotthreads/RestNodesHotThreadsAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/hotthreads/RestNodesHotThreadsAction.java index 24c4c449410..53bec14f967 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/hotthreads/RestNodesHotThreadsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/hotthreads/RestNodesHotThreadsAction.java @@ -43,7 +43,7 @@ public class RestNodesHotThreadsAction extends BaseRestHandler { @Inject public RestNodesHotThreadsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(RestRequest.Method.GET, "/_cluster/nodes/hotthreads", this); controller.registerHandler(RestRequest.Method.GET, "/_cluster/nodes/hot_threads", this); controller.registerHandler(RestRequest.Method.GET, "/_cluster/nodes/{nodeId}/hotthreads", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/info/RestNodesInfoAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/info/RestNodesInfoAction.java index f2c51850000..ce1e7811da6 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/info/RestNodesInfoAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/info/RestNodesInfoAction.java @@ -52,7 +52,7 @@ public class RestNodesInfoAction extends BaseRestHandler { @Inject public RestNodesInfoAction(Settings settings, RestController controller, Client client, SettingsFilter settingsFilter) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_nodes", this); // this endpoint is used for metrics, not for nodeIds, like /_nodes/fs controller.registerHandler(GET, "/_nodes/{nodeId}", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/stats/RestNodesStatsAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/stats/RestNodesStatsAction.java index 786891d330d..2b3f0518c37 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/stats/RestNodesStatsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/node/stats/RestNodesStatsAction.java @@ -45,7 +45,7 @@ public class RestNodesStatsAction extends BaseRestHandler { @Inject public RestNodesStatsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_nodes/stats", this); controller.registerHandler(GET, "/_nodes/{nodeId}/stats", this); 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 813c7822428..46fef04b857 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 @@ -37,7 +37,7 @@ public class RestListTasksAction extends BaseRestHandler { @Inject public RestListTasksAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_tasks", this); controller.registerHandler(GET, "/_tasks/{nodeId}", this); controller.registerHandler(GET, "/_tasks/{nodeId}/{actions}", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/delete/RestDeleteRepositoryAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/delete/RestDeleteRepositoryAction.java index 36e02ba4599..136c1cfae3f 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/delete/RestDeleteRepositoryAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/delete/RestDeleteRepositoryAction.java @@ -40,7 +40,7 @@ public class RestDeleteRepositoryAction extends BaseRestHandler { @Inject public RestDeleteRepositoryAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(DELETE, "/_snapshot/{repository}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/get/RestGetRepositoriesAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/get/RestGetRepositoriesAction.java index fd347ccd332..09422481cf3 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/get/RestGetRepositoriesAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/get/RestGetRepositoriesAction.java @@ -50,7 +50,7 @@ public class RestGetRepositoriesAction extends BaseRestHandler { @Inject public RestGetRepositoriesAction(Settings settings, RestController controller, Client client, SettingsFilter settingsFilter) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_snapshot", this); controller.registerHandler(GET, "/_snapshot/{repository}", this); this.settingsFilter = settingsFilter; diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/put/RestPutRepositoryAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/put/RestPutRepositoryAction.java index feeeeb77aba..878eb2915bc 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/put/RestPutRepositoryAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/put/RestPutRepositoryAction.java @@ -41,7 +41,7 @@ public class RestPutRepositoryAction extends BaseRestHandler { @Inject public RestPutRepositoryAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(PUT, "/_snapshot/{repository}", this); controller.registerHandler(POST, "/_snapshot/{repository}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/verify/RestVerifyRepositoryAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/verify/RestVerifyRepositoryAction.java index c0c7ad5b953..306dcbb21b9 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/verify/RestVerifyRepositoryAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/verify/RestVerifyRepositoryAction.java @@ -36,7 +36,7 @@ public class RestVerifyRepositoryAction extends BaseRestHandler { @Inject public RestVerifyRepositoryAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/_snapshot/{repository}/_verify", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/reroute/RestClusterRerouteAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/reroute/RestClusterRerouteAction.java index 387728918a6..529d73d3e59 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/reroute/RestClusterRerouteAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/reroute/RestClusterRerouteAction.java @@ -49,7 +49,7 @@ public class RestClusterRerouteAction extends BaseRestHandler { @Inject public RestClusterRerouteAction(Settings settings, RestController controller, Client client, SettingsFilter settingsFilter) { - super(settings, controller, client); + super(settings, client); this.settingsFilter = settingsFilter; controller.registerHandler(RestRequest.Method.POST, "/_cluster/reroute", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterGetSettingsAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterGetSettingsAction.java index fc4432a658f..04bda2cb1fa 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterGetSettingsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterGetSettingsAction.java @@ -48,7 +48,7 @@ public class RestClusterGetSettingsAction extends BaseRestHandler { @Inject public RestClusterGetSettingsAction(Settings settings, RestController controller, Client client, ClusterSettings clusterSettings) { - super(settings, controller, client); + super(settings, client); this.clusterSettings = clusterSettings; controller.registerHandler(RestRequest.Method.GET, "/_cluster/settings", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterUpdateSettingsAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterUpdateSettingsAction.java index aa84606b076..64083f1e806 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterUpdateSettingsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterUpdateSettingsAction.java @@ -43,7 +43,7 @@ public class RestClusterUpdateSettingsAction extends BaseRestHandler { @Inject public RestClusterUpdateSettingsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(RestRequest.Method.PUT, "/_cluster/settings", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/shards/RestClusterSearchShardsAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/shards/RestClusterSearchShardsAction.java index ee68c1bbb7a..860e110b2d6 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/shards/RestClusterSearchShardsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/shards/RestClusterSearchShardsAction.java @@ -42,7 +42,7 @@ public class RestClusterSearchShardsAction extends BaseRestHandler { @Inject public RestClusterSearchShardsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_search_shards", this); controller.registerHandler(POST, "/_search_shards", this); controller.registerHandler(GET, "/{index}/_search_shards", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/create/RestCreateSnapshotAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/create/RestCreateSnapshotAction.java index bf9dd4a0119..9d6be664d48 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/create/RestCreateSnapshotAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/create/RestCreateSnapshotAction.java @@ -41,7 +41,7 @@ public class RestCreateSnapshotAction extends BaseRestHandler { @Inject public RestCreateSnapshotAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(PUT, "/_snapshot/{repository}/{snapshot}", this); controller.registerHandler(POST, "/_snapshot/{repository}/{snapshot}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/delete/RestDeleteSnapshotAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/delete/RestDeleteSnapshotAction.java index 66b5a4188c0..38c78bd5d88 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/delete/RestDeleteSnapshotAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/delete/RestDeleteSnapshotAction.java @@ -40,7 +40,7 @@ public class RestDeleteSnapshotAction extends BaseRestHandler { @Inject public RestDeleteSnapshotAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(DELETE, "/_snapshot/{repository}/{snapshot}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/get/RestGetSnapshotsAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/get/RestGetSnapshotsAction.java index 123798cf995..1151fed8f23 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/get/RestGetSnapshotsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/get/RestGetSnapshotsAction.java @@ -41,7 +41,7 @@ public class RestGetSnapshotsAction extends BaseRestHandler { @Inject public RestGetSnapshotsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_snapshot/{repository}/{snapshot}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/restore/RestRestoreSnapshotAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/restore/RestRestoreSnapshotAction.java index 028285d3064..e2a16bd4b46 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/restore/RestRestoreSnapshotAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/restore/RestRestoreSnapshotAction.java @@ -40,7 +40,7 @@ public class RestRestoreSnapshotAction extends BaseRestHandler { @Inject public RestRestoreSnapshotAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/_snapshot/{repository}/{snapshot}/_restore", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/status/RestSnapshotsStatusAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/status/RestSnapshotsStatusAction.java index b60a740a15d..2e8810e2ba7 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/status/RestSnapshotsStatusAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/snapshots/status/RestSnapshotsStatusAction.java @@ -41,7 +41,7 @@ public class RestSnapshotsStatusAction extends BaseRestHandler { @Inject public RestSnapshotsStatusAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_snapshot/{repository}/{snapshot}/_status", this); controller.registerHandler(GET, "/_snapshot/{repository}/_status", this); controller.registerHandler(GET, "/_snapshot/_status", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/state/RestClusterStateAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/state/RestClusterStateAction.java index f28ecfe4888..720d19a7fe4 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/state/RestClusterStateAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/state/RestClusterStateAction.java @@ -52,7 +52,7 @@ public class RestClusterStateAction extends BaseRestHandler { @Inject public RestClusterStateAction(Settings settings, RestController controller, Client client, SettingsFilter settingsFilter) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(RestRequest.Method.GET, "/_cluster/state", this); controller.registerHandler(RestRequest.Method.GET, "/_cluster/state/{metric}", this); controller.registerHandler(RestRequest.Method.GET, "/_cluster/state/{metric}/{indices}", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/stats/RestClusterStatsAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/stats/RestClusterStatsAction.java index b14293ba310..a09820e71b6 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/stats/RestClusterStatsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/stats/RestClusterStatsAction.java @@ -38,7 +38,7 @@ public class RestClusterStatsAction extends BaseRestHandler { @Inject public RestClusterStatsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(RestRequest.Method.GET, "/_cluster/stats", this); controller.registerHandler(RestRequest.Method.GET, "/_cluster/stats/nodes/{nodeId}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/tasks/RestPendingClusterTasksAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/tasks/RestPendingClusterTasksAction.java index 5d9eac430b5..333b6d64491 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/tasks/RestPendingClusterTasksAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/cluster/tasks/RestPendingClusterTasksAction.java @@ -36,7 +36,7 @@ public class RestPendingClusterTasksAction extends BaseRestHandler { @Inject public RestPendingClusterTasksAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(RestRequest.Method.GET, "/_cluster/pending_tasks", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/RestIndicesAliasesAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/RestIndicesAliasesAction.java index f62d6febee5..c60671f8644 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/RestIndicesAliasesAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/RestIndicesAliasesAction.java @@ -47,7 +47,7 @@ public class RestIndicesAliasesAction extends BaseRestHandler { @Inject public RestIndicesAliasesAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/_aliases", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/delete/RestIndexDeleteAliasesAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/delete/RestIndexDeleteAliasesAction.java index 6748cc2509d..7fcaadc3d8b 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/delete/RestIndexDeleteAliasesAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/delete/RestIndexDeleteAliasesAction.java @@ -38,7 +38,7 @@ public class RestIndexDeleteAliasesAction extends BaseRestHandler { @Inject public RestIndexDeleteAliasesAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(DELETE, "/{index}/_alias/{name}", this); controller.registerHandler(DELETE, "/{index}/_aliases/{name}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/get/RestGetAliasesAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/get/RestGetAliasesAction.java index aa62ee471dc..da439c63d5e 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/get/RestGetAliasesAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/get/RestGetAliasesAction.java @@ -52,7 +52,7 @@ public class RestGetAliasesAction extends BaseRestHandler { @Inject public RestGetAliasesAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_alias/{name}", this); controller.registerHandler(GET, "/{index}/_alias/{name}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/get/RestGetIndicesAliasesAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/get/RestGetIndicesAliasesAction.java index 4c774b58645..4f9e2b93c2b 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/get/RestGetIndicesAliasesAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/get/RestGetIndicesAliasesAction.java @@ -51,7 +51,7 @@ public class RestGetIndicesAliasesAction extends BaseRestHandler { @Inject public RestGetIndicesAliasesAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/{index}/_aliases/{name}", this); controller.registerHandler(GET, "/_aliases/{name}", this); } 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 fce40123b68..15ea664245d 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 @@ -44,7 +44,7 @@ public class RestAliasesExistAction extends BaseRestHandler { @Inject public RestAliasesExistAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(HEAD, "/_alias/{name}", this); controller.registerHandler(HEAD, "/{index}/_alias/{name}", this); controller.registerHandler(HEAD, "/{index}/_alias", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/put/RestIndexPutAliasAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/put/RestIndexPutAliasAction.java index 4965f6b218d..7a0c2ad466f 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/put/RestIndexPutAliasAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/alias/put/RestIndexPutAliasAction.java @@ -45,7 +45,7 @@ public class RestIndexPutAliasAction extends BaseRestHandler { @Inject public RestIndexPutAliasAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(PUT, "/{index}/_alias/{name}", this); controller.registerHandler(PUT, "/_alias/{name}", this); controller.registerHandler(PUT, "/{index}/_aliases/{name}", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/analyze/RestAnalyzeAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/analyze/RestAnalyzeAction.java index 3a86911f464..e440e1b95c7 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/analyze/RestAnalyzeAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/analyze/RestAnalyzeAction.java @@ -61,7 +61,7 @@ public class RestAnalyzeAction extends BaseRestHandler { @Inject public RestAnalyzeAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_analyze", this); controller.registerHandler(GET, "/{index}/_analyze", this); controller.registerHandler(POST, "/_analyze", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/cache/clear/RestClearIndicesCacheAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/cache/clear/RestClearIndicesCacheAction.java index cc06a14b8de..7adb6909532 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/cache/clear/RestClearIndicesCacheAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/cache/clear/RestClearIndicesCacheAction.java @@ -51,7 +51,7 @@ public class RestClearIndicesCacheAction extends BaseRestHandler { @Inject public RestClearIndicesCacheAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/_cache/clear", this); controller.registerHandler(POST, "/{index}/_cache/clear", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/close/RestCloseIndexAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/close/RestCloseIndexAction.java index 091fbc1680d..5f211b88d11 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/close/RestCloseIndexAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/close/RestCloseIndexAction.java @@ -39,7 +39,7 @@ public class RestCloseIndexAction extends BaseRestHandler { @Inject public RestCloseIndexAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(RestRequest.Method.POST, "/_close", this); controller.registerHandler(RestRequest.Method.POST, "/{index}/_close", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/create/RestCreateIndexAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/create/RestCreateIndexAction.java index 41a272cc8b7..46bc9388972 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/create/RestCreateIndexAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/create/RestCreateIndexAction.java @@ -37,7 +37,7 @@ public class RestCreateIndexAction extends BaseRestHandler { @Inject public RestCreateIndexAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(RestRequest.Method.PUT, "/{index}", this); controller.registerHandler(RestRequest.Method.POST, "/{index}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/delete/RestDeleteIndexAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/delete/RestDeleteIndexAction.java index 0851fb867b7..4953842c54a 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/delete/RestDeleteIndexAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/delete/RestDeleteIndexAction.java @@ -39,7 +39,7 @@ public class RestDeleteIndexAction extends BaseRestHandler { @Inject public RestDeleteIndexAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(RestRequest.Method.DELETE, "/", this); controller.registerHandler(RestRequest.Method.DELETE, "/{index}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/exists/indices/RestIndicesExistsAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/exists/indices/RestIndicesExistsAction.java index 6843f5c5ce2..72dea18abd9 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/exists/indices/RestIndicesExistsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/exists/indices/RestIndicesExistsAction.java @@ -45,7 +45,7 @@ public class RestIndicesExistsAction extends BaseRestHandler { @Inject public RestIndicesExistsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(HEAD, "/{index}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/exists/types/RestTypesExistsAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/exists/types/RestTypesExistsAction.java index f1f227edfdd..dd206dcb63a 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/exists/types/RestTypesExistsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/exists/types/RestTypesExistsAction.java @@ -44,7 +44,7 @@ public class RestTypesExistsAction extends BaseRestHandler { @Inject public RestTypesExistsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(HEAD, "/{index}/{type}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/flush/RestFlushAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/flush/RestFlushAction.java index 47c0451adfc..f3b3304bcf9 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/flush/RestFlushAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/flush/RestFlushAction.java @@ -47,7 +47,7 @@ public class RestFlushAction extends BaseRestHandler { @Inject public RestFlushAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/_flush", this); controller.registerHandler(POST, "/{index}/_flush", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/flush/RestSyncedFlushAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/flush/RestSyncedFlushAction.java index 4fe893bd411..9bb36f03d65 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/flush/RestSyncedFlushAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/flush/RestSyncedFlushAction.java @@ -45,7 +45,7 @@ public class RestSyncedFlushAction extends BaseRestHandler { @Inject public RestSyncedFlushAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/_flush/synced", this); controller.registerHandler(POST, "/{index}/_flush/synced", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/forcemerge/RestForceMergeAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/forcemerge/RestForceMergeAction.java index d8ef7bace3a..8aa2683be5e 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/forcemerge/RestForceMergeAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/forcemerge/RestForceMergeAction.java @@ -46,7 +46,7 @@ public class RestForceMergeAction extends BaseRestHandler { @Inject public RestForceMergeAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/_forcemerge", this); controller.registerHandler(POST, "/{index}/_forcemerge", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/get/RestGetIndicesAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/get/RestGetIndicesAction.java index b7371f7b80e..f32f69b57ed 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/get/RestGetIndicesAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/get/RestGetIndicesAction.java @@ -54,7 +54,7 @@ public class RestGetIndicesAction extends BaseRestHandler { @Inject public RestGetIndicesAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/{index}", this); controller.registerHandler(GET, "/{index}/{type}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/mapping/get/RestGetFieldMappingAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/mapping/get/RestGetFieldMappingAction.java index 7594a097c94..0db931d0a7a 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/mapping/get/RestGetFieldMappingAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/mapping/get/RestGetFieldMappingAction.java @@ -51,7 +51,7 @@ public class RestGetFieldMappingAction extends BaseRestHandler { @Inject public RestGetFieldMappingAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_mapping/field/{fields}", this); controller.registerHandler(GET, "/_mapping/{type}/field/{fields}", this); controller.registerHandler(GET, "/{index}/_mapping/field/{fields}", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/mapping/get/RestGetMappingAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/mapping/get/RestGetMappingAction.java index 48fa60cb4b0..09be44648f9 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/mapping/get/RestGetMappingAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/mapping/get/RestGetMappingAction.java @@ -52,7 +52,7 @@ public class RestGetMappingAction extends BaseRestHandler { @Inject public RestGetMappingAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/{index}/{type}/_mapping", this); controller.registerHandler(GET, "/{index}/_mappings/{type}", this); controller.registerHandler(GET, "/{index}/_mapping/{type}", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/mapping/put/RestPutMappingAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/mapping/put/RestPutMappingAction.java index 3ceecbfd3a9..fdb16d2fb8f 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/mapping/put/RestPutMappingAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/mapping/put/RestPutMappingAction.java @@ -44,7 +44,7 @@ public class RestPutMappingAction extends BaseRestHandler { @Inject public RestPutMappingAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(PUT, "/{index}/_mapping/", this); controller.registerHandler(PUT, "/{index}/{type}/_mapping", this); controller.registerHandler(PUT, "/{index}/_mapping/{type}", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/open/RestOpenIndexAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/open/RestOpenIndexAction.java index cb22f81ba46..58bda9d3a3d 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/open/RestOpenIndexAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/open/RestOpenIndexAction.java @@ -39,7 +39,7 @@ public class RestOpenIndexAction extends BaseRestHandler { @Inject public RestOpenIndexAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(RestRequest.Method.POST, "/_open", this); controller.registerHandler(RestRequest.Method.POST, "/{index}/_open", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/recovery/RestRecoveryAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/recovery/RestRecoveryAction.java index e46831e81e8..88bc9fb8c9f 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/recovery/RestRecoveryAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/recovery/RestRecoveryAction.java @@ -45,7 +45,7 @@ public class RestRecoveryAction extends BaseRestHandler { @Inject public RestRecoveryAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_recovery", this); controller.registerHandler(GET, "/{index}/_recovery", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/refresh/RestRefreshAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/refresh/RestRefreshAction.java index e552b13316a..fcc6d240b34 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/refresh/RestRefreshAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/refresh/RestRefreshAction.java @@ -47,7 +47,7 @@ public class RestRefreshAction extends BaseRestHandler { @Inject public RestRefreshAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/_refresh", this); controller.registerHandler(POST, "/{index}/_refresh", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/segments/RestIndicesSegmentsAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/segments/RestIndicesSegmentsAction.java index a233c75da58..da76a769ce4 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/segments/RestIndicesSegmentsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/segments/RestIndicesSegmentsAction.java @@ -45,7 +45,7 @@ public class RestIndicesSegmentsAction extends BaseRestHandler { @Inject public RestIndicesSegmentsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_segments", this); controller.registerHandler(GET, "/{index}/_segments", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/settings/RestGetSettingsAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/settings/RestGetSettingsAction.java index f27897aa731..d41e09141af 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/settings/RestGetSettingsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/settings/RestGetSettingsAction.java @@ -44,7 +44,7 @@ public class RestGetSettingsAction extends BaseRestHandler { @Inject public RestGetSettingsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/{index}/_settings/{name}", this); controller.registerHandler(GET, "/_settings/{name}", this); controller.registerHandler(GET, "/{index}/_setting/{name}", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/settings/RestUpdateSettingsAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/settings/RestUpdateSettingsAction.java index 1a8ba58306d..bcf43a4baa6 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/settings/RestUpdateSettingsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/settings/RestUpdateSettingsAction.java @@ -53,7 +53,7 @@ public class RestUpdateSettingsAction extends BaseRestHandler { @Inject public RestUpdateSettingsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(RestRequest.Method.PUT, "/{index}/_settings", this); controller.registerHandler(RestRequest.Method.PUT, "/_settings", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/shards/RestIndicesShardStoresAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/shards/RestIndicesShardStoresAction.java index e2dc64cc475..586599c1a1e 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/shards/RestIndicesShardStoresAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/shards/RestIndicesShardStoresAction.java @@ -46,7 +46,7 @@ public class RestIndicesShardStoresAction extends BaseRestHandler { @Inject public RestIndicesShardStoresAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_shard_stores", this); controller.registerHandler(GET, "/{index}/_shard_stores", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/stats/RestIndicesStatsAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/stats/RestIndicesStatsAction.java index 891afd6b8cf..e75dfcc4dc7 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/stats/RestIndicesStatsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/stats/RestIndicesStatsAction.java @@ -47,7 +47,7 @@ public class RestIndicesStatsAction extends BaseRestHandler { @Inject public RestIndicesStatsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_stats", this); controller.registerHandler(GET, "/_stats/{metric}", this); controller.registerHandler(GET, "/_stats/{metric}/{indexMetric}", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/delete/RestDeleteIndexTemplateAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/delete/RestDeleteIndexTemplateAction.java index a4c1869609b..a59ab9ac704 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/delete/RestDeleteIndexTemplateAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/delete/RestDeleteIndexTemplateAction.java @@ -36,7 +36,7 @@ public class RestDeleteIndexTemplateAction extends BaseRestHandler { @Inject public RestDeleteIndexTemplateAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(RestRequest.Method.DELETE, "/_template/{name}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/get/RestGetIndexTemplateAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/get/RestGetIndexTemplateAction.java index d5bfa0db907..d62d97400c5 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/get/RestGetIndexTemplateAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/get/RestGetIndexTemplateAction.java @@ -50,7 +50,7 @@ public class RestGetIndexTemplateAction extends BaseRestHandler { @Inject public RestGetIndexTemplateAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_template", this); controller.registerHandler(GET, "/_template/{name}", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/head/RestHeadIndexTemplateAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/head/RestHeadIndexTemplateAction.java index 0838fa887e6..648d083e763 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/head/RestHeadIndexTemplateAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/head/RestHeadIndexTemplateAction.java @@ -42,7 +42,7 @@ public class RestHeadIndexTemplateAction extends BaseRestHandler { @Inject public RestHeadIndexTemplateAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(HEAD, "/_template/{name}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/put/RestPutIndexTemplateAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/put/RestPutIndexTemplateAction.java index 45f8a674dde..0b08b64e89b 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/put/RestPutIndexTemplateAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/template/put/RestPutIndexTemplateAction.java @@ -36,7 +36,7 @@ public class RestPutIndexTemplateAction extends BaseRestHandler { @Inject public RestPutIndexTemplateAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(RestRequest.Method.PUT, "/_template/{name}", this); controller.registerHandler(RestRequest.Method.POST, "/_template/{name}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/upgrade/RestUpgradeAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/upgrade/RestUpgradeAction.java index 6a554db60fe..60a781f90bb 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/upgrade/RestUpgradeAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/upgrade/RestUpgradeAction.java @@ -49,7 +49,7 @@ public class RestUpgradeAction extends BaseRestHandler { @Inject public RestUpgradeAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/_upgrade", this); controller.registerHandler(POST, "/{index}/_upgrade", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/validate/query/RestValidateQueryAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/validate/query/RestValidateQueryAction.java index 81bdaf7536b..86d6e9d6089 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/validate/query/RestValidateQueryAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/validate/query/RestValidateQueryAction.java @@ -57,7 +57,7 @@ public class RestValidateQueryAction extends BaseRestHandler { @Inject public RestValidateQueryAction(Settings settings, RestController controller, Client client, IndicesQueriesRegistry indicesQueriesRegistry) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_validate/query", this); controller.registerHandler(POST, "/_validate/query", this); controller.registerHandler(GET, "/{index}/_validate/query", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/validate/template/RestRenderSearchTemplateAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/validate/template/RestRenderSearchTemplateAction.java index 5ebec7130df..f1308657528 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/validate/template/RestRenderSearchTemplateAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/validate/template/RestRenderSearchTemplateAction.java @@ -52,7 +52,7 @@ public class RestRenderSearchTemplateAction extends BaseRestHandler { @Inject public RestRenderSearchTemplateAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_render/template", this); controller.registerHandler(POST, "/_render/template", this); controller.registerHandler(GET, "/_render/template/{id}", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/bulk/RestBulkAction.java b/core/src/main/java/org/elasticsearch/rest/action/bulk/RestBulkAction.java index 37ce03bac70..3c0f4440d40 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/bulk/RestBulkAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/bulk/RestBulkAction.java @@ -58,7 +58,7 @@ public class RestBulkAction extends BaseRestHandler { @Inject public RestBulkAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/_bulk", this); controller.registerHandler(PUT, "/_bulk", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/cat/AbstractCatAction.java b/core/src/main/java/org/elasticsearch/rest/action/cat/AbstractCatAction.java index 895211a0979..12393f58007 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/cat/AbstractCatAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/cat/AbstractCatAction.java @@ -39,7 +39,7 @@ import static org.elasticsearch.rest.action.support.RestTable.pad; public abstract class AbstractCatAction extends BaseRestHandler { public AbstractCatAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); } protected abstract void doRequest(final RestRequest request, final RestChannel channel, final Client client); diff --git a/core/src/main/java/org/elasticsearch/rest/action/cat/RestCatAction.java b/core/src/main/java/org/elasticsearch/rest/action/cat/RestCatAction.java index 337684769f3..23229540b96 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/cat/RestCatAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/cat/RestCatAction.java @@ -41,7 +41,7 @@ public class RestCatAction extends BaseRestHandler { @Inject public RestCatAction(Settings settings, RestController controller, Set catActions, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_cat", this); StringBuilder sb = new StringBuilder(); sb.append(CAT_NL); diff --git a/core/src/main/java/org/elasticsearch/rest/action/count/RestCountAction.java b/core/src/main/java/org/elasticsearch/rest/action/count/RestCountAction.java index 834b3d391b1..c423f7a8537 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/count/RestCountAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/count/RestCountAction.java @@ -54,7 +54,7 @@ public class RestCountAction extends BaseRestHandler { @Inject public RestCountAction(Settings settings, RestController controller, Client client, IndicesQueriesRegistry indicesQueriesRegistry) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/_count", this); controller.registerHandler(GET, "/_count", this); controller.registerHandler(POST, "/{index}/_count", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/delete/RestDeleteAction.java b/core/src/main/java/org/elasticsearch/rest/action/delete/RestDeleteAction.java index 4336c9db2d4..8e3449344c4 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/delete/RestDeleteAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/delete/RestDeleteAction.java @@ -41,7 +41,7 @@ public class RestDeleteAction extends BaseRestHandler { @Inject public RestDeleteAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(DELETE, "/{index}/{type}/{id}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/explain/RestExplainAction.java b/core/src/main/java/org/elasticsearch/rest/action/explain/RestExplainAction.java index 0e472bb0bf3..864cddc4ba0 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/explain/RestExplainAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/explain/RestExplainAction.java @@ -58,7 +58,7 @@ public class RestExplainAction extends BaseRestHandler { @Inject public RestExplainAction(Settings settings, RestController controller, Client client, IndicesQueriesRegistry indicesQueriesRegistry) { - super(settings, controller, client); + super(settings, client); this.indicesQueriesRegistry = indicesQueriesRegistry; controller.registerHandler(GET, "/{index}/{type}/{id}/_explain", this); controller.registerHandler(POST, "/{index}/{type}/{id}/_explain", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/fieldstats/RestFieldStatsAction.java b/core/src/main/java/org/elasticsearch/rest/action/fieldstats/RestFieldStatsAction.java index c314c4325d6..17b406c71eb 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/fieldstats/RestFieldStatsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/fieldstats/RestFieldStatsAction.java @@ -50,7 +50,7 @@ public class RestFieldStatsAction extends BaseRestHandler { @Inject public RestFieldStatsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_field_stats", this); controller.registerHandler(POST, "/_field_stats", this); controller.registerHandler(GET, "/{index}/_field_stats", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/get/RestGetAction.java b/core/src/main/java/org/elasticsearch/rest/action/get/RestGetAction.java index e85eef48574..0f541bf7a97 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/get/RestGetAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/get/RestGetAction.java @@ -48,7 +48,7 @@ public class RestGetAction extends BaseRestHandler { @Inject public RestGetAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/{index}/{type}/{id}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/get/RestGetSourceAction.java b/core/src/main/java/org/elasticsearch/rest/action/get/RestGetSourceAction.java index ff6c04a6d12..d38ad458c43 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/get/RestGetSourceAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/get/RestGetSourceAction.java @@ -48,7 +48,7 @@ public class RestGetSourceAction extends BaseRestHandler { @Inject public RestGetSourceAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/{index}/{type}/{id}/_source", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/get/RestHeadAction.java b/core/src/main/java/org/elasticsearch/rest/action/get/RestHeadAction.java index f32c07f20f1..31fd0cc9eac 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/get/RestHeadAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/get/RestHeadAction.java @@ -44,7 +44,7 @@ public class RestHeadAction extends BaseRestHandler { @Inject public RestHeadAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(HEAD, "/{index}/{type}/{id}", this); controller.registerHandler(HEAD, "/{index}/{type}/{id}/_source", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/get/RestMultiGetAction.java b/core/src/main/java/org/elasticsearch/rest/action/get/RestMultiGetAction.java index 440312b7cb9..01a9c1b4e5a 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/get/RestMultiGetAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/get/RestMultiGetAction.java @@ -42,7 +42,7 @@ public class RestMultiGetAction extends BaseRestHandler { @Inject public RestMultiGetAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_mget", this); controller.registerHandler(POST, "/_mget", this); controller.registerHandler(GET, "/{index}/_mget", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/index/RestIndexAction.java b/core/src/main/java/org/elasticsearch/rest/action/index/RestIndexAction.java index 13a93299187..5a65699df8c 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/index/RestIndexAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/index/RestIndexAction.java @@ -47,7 +47,7 @@ public class RestIndexAction extends BaseRestHandler { @Inject public RestIndexAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/{index}/{type}", this); // auto id creation controller.registerHandler(PUT, "/{index}/{type}/{id}", this); controller.registerHandler(POST, "/{index}/{type}/{id}", this); @@ -58,7 +58,7 @@ public class RestIndexAction extends BaseRestHandler { final class CreateHandler extends BaseRestHandler { protected CreateHandler(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); } @Override diff --git a/core/src/main/java/org/elasticsearch/rest/action/main/RestMainAction.java b/core/src/main/java/org/elasticsearch/rest/action/main/RestMainAction.java index 42de9b898ae..aaf0906b0f5 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/main/RestMainAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/main/RestMainAction.java @@ -48,7 +48,7 @@ public class RestMainAction extends BaseRestHandler { @Inject public RestMainAction(Settings settings, Version version, RestController controller, ClusterName clusterName, Client client, ClusterService clusterService) { - super(settings, controller, client); + super(settings, client); this.version = version; this.clusterName = clusterName; this.clusterService = clusterService; diff --git a/core/src/main/java/org/elasticsearch/rest/action/percolate/RestMultiPercolateAction.java b/core/src/main/java/org/elasticsearch/rest/action/percolate/RestMultiPercolateAction.java index 879ec78d754..9e925022cf8 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/percolate/RestMultiPercolateAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/percolate/RestMultiPercolateAction.java @@ -44,7 +44,7 @@ public class RestMultiPercolateAction extends BaseRestHandler { @Inject public RestMultiPercolateAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/_mpercolate", this); controller.registerHandler(POST, "/{index}/_mpercolate", this); controller.registerHandler(POST, "/{index}/{type}/_mpercolate", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/percolate/RestPercolateAction.java b/core/src/main/java/org/elasticsearch/rest/action/percolate/RestPercolateAction.java index 052fa42104b..a7c66b245e1 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/percolate/RestPercolateAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/percolate/RestPercolateAction.java @@ -44,7 +44,7 @@ public class RestPercolateAction extends BaseRestHandler { @Inject public RestPercolateAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/{index}/{type}/_percolate", this); controller.registerHandler(POST, "/{index}/{type}/_percolate", this); @@ -109,7 +109,7 @@ public class RestPercolateAction extends BaseRestHandler { final class RestCountPercolateDocHandler extends BaseRestHandler { private RestCountPercolateDocHandler(Settings settings, final RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); } @Override @@ -123,7 +123,7 @@ public class RestPercolateAction extends BaseRestHandler { final class RestPercolateExistingDocHandler extends BaseRestHandler { protected RestPercolateExistingDocHandler(Settings settings, final RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); } @Override @@ -136,7 +136,7 @@ public class RestPercolateAction extends BaseRestHandler { final class RestCountPercolateExistingDocHandler extends BaseRestHandler { protected RestCountPercolateExistingDocHandler(Settings settings, final RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); } @Override diff --git a/core/src/main/java/org/elasticsearch/rest/action/script/RestDeleteIndexedScriptAction.java b/core/src/main/java/org/elasticsearch/rest/action/script/RestDeleteIndexedScriptAction.java index b492e7c513f..9009025d3a9 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/script/RestDeleteIndexedScriptAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/script/RestDeleteIndexedScriptAction.java @@ -47,7 +47,7 @@ public class RestDeleteIndexedScriptAction extends BaseRestHandler { } protected RestDeleteIndexedScriptAction(Settings settings, RestController controller, boolean registerDefaultHandlers, Client client) { - super(settings, controller, client); + super(settings, client); if (registerDefaultHandlers) { controller.registerHandler(DELETE, "/_scripts/{lang}/{id}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/script/RestGetIndexedScriptAction.java b/core/src/main/java/org/elasticsearch/rest/action/script/RestGetIndexedScriptAction.java index a4c6784d415..e2c4ff6373d 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/script/RestGetIndexedScriptAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/script/RestGetIndexedScriptAction.java @@ -48,7 +48,7 @@ public class RestGetIndexedScriptAction extends BaseRestHandler { } protected RestGetIndexedScriptAction(Settings settings, RestController controller, boolean registerDefaultHandlers, Client client) { - super(settings, controller, client); + super(settings, client); if (registerDefaultHandlers) { controller.registerHandler(GET, "/_scripts/{lang}/{id}", this); } diff --git a/core/src/main/java/org/elasticsearch/rest/action/script/RestPutIndexedScriptAction.java b/core/src/main/java/org/elasticsearch/rest/action/script/RestPutIndexedScriptAction.java index ed440c2b9fa..f5a6f67517e 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/script/RestPutIndexedScriptAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/script/RestPutIndexedScriptAction.java @@ -55,7 +55,7 @@ public class RestPutIndexedScriptAction extends BaseRestHandler { } protected RestPutIndexedScriptAction(Settings settings, RestController controller, boolean registerDefaultHandlers, Client client) { - super(settings, controller, client); + super(settings, client); if (registerDefaultHandlers) { controller.registerHandler(POST, "/_scripts/{lang}/{id}", this); controller.registerHandler(PUT, "/_scripts/{lang}/{id}", this); @@ -67,7 +67,7 @@ public class RestPutIndexedScriptAction extends BaseRestHandler { final class CreateHandler extends BaseRestHandler { protected CreateHandler(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); } @Override diff --git a/core/src/main/java/org/elasticsearch/rest/action/search/RestClearScrollAction.java b/core/src/main/java/org/elasticsearch/rest/action/search/RestClearScrollAction.java index b2a2905585c..0dce23bf3b1 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/search/RestClearScrollAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/search/RestClearScrollAction.java @@ -47,7 +47,7 @@ public class RestClearScrollAction extends BaseRestHandler { @Inject public RestClearScrollAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(DELETE, "/_search/scroll", this); controller.registerHandler(DELETE, "/_search/scroll/{scroll_id}", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/search/RestMultiSearchAction.java b/core/src/main/java/org/elasticsearch/rest/action/search/RestMultiSearchAction.java index ff51263e08b..ed69dd6287b 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/search/RestMultiSearchAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/search/RestMultiSearchAction.java @@ -62,7 +62,7 @@ public class RestMultiSearchAction extends BaseRestHandler { @Inject public RestMultiSearchAction(Settings settings, RestController controller, Client client, IndicesQueriesRegistry indicesQueriesRegistry) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_msearch", this); controller.registerHandler(POST, "/_msearch", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/search/RestSearchAction.java b/core/src/main/java/org/elasticsearch/rest/action/search/RestSearchAction.java index 6db9531af84..e58caea5320 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/search/RestSearchAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/search/RestSearchAction.java @@ -65,7 +65,7 @@ public class RestSearchAction extends BaseRestHandler { @Inject public RestSearchAction(Settings settings, RestController controller, Client client, IndicesQueriesRegistry queryRegistry) { - super(settings, controller, client); + super(settings, client); this.queryRegistry = queryRegistry; controller.registerHandler(GET, "/_search", this); controller.registerHandler(POST, "/_search", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/search/RestSearchScrollAction.java b/core/src/main/java/org/elasticsearch/rest/action/search/RestSearchScrollAction.java index eb7e0465902..9e9964245e4 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/search/RestSearchScrollAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/search/RestSearchScrollAction.java @@ -51,7 +51,7 @@ public class RestSearchScrollAction extends BaseRestHandler { @Inject public RestSearchScrollAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_search/scroll", this); controller.registerHandler(POST, "/_search/scroll", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/suggest/RestSuggestAction.java b/core/src/main/java/org/elasticsearch/rest/action/suggest/RestSuggestAction.java index 2841bbe1fe3..4e6b88b68b8 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/suggest/RestSuggestAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/suggest/RestSuggestAction.java @@ -49,7 +49,7 @@ public class RestSuggestAction extends BaseRestHandler { @Inject public RestSuggestAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/_suggest", this); controller.registerHandler(GET, "/_suggest", this); controller.registerHandler(POST, "/{index}/_suggest", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/template/RestPutSearchTemplateAction.java b/core/src/main/java/org/elasticsearch/rest/action/template/RestPutSearchTemplateAction.java index 1523d299f03..4d0da8f0d14 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/template/RestPutSearchTemplateAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/template/RestPutSearchTemplateAction.java @@ -50,7 +50,7 @@ public class RestPutSearchTemplateAction extends RestPutIndexedScriptAction { final class CreateHandler extends BaseRestHandler { protected CreateHandler(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); } @Override diff --git a/core/src/main/java/org/elasticsearch/rest/action/termvectors/RestMultiTermVectorsAction.java b/core/src/main/java/org/elasticsearch/rest/action/termvectors/RestMultiTermVectorsAction.java index fe897f9b09f..dfcbeef171c 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/termvectors/RestMultiTermVectorsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/termvectors/RestMultiTermVectorsAction.java @@ -40,7 +40,7 @@ public class RestMultiTermVectorsAction extends BaseRestHandler { @Inject public RestMultiTermVectorsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/_mtermvectors", this); controller.registerHandler(POST, "/_mtermvectors", this); controller.registerHandler(GET, "/{index}/_mtermvectors", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/termvectors/RestTermVectorsAction.java b/core/src/main/java/org/elasticsearch/rest/action/termvectors/RestTermVectorsAction.java index af81dfcd0a9..dbbd885fe64 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/termvectors/RestTermVectorsAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/termvectors/RestTermVectorsAction.java @@ -49,7 +49,7 @@ public class RestTermVectorsAction extends BaseRestHandler { @Inject public RestTermVectorsAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(GET, "/{index}/{type}/_termvectors", this); controller.registerHandler(POST, "/{index}/{type}/_termvectors", this); controller.registerHandler(GET, "/{index}/{type}/{id}/_termvectors", this); diff --git a/core/src/main/java/org/elasticsearch/rest/action/update/RestUpdateAction.java b/core/src/main/java/org/elasticsearch/rest/action/update/RestUpdateAction.java index 24264ca292e..88f90374523 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/update/RestUpdateAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/update/RestUpdateAction.java @@ -48,7 +48,7 @@ public class RestUpdateAction extends BaseRestHandler { @Inject public RestUpdateAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(POST, "/{index}/{type}/{id}/_update", this); } diff --git a/core/src/main/java/org/elasticsearch/script/ScriptService.java b/core/src/main/java/org/elasticsearch/script/ScriptService.java index c9e9f9a873d..37095513aed 100644 --- a/core/src/main/java/org/elasticsearch/script/ScriptService.java +++ b/core/src/main/java/org/elasticsearch/script/ScriptService.java @@ -31,7 +31,6 @@ import org.elasticsearch.action.indexedscripts.delete.DeleteIndexedScriptRequest import org.elasticsearch.action.indexedscripts.get.GetIndexedScriptRequest; import org.elasticsearch.action.indexedscripts.put.PutIndexedScriptRequest; import org.elasticsearch.client.Client; -import org.elasticsearch.common.HasContextAndHeaders; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.Strings; @@ -225,7 +224,7 @@ public class ScriptService extends AbstractComponent implements Closeable { /** * Checks if a script can be executed and compiles it if needed, or returns the previously compiled and cached script. */ - public CompiledScript compile(Script script, ScriptContext scriptContext, HasContextAndHeaders headersContext, Map params) { + public CompiledScript compile(Script script, ScriptContext scriptContext, Map params) { if (script == null) { throw new IllegalArgumentException("The parameter script (Script) must not be null."); } @@ -253,14 +252,14 @@ public class ScriptService extends AbstractComponent implements Closeable { " operation [" + scriptContext.getKey() + "] and lang [" + lang + "] are not supported"); } - return compileInternal(script, headersContext, params); + return compileInternal(script, params); } /** * Compiles a script straight-away, or returns the previously compiled and cached script, * without checking if it can be executed based on settings. */ - public CompiledScript compileInternal(Script script, HasContextAndHeaders context, Map params) { + public CompiledScript compileInternal(Script script, Map params) { if (script == null) { throw new IllegalArgumentException("The parameter script (Script) must not be null."); } @@ -297,7 +296,7 @@ public class ScriptService extends AbstractComponent implements Closeable { //the script has been updated in the index since the last look up. final IndexedScript indexedScript = new IndexedScript(lang, name); name = indexedScript.id; - code = getScriptFromIndex(indexedScript.lang, indexedScript.id, context); + code = getScriptFromIndex(indexedScript.lang, indexedScript.id); } CacheKey cacheKey = new CacheKey(scriptEngineService, type == ScriptType.INLINE ? null : name, code, params); @@ -323,7 +322,7 @@ public class ScriptService extends AbstractComponent implements Closeable { public void queryScriptIndex(GetIndexedScriptRequest request, final ActionListener listener) { String scriptLang = validateScriptLanguage(request.scriptLang()); - GetRequest getRequest = new GetRequest(request, SCRIPT_INDEX).type(scriptLang).id(request.id()) + GetRequest getRequest = new GetRequest(SCRIPT_INDEX).type(scriptLang).id(request.id()) .version(request.version()).versionType(request.versionType()) .preference("_local"); //Set preference for no forking client.get(getRequest, listener); @@ -338,13 +337,12 @@ public class ScriptService extends AbstractComponent implements Closeable { return scriptLang; } - String getScriptFromIndex(String scriptLang, String id, HasContextAndHeaders context) { + String getScriptFromIndex(String scriptLang, String id) { if (client == null) { throw new IllegalArgumentException("Got an indexed script with no Client registered."); } scriptLang = validateScriptLanguage(scriptLang); GetRequest getRequest = new GetRequest(SCRIPT_INDEX, scriptLang, id); - getRequest.copyContextAndHeadersFrom(context); GetResponse responseFields = client.get(getRequest).actionGet(); if (responseFields.isExists()) { return getScriptFromResponse(responseFields); @@ -392,7 +390,7 @@ public class ScriptService extends AbstractComponent implements Closeable { //verify that the script compiles validate(request.source(), scriptLang); - IndexRequest indexRequest = new IndexRequest(request).index(SCRIPT_INDEX).type(scriptLang).id(request.id()) + IndexRequest indexRequest = new IndexRequest().index(SCRIPT_INDEX).type(scriptLang).id(request.id()) .version(request.version()).versionType(request.versionType()) .source(request.source()).opType(request.opType()).refresh(true); //Always refresh after indexing a template client.index(indexRequest, listener); @@ -400,7 +398,7 @@ public class ScriptService extends AbstractComponent implements Closeable { public void deleteScriptFromIndex(DeleteIndexedScriptRequest request, ActionListener listener) { String scriptLang = validateScriptLanguage(request.scriptLang()); - DeleteRequest deleteRequest = new DeleteRequest(request).index(SCRIPT_INDEX).type(scriptLang).id(request.id()) + DeleteRequest deleteRequest = new DeleteRequest().index(SCRIPT_INDEX).type(scriptLang).id(request.id()) .refresh(true).version(request.version()).versionType(request.versionType()); client.delete(deleteRequest, listener); } @@ -437,8 +435,8 @@ public class ScriptService extends AbstractComponent implements Closeable { /** * Compiles (or retrieves from cache) and executes the provided script */ - public ExecutableScript executable(Script script, ScriptContext scriptContext, HasContextAndHeaders headersContext, Map params) { - return executable(compile(script, scriptContext, headersContext, params), script.getParams()); + public ExecutableScript executable(Script script, ScriptContext scriptContext, Map params) { + return executable(compile(script, scriptContext, params), script.getParams()); } /** @@ -452,7 +450,7 @@ public class ScriptService extends AbstractComponent implements Closeable { * Compiles (or retrieves from cache) and executes the provided search script */ public SearchScript search(SearchLookup lookup, Script script, ScriptContext scriptContext, Map params) { - CompiledScript compiledScript = compile(script, scriptContext, SearchContext.current(), params); + CompiledScript compiledScript = compile(script, scriptContext, params); return getScriptEngineServiceForLang(compiledScript.lang()).search(compiledScript, lookup, script.getParams()); } diff --git a/core/src/main/java/org/elasticsearch/search/SearchService.java b/core/src/main/java/org/elasticsearch/search/SearchService.java index 473282a5777..4737bd5cc30 100644 --- a/core/src/main/java/org/elasticsearch/search/SearchService.java +++ b/core/src/main/java/org/elasticsearch/search/SearchService.java @@ -566,7 +566,7 @@ public class SearchService extends AbstractLifecycleComponent imp context.scrollContext().scroll = request.scroll(); } if (request.template() != null) { - ExecutableScript executable = this.scriptService.executable(request.template(), ScriptContext.Standard.SEARCH, context, Collections.emptyMap()); + ExecutableScript executable = this.scriptService.executable(request.template(), ScriptContext.Standard.SEARCH, Collections.emptyMap()); BytesReference run = (BytesReference) executable.run(); try (XContentParser parser = XContentFactory.xContent(run).createParser(run)) { QueryParseContext queryParseContext = new QueryParseContext(indicesService.getIndicesQueryRegistry()); diff --git a/core/src/main/java/org/elasticsearch/search/action/SearchServiceTransportAction.java b/core/src/main/java/org/elasticsearch/search/action/SearchServiceTransportAction.java index 6e2bdf932f4..138b215e68f 100644 --- a/core/src/main/java/org/elasticsearch/search/action/SearchServiceTransportAction.java +++ b/core/src/main/java/org/elasticsearch/search/action/SearchServiceTransportAction.java @@ -125,7 +125,7 @@ public class SearchServiceTransportAction extends AbstractComponent { } public void sendClearAllScrollContexts(DiscoveryNode node, ClearScrollRequest request, final ActionListener listener) { - transportService.sendRequest(node, CLEAR_SCROLL_CONTEXTS_ACTION_NAME, new ClearScrollContextsRequest(request), new ActionListenerResponseHandler(listener) { + transportService.sendRequest(node, CLEAR_SCROLL_CONTEXTS_ACTION_NAME, new ClearScrollContextsRequest(), new ActionListenerResponseHandler(listener) { @Override public TransportResponse newInstance() { return TransportResponse.Empty.INSTANCE; @@ -220,11 +220,10 @@ public class SearchServiceTransportAction extends AbstractComponent { } ScrollFreeContextRequest(ClearScrollRequest request, long id) { - this((TransportRequest) request, id); + this(id); } - private ScrollFreeContextRequest(TransportRequest request, long id) { - super(request); + private ScrollFreeContextRequest(long id) { this.id = id; } @@ -252,7 +251,7 @@ public class SearchServiceTransportAction extends AbstractComponent { } SearchFreeContextRequest(SearchRequest request, long id) { - super(request, id); + super(id); this.originalIndices = new OriginalIndices(request); } @@ -322,14 +321,6 @@ public class SearchServiceTransportAction extends AbstractComponent { } public static class ClearScrollContextsRequest extends TransportRequest { - - public ClearScrollContextsRequest() { - } - - ClearScrollContextsRequest(TransportRequest request) { - super(request); - } - } class ClearScrollContextsTransportHandler implements TransportRequestHandler { diff --git a/core/src/main/java/org/elasticsearch/search/aggregations/InternalAggregation.java b/core/src/main/java/org/elasticsearch/search/aggregations/InternalAggregation.java index 1c67a941daf..04b1026446f 100644 --- a/core/src/main/java/org/elasticsearch/search/aggregations/InternalAggregation.java +++ b/core/src/main/java/org/elasticsearch/search/aggregations/InternalAggregation.java @@ -18,8 +18,6 @@ */ package org.elasticsearch.search.aggregations; -import org.elasticsearch.common.DelegatingHasContextAndHeaders; -import org.elasticsearch.common.HasContextAndHeaders; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.StreamInput; @@ -92,13 +90,12 @@ public abstract class InternalAggregation implements Aggregation, ToXContent, St } } - public static class ReduceContext extends DelegatingHasContextAndHeaders { + public static class ReduceContext { private final BigArrays bigArrays; private ScriptService scriptService; - public ReduceContext(BigArrays bigArrays, ScriptService scriptService, HasContextAndHeaders headersContext) { - super(headersContext); + public ReduceContext(BigArrays bigArrays, ScriptService scriptService) { this.bigArrays = bigArrays; this.scriptService = scriptService; } @@ -106,7 +103,7 @@ public abstract class InternalAggregation implements Aggregation, ToXContent, St public BigArrays bigArrays() { return bigArrays; } - + public ScriptService scriptService() { return scriptService; } diff --git a/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/ScriptHeuristic.java b/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/ScriptHeuristic.java index 9efea000512..a160451265f 100644 --- a/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/ScriptHeuristic.java +++ b/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/ScriptHeuristic.java @@ -87,7 +87,7 @@ public class ScriptHeuristic extends SignificanceHeuristic { @Override public void initialize(InternalAggregation.ReduceContext context) { - searchScript = context.scriptService().executable(script, ScriptContext.Standard.AGGS, context, Collections.emptyMap()); + searchScript = context.scriptService().executable(script, ScriptContext.Standard.AGGS, Collections.emptyMap()); searchScript.setNextVar("_subset_freq", subsetDfHolder); searchScript.setNextVar("_subset_size", subsetSizeHolder); searchScript.setNextVar("_superset_freq", supersetDfHolder); @@ -175,7 +175,7 @@ public class ScriptHeuristic extends SignificanceHeuristic { } ExecutableScript searchScript; try { - searchScript = scriptService.executable(script, ScriptContext.Standard.AGGS, context, Collections.emptyMap()); + searchScript = scriptService.executable(script, ScriptContext.Standard.AGGS, Collections.emptyMap()); } catch (Exception e) { throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. the script [{}] could not be loaded", e, script, heuristicName); } diff --git a/core/src/main/java/org/elasticsearch/search/aggregations/metrics/scripted/InternalScriptedMetric.java b/core/src/main/java/org/elasticsearch/search/aggregations/metrics/scripted/InternalScriptedMetric.java index 00c6b6b49bb..3a516c690e7 100644 --- a/core/src/main/java/org/elasticsearch/search/aggregations/metrics/scripted/InternalScriptedMetric.java +++ b/core/src/main/java/org/elasticsearch/search/aggregations/metrics/scripted/InternalScriptedMetric.java @@ -92,7 +92,7 @@ public class InternalScriptedMetric extends InternalMetricsAggregation implement vars.putAll(firstAggregation.reduceScript.getParams()); } CompiledScript compiledScript = reduceContext.scriptService().compile(firstAggregation.reduceScript, - ScriptContext.Standard.AGGS, reduceContext, Collections.emptyMap()); + ScriptContext.Standard.AGGS, Collections.emptyMap()); ExecutableScript script = reduceContext.scriptService().executable(compiledScript, vars); aggregation = script.run(); } else { diff --git a/core/src/main/java/org/elasticsearch/search/aggregations/metrics/scripted/ScriptedMetricAggregator.java b/core/src/main/java/org/elasticsearch/search/aggregations/metrics/scripted/ScriptedMetricAggregator.java index 6603c6289b2..68d886a7bfe 100644 --- a/core/src/main/java/org/elasticsearch/search/aggregations/metrics/scripted/ScriptedMetricAggregator.java +++ b/core/src/main/java/org/elasticsearch/search/aggregations/metrics/scripted/ScriptedMetricAggregator.java @@ -59,11 +59,11 @@ public class ScriptedMetricAggregator extends MetricsAggregator { this.params = params; ScriptService scriptService = context.searchContext().scriptService(); if (initScript != null) { - scriptService.executable(initScript, ScriptContext.Standard.AGGS, context.searchContext(), Collections.emptyMap()).run(); + scriptService.executable(initScript, ScriptContext.Standard.AGGS, Collections.emptyMap()).run(); } this.mapScript = scriptService.search(context.searchContext().lookup(), mapScript, ScriptContext.Standard.AGGS, Collections.emptyMap()); if (combineScript != null) { - this.combineScript = scriptService.executable(combineScript, ScriptContext.Standard.AGGS, context.searchContext(), Collections.emptyMap()); + this.combineScript = scriptService.executable(combineScript, ScriptContext.Standard.AGGS, Collections.emptyMap()); } else { this.combineScript = null; } diff --git a/core/src/main/java/org/elasticsearch/search/aggregations/pipeline/bucketscript/BucketScriptPipelineAggregator.java b/core/src/main/java/org/elasticsearch/search/aggregations/pipeline/bucketscript/BucketScriptPipelineAggregator.java index 76cb15ed46d..4da355f4f8a 100644 --- a/core/src/main/java/org/elasticsearch/search/aggregations/pipeline/bucketscript/BucketScriptPipelineAggregator.java +++ b/core/src/main/java/org/elasticsearch/search/aggregations/pipeline/bucketscript/BucketScriptPipelineAggregator.java @@ -94,7 +94,7 @@ public class BucketScriptPipelineAggregator extends PipelineAggregator { InternalMultiBucketAggregation originalAgg = (InternalMultiBucketAggregation) aggregation; List buckets = originalAgg.getBuckets(); - CompiledScript compiledScript = reduceContext.scriptService().compile(script, ScriptContext.Standard.AGGS, reduceContext, Collections.emptyMap()); + CompiledScript compiledScript = reduceContext.scriptService().compile(script, ScriptContext.Standard.AGGS, Collections.emptyMap()); List newBuckets = new ArrayList<>(); for (Bucket bucket : buckets) { Map vars = new HashMap<>(); diff --git a/core/src/main/java/org/elasticsearch/search/aggregations/pipeline/having/BucketSelectorPipelineAggregator.java b/core/src/main/java/org/elasticsearch/search/aggregations/pipeline/having/BucketSelectorPipelineAggregator.java index edc3b4e87ce..1032d0f0175 100644 --- a/core/src/main/java/org/elasticsearch/search/aggregations/pipeline/having/BucketSelectorPipelineAggregator.java +++ b/core/src/main/java/org/elasticsearch/search/aggregations/pipeline/having/BucketSelectorPipelineAggregator.java @@ -89,7 +89,7 @@ public class BucketSelectorPipelineAggregator extends PipelineAggregator { InternalMultiBucketAggregation originalAgg = (InternalMultiBucketAggregation) aggregation; List buckets = originalAgg.getBuckets(); - CompiledScript compiledScript = reduceContext.scriptService().compile(script, ScriptContext.Standard.AGGS, reduceContext, Collections.emptyMap()); + CompiledScript compiledScript = reduceContext.scriptService().compile(script, ScriptContext.Standard.AGGS, Collections.emptyMap()); List newBuckets = new ArrayList<>(); for (Bucket bucket : buckets) { Map vars = new HashMap<>(); diff --git a/core/src/main/java/org/elasticsearch/search/controller/SearchPhaseController.java b/core/src/main/java/org/elasticsearch/search/controller/SearchPhaseController.java index ef16a03831d..d79b1f59a6a 100644 --- a/core/src/main/java/org/elasticsearch/search/controller/SearchPhaseController.java +++ b/core/src/main/java/org/elasticsearch/search/controller/SearchPhaseController.java @@ -31,7 +31,6 @@ import org.apache.lucene.search.TermStatistics; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopFieldDocs; import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.common.HasContextAndHeaders; import org.elasticsearch.common.collect.HppcMaps; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.inject.Inject; @@ -299,7 +298,7 @@ public class SearchPhaseController extends AbstractComponent { } public InternalSearchResponse merge(ScoreDoc[] sortedDocs, AtomicArray queryResultsArr, - AtomicArray fetchResultsArr, HasContextAndHeaders headersContext) { + AtomicArray fetchResultsArr) { List> queryResults = queryResultsArr.asList(); List> fetchResults = fetchResultsArr.asList(); @@ -407,7 +406,7 @@ public class SearchPhaseController extends AbstractComponent { for (AtomicArray.Entry entry : queryResults) { aggregationsList.add((InternalAggregations) entry.value.queryResult().aggregations()); } - aggregations = InternalAggregations.reduce(aggregationsList, new ReduceContext(bigArrays, scriptService, headersContext)); + aggregations = InternalAggregations.reduce(aggregationsList, new ReduceContext(bigArrays, scriptService)); } } @@ -430,7 +429,7 @@ public class SearchPhaseController extends AbstractComponent { }).collect(Collectors.toList()); for (SiblingPipelineAggregator pipelineAggregator : pipelineAggregators) { InternalAggregation newAgg = pipelineAggregator.doReduce(new InternalAggregations(newAggs), new ReduceContext( - bigArrays, scriptService, headersContext)); + bigArrays, scriptService)); newAggs.add(newAgg); } aggregations = new InternalAggregations(newAggs); diff --git a/core/src/main/java/org/elasticsearch/search/fetch/ShardFetchRequest.java b/core/src/main/java/org/elasticsearch/search/fetch/ShardFetchRequest.java index 0d524ed3e3e..4087eb9a01c 100644 --- a/core/src/main/java/org/elasticsearch/search/fetch/ShardFetchRequest.java +++ b/core/src/main/java/org/elasticsearch/search/fetch/ShardFetchRequest.java @@ -22,7 +22,6 @@ package org.elasticsearch.search.fetch; import com.carrotsearch.hppc.IntArrayList; import org.apache.lucene.search.FieldDoc; import org.apache.lucene.search.ScoreDoc; -import org.elasticsearch.action.search.SearchScrollRequest; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.lucene.Lucene; @@ -47,16 +46,7 @@ public class ShardFetchRequest extends TransportRequest { public ShardFetchRequest() { } - public ShardFetchRequest(SearchScrollRequest request, long id, IntArrayList list, ScoreDoc lastEmittedDoc) { - super(request); - this.id = id; - this.docIds = list.buffer; - this.size = list.size(); - this.lastEmittedDoc = lastEmittedDoc; - } - - protected ShardFetchRequest(TransportRequest originalRequest, long id, IntArrayList list, ScoreDoc lastEmittedDoc) { - super(originalRequest); + public ShardFetchRequest(long id, IntArrayList list, ScoreDoc lastEmittedDoc) { this.id = id; this.docIds = list.buffer; this.size = list.size(); diff --git a/core/src/main/java/org/elasticsearch/search/fetch/ShardFetchSearchRequest.java b/core/src/main/java/org/elasticsearch/search/fetch/ShardFetchSearchRequest.java index cc53b48f135..d908aca0fc8 100644 --- a/core/src/main/java/org/elasticsearch/search/fetch/ShardFetchSearchRequest.java +++ b/core/src/main/java/org/elasticsearch/search/fetch/ShardFetchSearchRequest.java @@ -46,7 +46,7 @@ public class ShardFetchSearchRequest extends ShardFetchRequest implements Indice } public ShardFetchSearchRequest(SearchRequest request, long id, IntArrayList list, ScoreDoc lastEmittedDoc) { - super(request, id, list, lastEmittedDoc); + super(id, list, lastEmittedDoc); this.originalIndices = new OriginalIndices(request); } diff --git a/core/src/main/java/org/elasticsearch/search/internal/DefaultSearchContext.java b/core/src/main/java/org/elasticsearch/search/internal/DefaultSearchContext.java index 3b7848d7d2f..e935dc25755 100644 --- a/core/src/main/java/org/elasticsearch/search/internal/DefaultSearchContext.java +++ b/core/src/main/java/org/elasticsearch/search/internal/DefaultSearchContext.java @@ -165,7 +165,7 @@ public class DefaultSearchContext extends SearchContext { BigArrays bigArrays, Counter timeEstimateCounter, ParseFieldMatcher parseFieldMatcher, TimeValue timeout ) { - super(parseFieldMatcher, request); + super(parseFieldMatcher); this.id = id; this.request = request; this.searchType = request.searchType(); diff --git a/core/src/main/java/org/elasticsearch/search/internal/FilteredSearchContext.java b/core/src/main/java/org/elasticsearch/search/internal/FilteredSearchContext.java index eaa14933b33..72d923eb62e 100644 --- a/core/src/main/java/org/elasticsearch/search/internal/FilteredSearchContext.java +++ b/core/src/main/java/org/elasticsearch/search/internal/FilteredSearchContext.java @@ -62,7 +62,7 @@ public abstract class FilteredSearchContext extends SearchContext { public FilteredSearchContext(SearchContext in) { //inner_hits in percolator ends up with null inner search context - super(in == null ? ParseFieldMatcher.EMPTY : in.parseFieldMatcher(), in); + super(in == null ? ParseFieldMatcher.EMPTY : in.parseFieldMatcher()); this.in = in; } diff --git a/core/src/main/java/org/elasticsearch/search/internal/InternalScrollSearchRequest.java b/core/src/main/java/org/elasticsearch/search/internal/InternalScrollSearchRequest.java index 77a490af385..7f918138045 100644 --- a/core/src/main/java/org/elasticsearch/search/internal/InternalScrollSearchRequest.java +++ b/core/src/main/java/org/elasticsearch/search/internal/InternalScrollSearchRequest.java @@ -42,7 +42,6 @@ public class InternalScrollSearchRequest extends TransportRequest { } public InternalScrollSearchRequest(SearchScrollRequest request, long id) { - super(request); this.id = id; this.scroll = request.scroll(); } diff --git a/core/src/main/java/org/elasticsearch/search/internal/SearchContext.java b/core/src/main/java/org/elasticsearch/search/internal/SearchContext.java index 76164b5c0f8..822031c1a06 100644 --- a/core/src/main/java/org/elasticsearch/search/internal/SearchContext.java +++ b/core/src/main/java/org/elasticsearch/search/internal/SearchContext.java @@ -25,8 +25,6 @@ import org.apache.lucene.search.Sort; import org.apache.lucene.util.Counter; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.cache.recycler.PageCacheRecycler; -import org.elasticsearch.common.DelegatingHasContextAndHeaders; -import org.elasticsearch.common.HasContextAndHeaders; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.lease.Releasable; @@ -66,7 +64,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -public abstract class SearchContext extends DelegatingHasContextAndHeaders implements Releasable { +public abstract class SearchContext implements Releasable { private static ThreadLocal current = new ThreadLocal<>(); public final static int DEFAULT_TERMINATE_AFTER = 0; @@ -90,8 +88,7 @@ public abstract class SearchContext extends DelegatingHasContextAndHeaders imple protected final ParseFieldMatcher parseFieldMatcher; - protected SearchContext(ParseFieldMatcher parseFieldMatcher, HasContextAndHeaders contextHeaders) { - super(contextHeaders); + protected SearchContext(ParseFieldMatcher parseFieldMatcher) { this.parseFieldMatcher = parseFieldMatcher; } diff --git a/core/src/main/java/org/elasticsearch/search/internal/ShardSearchLocalRequest.java b/core/src/main/java/org/elasticsearch/search/internal/ShardSearchLocalRequest.java index 9d15dfd5790..4a42f77f82f 100644 --- a/core/src/main/java/org/elasticsearch/search/internal/ShardSearchLocalRequest.java +++ b/core/src/main/java/org/elasticsearch/search/internal/ShardSearchLocalRequest.java @@ -22,7 +22,6 @@ package org.elasticsearch.search.internal; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.cluster.routing.ShardRouting; -import org.elasticsearch.common.ContextAndHeaderHolder; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamOutput; @@ -57,7 +56,7 @@ import static org.elasticsearch.search.Scroll.readScroll; * */ -public class ShardSearchLocalRequest extends ContextAndHeaderHolder implements ShardSearchRequest { +public class ShardSearchLocalRequest implements ShardSearchRequest { private String index; private int shardId; @@ -84,7 +83,6 @@ public class ShardSearchLocalRequest extends ContextAndHeaderHolder implements S this.scroll = searchRequest.scroll(); this.filteringAliases = filteringAliases; this.nowInMillis = nowInMillis; - copyContextAndHeadersFrom(searchRequest); } public ShardSearchLocalRequest(String[] types, long nowInMillis) { diff --git a/core/src/main/java/org/elasticsearch/search/internal/ShardSearchRequest.java b/core/src/main/java/org/elasticsearch/search/internal/ShardSearchRequest.java index b1730b6a14e..1f0b3d1f188 100644 --- a/core/src/main/java/org/elasticsearch/search/internal/ShardSearchRequest.java +++ b/core/src/main/java/org/elasticsearch/search/internal/ShardSearchRequest.java @@ -20,7 +20,6 @@ package org.elasticsearch.search.internal; import org.elasticsearch.action.search.SearchType; -import org.elasticsearch.common.HasContextAndHeaders; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.script.Template; import org.elasticsearch.search.Scroll; @@ -33,7 +32,7 @@ import java.io.IOException; * It provides all the methods that the {@link org.elasticsearch.search.internal.SearchContext} needs. * Provides a cache key based on its content that can be used to cache shard level response. */ -public interface ShardSearchRequest extends HasContextAndHeaders { +public interface ShardSearchRequest { String index(); diff --git a/core/src/main/java/org/elasticsearch/search/internal/ShardSearchTransportRequest.java b/core/src/main/java/org/elasticsearch/search/internal/ShardSearchTransportRequest.java index 0f9c0ced411..48ea31c170a 100644 --- a/core/src/main/java/org/elasticsearch/search/internal/ShardSearchTransportRequest.java +++ b/core/src/main/java/org/elasticsearch/search/internal/ShardSearchTransportRequest.java @@ -51,7 +51,6 @@ public class ShardSearchTransportRequest extends TransportRequest implements Sha public ShardSearchTransportRequest(SearchRequest searchRequest, ShardRouting shardRouting, int numberOfShards, String[] filteringAliases, long nowInMillis) { - super(searchRequest); this.shardSearchLocalRequest = new ShardSearchLocalRequest(searchRequest, shardRouting, numberOfShards, filteringAliases, nowInMillis); this.originalIndices = new OriginalIndices(searchRequest); } diff --git a/core/src/main/java/org/elasticsearch/search/query/QuerySearchRequest.java b/core/src/main/java/org/elasticsearch/search/query/QuerySearchRequest.java index a1395bd73db..15593abf0da 100644 --- a/core/src/main/java/org/elasticsearch/search/query/QuerySearchRequest.java +++ b/core/src/main/java/org/elasticsearch/search/query/QuerySearchRequest.java @@ -47,7 +47,6 @@ public class QuerySearchRequest extends TransportRequest implements IndicesReque } public QuerySearchRequest(SearchRequest request, long id, AggregatedDfs dfs) { - super(request); this.id = id; this.dfs = dfs; this.originalIndices = new OriginalIndices(request); diff --git a/core/src/main/java/org/elasticsearch/search/suggest/SuggestContextParser.java b/core/src/main/java/org/elasticsearch/search/suggest/SuggestContextParser.java index a8050d1acaf..a7aa3fd60b6 100644 --- a/core/src/main/java/org/elasticsearch/search/suggest/SuggestContextParser.java +++ b/core/src/main/java/org/elasticsearch/search/suggest/SuggestContextParser.java @@ -18,7 +18,6 @@ */ package org.elasticsearch.search.suggest; -import org.elasticsearch.common.HasContextAndHeaders; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.fielddata.IndexFieldDataService; import org.elasticsearch.index.mapper.MapperService; @@ -26,6 +25,6 @@ import org.elasticsearch.index.mapper.MapperService; import java.io.IOException; public interface SuggestContextParser { - SuggestionSearchContext.SuggestionContext parse(XContentParser parser, MapperService mapperService, IndexFieldDataService indexFieldDataService, HasContextAndHeaders headersContext) throws IOException; + SuggestionSearchContext.SuggestionContext parse(XContentParser parser, MapperService mapperService, IndexFieldDataService indexFieldDataService) throws IOException; -} \ No newline at end of file +} diff --git a/core/src/main/java/org/elasticsearch/search/suggest/SuggestParseElement.java b/core/src/main/java/org/elasticsearch/search/suggest/SuggestParseElement.java index 650eb76b1c4..a8a4e9ec26b 100644 --- a/core/src/main/java/org/elasticsearch/search/suggest/SuggestParseElement.java +++ b/core/src/main/java/org/elasticsearch/search/suggest/SuggestParseElement.java @@ -19,7 +19,6 @@ package org.elasticsearch.search.suggest; import org.apache.lucene.util.BytesRef; -import org.elasticsearch.common.HasContextAndHeaders; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.fielddata.IndexFieldDataService; @@ -46,12 +45,12 @@ public final class SuggestParseElement implements SearchParseElement { @Override public void parse(XContentParser parser, SearchContext context) throws Exception { SuggestionSearchContext suggestionSearchContext = parseInternal(parser, context.mapperService(), context.fieldData(), - context.shardTarget().index(), context.shardTarget().shardId(), context); + context.shardTarget().index(), context.shardTarget().shardId()); context.suggest(suggestionSearchContext); } public SuggestionSearchContext parseInternal(XContentParser parser, MapperService mapperService, IndexFieldDataService fieldDataService, - String index, int shardId, HasContextAndHeaders headersContext) throws IOException { + String index, int shardId) throws IOException { SuggestionSearchContext suggestionSearchContext = new SuggestionSearchContext(); BytesRef globalText = null; @@ -96,7 +95,7 @@ public final class SuggestParseElement implements SearchParseElement { throw new IllegalArgumentException("Suggester[" + fieldName + "] not supported"); } final SuggestContextParser contextParser = suggesters.get(fieldName).getContextParser(); - suggestionContext = contextParser.parse(parser, mapperService, fieldDataService, headersContext); + suggestionContext = contextParser.parse(parser, mapperService, fieldDataService); } } if (suggestionContext != null) { diff --git a/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionSuggestParser.java b/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionSuggestParser.java index a2e5f743c59..7d886e1c7eb 100644 --- a/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionSuggestParser.java +++ b/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionSuggestParser.java @@ -20,7 +20,6 @@ package org.elasticsearch.search.suggest.completion; import org.apache.lucene.analysis.Analyzer; import org.elasticsearch.ElasticsearchException; -import org.elasticsearch.common.HasContextAndHeaders; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.unit.Fuzziness; @@ -134,8 +133,7 @@ public class CompletionSuggestParser implements SuggestContextParser { } @Override - public SuggestionSearchContext.SuggestionContext parse(XContentParser parser, MapperService mapperService, IndexFieldDataService fieldDataService, - HasContextAndHeaders headersContext) throws IOException { + public SuggestionSearchContext.SuggestionContext parse(XContentParser parser, MapperService mapperService, IndexFieldDataService fieldDataService) throws IOException { final CompletionSuggestionContext suggestion = new CompletionSuggestionContext(completionSuggester, mapperService, fieldDataService); final ContextAndSuggest contextAndSuggest = new ContextAndSuggest(mapperService); TLP_PARSER.parse(parser, suggestion, contextAndSuggest); diff --git a/core/src/main/java/org/elasticsearch/search/suggest/phrase/PhraseSuggestParser.java b/core/src/main/java/org/elasticsearch/search/suggest/phrase/PhraseSuggestParser.java index 0b904a95720..b4776652fb0 100644 --- a/core/src/main/java/org/elasticsearch/search/suggest/phrase/PhraseSuggestParser.java +++ b/core/src/main/java/org/elasticsearch/search/suggest/phrase/PhraseSuggestParser.java @@ -22,7 +22,6 @@ import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Terms; import org.apache.lucene.util.BytesRef; -import org.elasticsearch.common.HasContextAndHeaders; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser.Token; @@ -50,8 +49,7 @@ public final class PhraseSuggestParser implements SuggestContextParser { } @Override - public SuggestionSearchContext.SuggestionContext parse(XContentParser parser, MapperService mapperService, IndexFieldDataService fieldDataService, - HasContextAndHeaders headersContext) throws IOException { + public SuggestionSearchContext.SuggestionContext parse(XContentParser parser, MapperService mapperService, IndexFieldDataService fieldDataService) throws IOException { PhraseSuggestionContext suggestion = new PhraseSuggestionContext(suggester); ParseFieldMatcher parseFieldMatcher = mapperService.getIndexSettings().getParseFieldMatcher(); XContentParser.Token token; @@ -143,8 +141,7 @@ public final class PhraseSuggestParser implements SuggestContextParser { throw new IllegalArgumentException("suggester[phrase][collate] query already set, doesn't support additional [" + fieldName + "]"); } Template template = Template.parse(parser, parseFieldMatcher); - CompiledScript compiledScript = suggester.scriptService().compile(template, ScriptContext.Standard.SEARCH, - headersContext, Collections.emptyMap()); + CompiledScript compiledScript = suggester.scriptService().compile(template, ScriptContext.Standard.SEARCH, Collections.emptyMap()); suggestion.setCollateQueryScript(compiledScript); } else if ("params".equals(fieldName)) { suggestion.setCollateScriptParams(parser.map()); diff --git a/core/src/main/java/org/elasticsearch/search/suggest/term/TermSuggestParser.java b/core/src/main/java/org/elasticsearch/search/suggest/term/TermSuggestParser.java index a0e0e289540..a2fd680c215 100644 --- a/core/src/main/java/org/elasticsearch/search/suggest/term/TermSuggestParser.java +++ b/core/src/main/java/org/elasticsearch/search/suggest/term/TermSuggestParser.java @@ -18,7 +18,6 @@ */ package org.elasticsearch.search.suggest.term; -import org.elasticsearch.common.HasContextAndHeaders; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.fielddata.IndexFieldDataService; @@ -39,8 +38,7 @@ public final class TermSuggestParser implements SuggestContextParser { } @Override - public SuggestionSearchContext.SuggestionContext parse(XContentParser parser, MapperService mapperService, IndexFieldDataService fieldDataService, - HasContextAndHeaders headersContext) throws IOException { + public SuggestionSearchContext.SuggestionContext parse(XContentParser parser, MapperService mapperService, IndexFieldDataService fieldDataService) throws IOException { XContentParser.Token token; String fieldName = null; TermSuggestionContext suggestion = new TermSuggestionContext(suggester); diff --git a/core/src/main/java/org/elasticsearch/threadpool/ThreadPool.java b/core/src/main/java/org/elasticsearch/threadpool/ThreadPool.java index 0e6204ddd10..378a849115b 100644 --- a/core/src/main/java/org/elasticsearch/threadpool/ThreadPool.java +++ b/core/src/main/java/org/elasticsearch/threadpool/ThreadPool.java @@ -20,6 +20,7 @@ package org.elasticsearch.threadpool; import org.apache.lucene.util.Counter; +import org.apache.lucene.util.IOUtils; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.io.stream.StreamInput; @@ -34,11 +35,13 @@ import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.EsAbortPolicy; import org.elasticsearch.common.util.concurrent.EsExecutors; import org.elasticsearch.common.util.concurrent.EsThreadPoolExecutor; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.util.concurrent.XRejectedExecutionHandler; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilderString; +import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; @@ -67,7 +70,7 @@ import static org.elasticsearch.common.unit.TimeValue.timeValueMinutes; /** * */ -public class ThreadPool extends AbstractComponent { +public class ThreadPool extends AbstractComponent implements Closeable { public static class Names { public static final String SAME = "same"; @@ -200,6 +203,8 @@ public class ThreadPool extends AbstractComponent { static final Executor DIRECT_EXECUTOR = command -> command.run(); + private final ThreadContext threadContext; + public ThreadPool(String name) { this(Settings.builder().put("name", name).build()); } @@ -208,7 +213,7 @@ public class ThreadPool extends AbstractComponent { super(settings); assert settings.get("name") != null : "ThreadPool's settings should contain a name"; - + threadContext = new ThreadContext(settings); Map groupSettings = THREADPOOL_GROUP_SETTING.get(settings).getAsGroups(); validate(groupSettings); @@ -448,7 +453,7 @@ public class ThreadPool extends AbstractComponent { } else { logger.debug("creating thread_pool [{}], type [{}], keep_alive [{}]", name, type, keepAlive); } - Executor executor = EsExecutors.newCached(name, keepAlive.millis(), TimeUnit.MILLISECONDS, threadFactory); + Executor executor = EsExecutors.newCached(name, keepAlive.millis(), TimeUnit.MILLISECONDS, threadFactory, threadContext); return new ExecutorHolder(executor, new Info(name, threadPoolType, -1, -1, keepAlive, null)); } else if (ThreadPoolType.FIXED == threadPoolType) { int defaultSize = defaultSettings.getAsInt("size", EsExecutors.boundedNumberOfProcessors(settings)); @@ -483,7 +488,7 @@ public class ThreadPool extends AbstractComponent { int size = applyHardSizeLimit(name, settings.getAsInt("size", defaultSize)); SizeValue queueSize = getAsSizeOrUnbounded(settings, "capacity", getAsSizeOrUnbounded(settings, "queue", getAsSizeOrUnbounded(settings, "queue_size", defaultQueueSize))); logger.debug("creating thread_pool [{}], type [{}], size [{}], queue_size [{}]", name, type, size, queueSize); - Executor executor = EsExecutors.newFixed(name, size, queueSize == null ? -1 : (int) queueSize.singles(), threadFactory); + Executor executor = EsExecutors.newFixed(name, size, queueSize == null ? -1 : (int) queueSize.singles(), threadFactory, threadContext); return new ExecutorHolder(executor, new Info(name, threadPoolType, size, size, null, queueSize)); } else if (ThreadPoolType.SCALING == threadPoolType) { TimeValue defaultKeepAlive = defaultSettings.getAsTime("keep_alive", timeValueMinutes(5)); @@ -527,7 +532,7 @@ public class ThreadPool extends AbstractComponent { } else { logger.debug("creating thread_pool [{}], type [{}], min [{}], size [{}], keep_alive [{}]", name, type, min, size, keepAlive); } - Executor executor = EsExecutors.newScaling(name, min, size, keepAlive.millis(), TimeUnit.MILLISECONDS, threadFactory); + Executor executor = EsExecutors.newScaling(name, min, size, keepAlive.millis(), TimeUnit.MILLISECONDS, threadFactory, threadContext); return new ExecutorHolder(executor, new Info(name, threadPoolType, min, size, keepAlive, null)); } throw new IllegalArgumentException("No type found [" + type + "], for [" + name + "]"); @@ -914,17 +919,30 @@ public class ThreadPool extends AbstractComponent { */ public static boolean terminate(ThreadPool pool, long timeout, TimeUnit timeUnit) { if (pool != null) { - pool.shutdown(); try { - if (pool.awaitTermination(timeout, timeUnit)) { - return true; + pool.shutdown(); + try { + if (pool.awaitTermination(timeout, timeUnit)) { + return true; + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); + // last resort + pool.shutdownNow(); + } finally { + IOUtils.closeWhileHandlingException(pool); } - // last resort - pool.shutdownNow(); } return false; } + + @Override + public void close() throws IOException { + threadContext.close(); + } + + public ThreadContext getThreadContext() { + return threadContext; + } } diff --git a/core/src/main/java/org/elasticsearch/transport/TransportMessage.java b/core/src/main/java/org/elasticsearch/transport/TransportMessage.java index f52f9179dd6..1434a6eaa73 100644 --- a/core/src/main/java/org/elasticsearch/transport/TransportMessage.java +++ b/core/src/main/java/org/elasticsearch/transport/TransportMessage.java @@ -19,29 +19,20 @@ package org.elasticsearch.transport; -import org.elasticsearch.common.ContextAndHeaderHolder; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Streamable; import org.elasticsearch.common.transport.TransportAddress; import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; -/** - * The transport message is also a {@link ContextAndHeaderHolder context holder} that holds transient context, that is, - * the context is not serialized with message. - */ -public abstract class TransportMessage> extends ContextAndHeaderHolder implements Streamable { +public abstract class TransportMessage> implements Streamable { private TransportAddress remoteAddress; - protected TransportMessage() { - } - - protected TransportMessage(TM message) { - copyContextAndHeadersFrom(message); - } - public void remoteAddress(TransportAddress remoteAddress) { this.remoteAddress = remoteAddress; } @@ -52,16 +43,11 @@ public abstract class TransportMessage> extends @Override public void readFrom(StreamInput in) throws IOException { - headers = in.readBoolean() ? in.readMap() : null; + } @Override public void writeTo(StreamOutput out) throws IOException { - if (headers == null) { - out.writeBoolean(false); - } else { - out.writeBoolean(true); - out.writeMap(headers); - } + } } diff --git a/core/src/main/java/org/elasticsearch/transport/TransportRequest.java b/core/src/main/java/org/elasticsearch/transport/TransportRequest.java index d5c1491f1a6..7db7f0726d0 100644 --- a/core/src/main/java/org/elasticsearch/transport/TransportRequest.java +++ b/core/src/main/java/org/elasticsearch/transport/TransportRequest.java @@ -26,24 +26,12 @@ import org.elasticsearch.tasks.Task; public abstract class TransportRequest extends TransportMessage { public static class Empty extends TransportRequest { - public static final Empty INSTANCE = new Empty(); - - public Empty() { - super(); - } - - public Empty(TransportRequest request) { - super(request); - } } public TransportRequest() { } - protected TransportRequest(TransportRequest request) { - super(request); - } public Task createTask(long id, String type, String action) { return new Task(id, type, action, this::getDescription); diff --git a/core/src/main/java/org/elasticsearch/transport/TransportResponse.java b/core/src/main/java/org/elasticsearch/transport/TransportResponse.java index 8ea7cd60d2d..28dcd12ca53 100644 --- a/core/src/main/java/org/elasticsearch/transport/TransportResponse.java +++ b/core/src/main/java/org/elasticsearch/transport/TransportResponse.java @@ -24,23 +24,6 @@ package org.elasticsearch.transport; public abstract class TransportResponse extends TransportMessage { public static class Empty extends TransportResponse { - public static final Empty INSTANCE = new Empty(); - - public Empty() { - super(); - } - - public Empty(TransportResponse request) { - super(request); - } } - - protected TransportResponse() { - } - - protected TransportResponse(TransportResponse response) { - super(response); - } - } diff --git a/core/src/main/java/org/elasticsearch/transport/TransportService.java b/core/src/main/java/org/elasticsearch/transport/TransportService.java index 5d74c4a408f..8cff05a4d6a 100644 --- a/core/src/main/java/org/elasticsearch/transport/TransportService.java +++ b/core/src/main/java/org/elasticsearch/transport/TransportService.java @@ -40,6 +40,7 @@ import org.elasticsearch.common.util.concurrent.ConcurrentMapLong; import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException; import org.elasticsearch.common.util.concurrent.FutureUtils; import org.elasticsearch.tasks.TaskManager; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.threadpool.ThreadPool; import java.io.IOException; @@ -288,7 +289,7 @@ public class TransportService extends AbstractLifecycleComponent(handler, node, action, timeoutHandler)); + clientHandlers.put(requestId, new RequestHolder<>(new ContextRestoreResponseHandler(threadPool.getThreadContext().newStoredContext(), handler), node, action, timeoutHandler)); if (started.get() == false) { // if we are not started the exception handling will remove the RequestHolder again and calls the handler to notify the caller. // it will only notify if the toStop code hasn't done the work yet. @@ -494,6 +495,7 @@ public class TransportService extends AbstractLifecycleComponent implements TransportResponseHandler { + private final TransportResponseHandler delegate; + private final ThreadContext.StoredContext threadContext; + private ContextRestoreResponseHandler(ThreadContext.StoredContext threadContext, TransportResponseHandler delegate) { + this.delegate = delegate; + this.threadContext = threadContext; + } + + @Override + public T newInstance() { + return delegate.newInstance(); + } + + @Override + public void handleResponse(T response) { + threadContext.restore(); + delegate.handleResponse(response); + } + + @Override + public void handleException(TransportException exp) { + threadContext.restore(); + delegate.handleException(exp); + } + + @Override + public String executor() { + return delegate.executor(); + } + } + static class DirectResponseChannel implements TransportChannel { final ESLogger logger; final DiscoveryNode localNode; 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 ba067fdabdf..d3957245bc1 100644 --- a/core/src/main/java/org/elasticsearch/transport/local/LocalTransport.java +++ b/core/src/main/java/org/elasticsearch/transport/local/LocalTransport.java @@ -36,6 +36,7 @@ import org.elasticsearch.common.transport.LocalTransportAddress; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.common.util.concurrent.EsExecutors; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.ActionNotFoundTransportException; import org.elasticsearch.transport.ConnectTransportException; @@ -72,7 +73,7 @@ import static org.elasticsearch.common.util.concurrent.ConcurrentCollections.new public class LocalTransport extends AbstractLifecycleComponent implements Transport { public static final String LOCAL_TRANSPORT_THREAD_NAME_PREFIX = "local_transport"; - private final ThreadPool threadPool; + final ThreadPool threadPool; private final ThreadPoolExecutor workers; private final Version version; private volatile TransportServiceAdapter transportServiceAdapter; @@ -96,7 +97,7 @@ public class LocalTransport extends AbstractLifecycleComponent implem int queueSize = this.settings.getAsInt(TRANSPORT_LOCAL_QUEUE, -1); logger.debug("creating [{}] workers, queue_size [{}]", workerCount, queueSize); final ThreadFactory threadFactory = EsExecutors.daemonThreadFactory(this.settings, LOCAL_TRANSPORT_THREAD_NAME_PREFIX); - this.workers = EsExecutors.newFixed(LOCAL_TRANSPORT_THREAD_NAME_PREFIX, workerCount, queueSize, threadFactory); + this.workers = EsExecutors.newFixed(LOCAL_TRANSPORT_THREAD_NAME_PREFIX, workerCount, queueSize, threadFactory, threadPool.getThreadContext()); this.namedWriteableRegistry = namedWriteableRegistry; } @@ -209,6 +210,7 @@ public class LocalTransport extends AbstractLifecycleComponent implem status = TransportStatus.setRequest(status); stream.writeByte(status); // 0 for request, 1 for response. + threadPool.getThreadContext().writeTo(stream); stream.writeString(action); request.writeTo(stream); @@ -220,12 +222,11 @@ public class LocalTransport extends AbstractLifecycleComponent implem } final byte[] data = stream.bytes().toBytes(); - transportServiceAdapter.sent(data.length); transportServiceAdapter.onRequestSent(node, requestId, action, request, options); - targetTransport.workers().execute(new Runnable() { - @Override - public void run() { + targetTransport.workers().execute(() -> { + ThreadContext threadContext = threadPool.getThreadContext(); + try (ThreadContext.StoredContext context = threadContext.stashContext()) { targetTransport.messageReceived(data, action, LocalTransport.this, version, requestId); } }); @@ -246,8 +247,9 @@ public class LocalTransport extends AbstractLifecycleComponent implem long requestId = stream.readLong(); byte status = stream.readByte(); boolean isRequest = TransportStatus.isRequest(status); - if (isRequest) { + ThreadContext threadContext = threadPool.getThreadContext(); + threadContext.readHeaders(stream); handleRequest(stream, requestId, sourceTransport, version); } else { final TransportResponseHandler handler = transportServiceAdapter.onResponseReceived(requestId); @@ -322,6 +324,7 @@ public class LocalTransport extends AbstractLifecycleComponent implem logger.warn("Failed to send error message back to client for action [" + action + "]", e); logger.warn("Actual Exception", e1); } + } } @@ -338,15 +341,11 @@ public class LocalTransport extends AbstractLifecycleComponent implem } protected void handleParsedResponse(final TransportResponse response, final TransportResponseHandler handler) { - threadPool.executor(handler.executor()).execute(new Runnable() { - @SuppressWarnings({"unchecked"}) - @Override - public void run() { - try { - handler.handleResponse(response); - } catch (Throwable e) { - handleException(handler, new ResponseHandlerFailureTransportException(e)); - } + threadPool.executor(handler.executor()).execute(() -> { + try { + handler.handleResponse(response); + } catch (Throwable e) { + handleException(handler, new ResponseHandlerFailureTransportException(e)); } }); } 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 e1e85e9a12f..aad31fd8ccd 100644 --- a/core/src/main/java/org/elasticsearch/transport/local/LocalTransportChannel.java +++ b/core/src/main/java/org/elasticsearch/transport/local/LocalTransportChannel.java @@ -21,6 +21,7 @@ package org.elasticsearch.transport.local; import org.elasticsearch.Version; import org.elasticsearch.common.io.stream.BytesStreamOutput; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.transport.RemoteTransportException; import org.elasticsearch.transport.TransportChannel; import org.elasticsearch.transport.TransportResponse; @@ -79,9 +80,9 @@ public class LocalTransportChannel implements TransportChannel { stream.writeByte(status); // 0 for request, 1 for response. response.writeTo(stream); final byte[] data = stream.bytes().toBytes(); - targetTransport.workers().execute(new Runnable() { - @Override - public void run() { + targetTransport.workers().execute(() -> { + ThreadContext threadContext = targetTransport.threadPool.getThreadContext(); + try (ThreadContext.StoredContext ignore = threadContext.stashContext()){ targetTransport.messageReceived(data, action, sourceTransport, version, null); } }); @@ -97,9 +98,9 @@ public class LocalTransportChannel implements TransportChannel { stream.writeThrowable(tx); final byte[] data = stream.bytes().toBytes(); - targetTransport.workers().execute(new Runnable() { - @Override - public void run() { + targetTransport.workers().execute(() -> { + ThreadContext threadContext = targetTransport.threadPool.getThreadContext(); + try (ThreadContext.StoredContext ignore = threadContext.stashContext()){ targetTransport.messageReceived(data, action, sourceTransport, version, null); } }); diff --git a/core/src/main/java/org/elasticsearch/transport/netty/MessageChannelHandler.java b/core/src/main/java/org/elasticsearch/transport/netty/MessageChannelHandler.java index 8df17f73233..6732b26ddbb 100644 --- a/core/src/main/java/org/elasticsearch/transport/netty/MessageChannelHandler.java +++ b/core/src/main/java/org/elasticsearch/transport/netty/MessageChannelHandler.java @@ -30,6 +30,7 @@ import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.util.concurrent.AbstractRunnable; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.ActionNotFoundTransportException; import org.elasticsearch.transport.RemoteTransportException; @@ -64,9 +65,11 @@ public class MessageChannelHandler extends SimpleChannelUpstreamHandler { protected final TransportServiceAdapter transportServiceAdapter; protected final NettyTransport transport; protected final String profileName; + private final ThreadContext threadContext; public MessageChannelHandler(NettyTransport transport, ESLogger logger, String profileName) { this.threadPool = transport.threadPool(); + this.threadContext = threadPool.getThreadContext(); this.transportServiceAdapter = transport.transportServiceAdapter(); this.transport = transport; this.logger = logger; @@ -101,7 +104,7 @@ public class MessageChannelHandler extends SimpleChannelUpstreamHandler { // buffer, or in the cumlation buffer, which is cleaned each time StreamInput streamIn = ChannelBufferStreamInputFactory.create(buffer, size); boolean success = false; - try { + try (ThreadContext.StoredContext tCtx = threadContext.stashContext()) { long requestId = streamIn.readLong(); byte status = streamIn.readByte(); Version version = Version.fromId(streamIn.readInt()); @@ -123,8 +126,8 @@ public class MessageChannelHandler extends SimpleChannelUpstreamHandler { streamIn = compressor.streamInput(streamIn); } streamIn.setVersion(version); - if (TransportStatus.isRequest(status)) { + threadContext.readHeaders(streamIn); String action = handleRequest(ctx.getChannel(), streamIn, requestId, version); // Chek the entire message has been read 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 6a6a6c38011..856e45cb638 100644 --- a/core/src/main/java/org/elasticsearch/transport/netty/NettyTransport.java +++ b/core/src/main/java/org/elasticsearch/transport/netty/NettyTransport.java @@ -845,6 +845,7 @@ public class NettyTransport extends AbstractLifecycleComponent implem Version version = Version.smallest(this.version, node.version()); stream.setVersion(version); + threadPool.getThreadContext().writeTo(stream); stream.writeString(action); ReleasablePagedBytesReference bytes; 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 55c10aa298e..635af1e51ce 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 @@ -155,7 +155,7 @@ public class TransportTasksActionTests extends ESTestCase { } public NodeRequest(NodesRequest request, String nodeId) { - super(request, nodeId); + super(nodeId); requestName = request.requestName; enableTaskManager = request.enableTaskManager; } diff --git a/core/src/test/java/org/elasticsearch/client/AbstractClientHeadersTestCase.java b/core/src/test/java/org/elasticsearch/client/AbstractClientHeadersTestCase.java index b814cff520c..0ecfc58de7c 100644 --- a/core/src/test/java/org/elasticsearch/client/AbstractClientHeadersTestCase.java +++ b/core/src/test/java/org/elasticsearch/client/AbstractClientHeadersTestCase.java @@ -23,34 +23,21 @@ import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.GenericAction; import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteAction; -import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteResponse; import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotAction; -import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse; import org.elasticsearch.action.admin.cluster.stats.ClusterStatsAction; -import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse; import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheAction; -import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexAction; -import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.flush.FlushAction; -import org.elasticsearch.action.admin.indices.flush.FlushResponse; import org.elasticsearch.action.admin.indices.stats.IndicesStatsAction; -import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse; import org.elasticsearch.action.delete.DeleteAction; -import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetAction; -import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexAction; -import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.indexedscripts.delete.DeleteIndexedScriptAction; -import org.elasticsearch.action.indexedscripts.delete.DeleteIndexedScriptResponse; import org.elasticsearch.action.search.SearchAction; -import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.client.support.Headers; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.ThreadPool; -import org.elasticsearch.transport.TransportMessage; import org.junit.After; import org.junit.Before; @@ -67,8 +54,8 @@ import static org.hamcrest.Matchers.notNullValue; public abstract class AbstractClientHeadersTestCase extends ESTestCase { protected static final Settings HEADER_SETTINGS = Settings.builder() - .put(Headers.PREFIX + ".key1", "val1") - .put(Headers.PREFIX + ".key2", "val 2") + .put(ThreadContext.PREFIX + ".key1", "val1") + .put(ThreadContext.PREFIX + ".key2", "val 2") .build(); private static final GenericAction[] ACTIONS = new GenericAction[] { @@ -91,8 +78,9 @@ public abstract class AbstractClientHeadersTestCase extends ESTestCase { Settings settings = Settings.builder() .put(HEADER_SETTINGS) .put("path.home", createTempDir().toString()) + .put("name", "test-" + getTestName()) .build(); - threadPool = new ThreadPool("test-" + getTestName()); + threadPool = new ThreadPool(settings); client = buildClient(settings, ACTIONS); } @@ -113,89 +101,75 @@ public abstract class AbstractClientHeadersTestCase extends ESTestCase { // validation in the settings??? - ugly and conceptually wrong) // choosing arbitrary top level actions to test - client.prepareGet("idx", "type", "id").execute().addListener(new AssertingActionListener(GetAction.NAME)); - client.prepareSearch().execute().addListener(new AssertingActionListener(SearchAction.NAME)); - client.prepareDelete("idx", "type", "id").execute().addListener(new AssertingActionListener(DeleteAction.NAME)); - client.prepareDeleteIndexedScript("lang", "id").execute().addListener(new AssertingActionListener(DeleteIndexedScriptAction.NAME)); - client.prepareIndex("idx", "type", "id").setSource("source").execute().addListener(new AssertingActionListener(IndexAction.NAME)); + client.prepareGet("idx", "type", "id").execute().addListener(new AssertingActionListener<>(GetAction.NAME, client.threadPool())); + client.prepareSearch().execute().addListener(new AssertingActionListener<>(SearchAction.NAME, client.threadPool())); + client.prepareDelete("idx", "type", "id").execute().addListener(new AssertingActionListener<>(DeleteAction.NAME, client.threadPool())); + client.prepareDeleteIndexedScript("lang", "id").execute().addListener(new AssertingActionListener<>(DeleteIndexedScriptAction.NAME, client.threadPool())); + client.prepareIndex("idx", "type", "id").setSource("source").execute().addListener(new AssertingActionListener<>(IndexAction.NAME, client.threadPool())); // choosing arbitrary cluster admin actions to test - client.admin().cluster().prepareClusterStats().execute().addListener(new AssertingActionListener(ClusterStatsAction.NAME)); - client.admin().cluster().prepareCreateSnapshot("repo", "bck").execute().addListener(new AssertingActionListener(CreateSnapshotAction.NAME)); - client.admin().cluster().prepareReroute().execute().addListener(new AssertingActionListener(ClusterRerouteAction.NAME)); + client.admin().cluster().prepareClusterStats().execute().addListener(new AssertingActionListener<>(ClusterStatsAction.NAME, client.threadPool())); + client.admin().cluster().prepareCreateSnapshot("repo", "bck").execute().addListener(new AssertingActionListener<>(CreateSnapshotAction.NAME, client.threadPool())); + client.admin().cluster().prepareReroute().execute().addListener(new AssertingActionListener<>(ClusterRerouteAction.NAME, client.threadPool())); // choosing arbitrary indices admin actions to test - client.admin().indices().prepareCreate("idx").execute().addListener(new AssertingActionListener(CreateIndexAction.NAME)); - client.admin().indices().prepareStats().execute().addListener(new AssertingActionListener(IndicesStatsAction.NAME)); - client.admin().indices().prepareClearCache("idx1", "idx2").execute().addListener(new AssertingActionListener(ClearIndicesCacheAction.NAME)); - client.admin().indices().prepareFlush().execute().addListener(new AssertingActionListener(FlushAction.NAME)); + client.admin().indices().prepareCreate("idx").execute().addListener(new AssertingActionListener<>(CreateIndexAction.NAME, client.threadPool())); + client.admin().indices().prepareStats().execute().addListener(new AssertingActionListener<>(IndicesStatsAction.NAME, client.threadPool())); + client.admin().indices().prepareClearCache("idx1", "idx2").execute().addListener(new AssertingActionListener<>(ClearIndicesCacheAction.NAME, client.threadPool())); + client.admin().indices().prepareFlush().execute().addListener(new AssertingActionListener<>(FlushAction.NAME, client.threadPool())); } public void testOverideHeader() throws Exception { String key1Val = randomAsciiOfLength(5); - Map expected = new HashMap<>(); + Map expected = new HashMap<>(); expected.put("key1", key1Val); expected.put("key2", "val 2"); - + client.threadPool().getThreadContext().putHeader("key1", key1Val); client.prepareGet("idx", "type", "id") - .putHeader("key1", key1Val) - .execute().addListener(new AssertingActionListener(GetAction.NAME, expected)); + .execute().addListener(new AssertingActionListener<>(GetAction.NAME, expected, client.threadPool())); client.admin().cluster().prepareClusterStats() - .putHeader("key1", key1Val) - .execute().addListener(new AssertingActionListener(ClusterStatsAction.NAME, expected)); + .execute().addListener(new AssertingActionListener<>(ClusterStatsAction.NAME, expected, client.threadPool())); client.admin().indices().prepareCreate("idx") - .putHeader("key1", key1Val) - .execute().addListener(new AssertingActionListener(CreateIndexAction.NAME, expected)); + .execute().addListener(new AssertingActionListener<>(CreateIndexAction.NAME, expected, client.threadPool())); } - protected static void assertHeaders(Map headers, Map expected) { - assertThat(headers, notNullValue()); - assertThat(headers.size(), is(expected.size())); - for (Map.Entry expectedEntry : expected.entrySet()) { - assertThat(headers.get(expectedEntry.getKey()), equalTo(expectedEntry.getValue())); + protected static void assertHeaders(Map headers, Map expected) { + assertNotNull(headers); + assertEquals(expected.size(), headers.size()); + for (Map.Entry expectedEntry : expected.entrySet()) { + assertEquals(headers.get(expectedEntry.getKey()), expectedEntry.getValue()); } } - protected static void assertHeaders(TransportMessage message) { - assertHeaders(message, HEADER_SETTINGS.getAsSettings(Headers.PREFIX).getAsStructuredMap()); - } - - protected static void assertHeaders(TransportMessage message, Map expected) { - assertThat(message.getHeaders(), notNullValue()); - assertThat(message.getHeaders().size(), is(expected.size())); - for (Map.Entry expectedEntry : expected.entrySet()) { - assertThat(message.getHeader(expectedEntry.getKey()), equalTo(expectedEntry.getValue())); - } + protected static void assertHeaders(ThreadPool pool) { + assertHeaders(pool.getThreadContext().getHeaders(), (Map)HEADER_SETTINGS.getAsSettings(ThreadContext.PREFIX).getAsStructuredMap()); } public static class InternalException extends Exception { private final String action; - private final Map headers; - public InternalException(String action, TransportMessage message) { + public InternalException(String action) { this.action = action; - this.headers = new HashMap<>(); - for (String key : message.getHeaders()) { - headers.put(key, message.getHeader(key)); - } } } protected static class AssertingActionListener implements ActionListener { private final String action; - private final Map expectedHeaders; + private final Map expectedHeaders; + private final ThreadPool pool; - public AssertingActionListener(String action) { - this(action, HEADER_SETTINGS.getAsSettings(Headers.PREFIX).getAsStructuredMap()); + public AssertingActionListener(String action, ThreadPool pool) { + this(action, (Map)HEADER_SETTINGS.getAsSettings(ThreadContext.PREFIX).getAsStructuredMap(), pool); } - public AssertingActionListener(String action, Map expectedHeaders) { + public AssertingActionListener(String action, Map expectedHeaders, ThreadPool pool) { this.action = action; this.expectedHeaders = expectedHeaders; + this.pool = pool; } @Override @@ -208,7 +182,7 @@ public abstract class AbstractClientHeadersTestCase extends ESTestCase { Throwable e = unwrap(t, InternalException.class); assertThat("expected action [" + action + "] to throw an internal exception", e, notNullValue()); assertThat(action, equalTo(((InternalException) e).action)); - Map headers = ((InternalException) e).headers; + Map headers = pool.getThreadContext().getHeaders(); assertHeaders(headers, expectedHeaders); } diff --git a/core/src/test/java/org/elasticsearch/client/node/NodeClientHeadersTests.java b/core/src/test/java/org/elasticsearch/client/node/NodeClientHeadersTests.java index e7ba8de0f97..f69c8f2da0b 100644 --- a/core/src/test/java/org/elasticsearch/client/node/NodeClientHeadersTests.java +++ b/core/src/test/java/org/elasticsearch/client/node/NodeClientHeadersTests.java @@ -27,7 +27,6 @@ import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.TransportAction; import org.elasticsearch.client.AbstractClientHeadersTestCase; import org.elasticsearch.client.Client; -import org.elasticsearch.client.support.Headers; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.tasks.Task; import org.elasticsearch.tasks.TaskManager; @@ -46,9 +45,8 @@ public class NodeClientHeadersTests extends AbstractClientHeadersTestCase { @Override protected Client buildClient(Settings headersSettings, GenericAction[] testedActions) { Settings settings = HEADER_SETTINGS; - Headers headers = new Headers(settings); Actions actions = new Actions(settings, threadPool, testedActions); - return new NodeClient(settings, threadPool, headers, actions); + return new NodeClient(settings, threadPool, actions); } private static class Actions extends HashMap { @@ -68,7 +66,7 @@ public class NodeClientHeadersTests extends AbstractClientHeadersTestCase { @Override protected void doExecute(ActionRequest request, ActionListener listener) { - listener.onFailure(new InternalException(actionName, request)); + listener.onFailure(new InternalException(actionName)); } } diff --git a/core/src/test/java/org/elasticsearch/client/transport/TransportClientHeadersTests.java b/core/src/test/java/org/elasticsearch/client/transport/TransportClientHeadersTests.java index f127ae28378..c364e640a24 100644 --- a/core/src/test/java/org/elasticsearch/client/transport/TransportClientHeadersTests.java +++ b/core/src/test/java/org/elasticsearch/client/transport/TransportClientHeadersTests.java @@ -134,30 +134,30 @@ public class TransportClientHeadersTests extends AbstractClientHeadersTestCase { @Override @SuppressWarnings("unchecked") public void sendRequest(DiscoveryNode node, String action, TransportRequest request, TransportRequestOptions options, TransportResponseHandler handler) { if (TransportLivenessAction.NAME.equals(action)) { - assertHeaders(request); + assertHeaders(threadPool); ((TransportResponseHandler) handler).handleResponse(new LivenessResponse(ClusterName.DEFAULT, node)); return; } if (ClusterStateAction.NAME.equals(action)) { - assertHeaders(request); + assertHeaders(threadPool); ClusterName cluster1 = new ClusterName("cluster1"); ((TransportResponseHandler) handler).handleResponse(new ClusterStateResponse(cluster1, state(cluster1))); clusterStateLatch.countDown(); return; } - handler.handleException(new TransportException("", new InternalException(action, request))); + handler.handleException(new TransportException("", new InternalException(action))); } @Override public boolean nodeConnected(DiscoveryNode node) { - assertThat((LocalTransportAddress) node.getAddress(), equalTo(address)); + assertThat(node.getAddress(), equalTo(address)); return true; } @Override public void connectToNode(DiscoveryNode node) throws ConnectTransportException { - assertThat((LocalTransportAddress) node.getAddress(), equalTo(address)); + assertThat(node.getAddress(), equalTo(address)); } } 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 72ace64d9ee..e6ea0410a55 100644 --- a/core/src/test/java/org/elasticsearch/client/transport/TransportClientNodesServiceTests.java +++ b/core/src/test/java/org/elasticsearch/client/transport/TransportClientNodesServiceTests.java @@ -21,7 +21,6 @@ package org.elasticsearch.client.transport; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; -import org.elasticsearch.client.support.Headers; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.settings.Settings; @@ -74,7 +73,7 @@ public class TransportClientNodesServiceTests extends ESTestCase { }; transportService = new TransportService(Settings.EMPTY, transport, threadPool); transportService.start(); - transportClientNodesService = new TransportClientNodesService(Settings.EMPTY, ClusterName.DEFAULT, transportService, threadPool, Headers.EMPTY, Version.CURRENT); + transportClientNodesService = new TransportClientNodesService(Settings.EMPTY, ClusterName.DEFAULT, transportService, threadPool, Version.CURRENT); nodesCount = randomIntBetween(1, 10); for (int i = 0; i < nodesCount; i++) { diff --git a/core/src/test/java/org/elasticsearch/common/network/NetworkModuleTests.java b/core/src/test/java/org/elasticsearch/common/network/NetworkModuleTests.java index 798e82a979e..c181d893568 100644 --- a/core/src/test/java/org/elasticsearch/common/network/NetworkModuleTests.java +++ b/core/src/test/java/org/elasticsearch/common/network/NetworkModuleTests.java @@ -82,7 +82,7 @@ public class NetworkModuleTests extends ModuleTestCase { static class FakeRestHandler extends BaseRestHandler { public FakeRestHandler() { - super(null, null, null); + super(null, null); } @Override protected void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception {} 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 b59c8dd1cb6..fabfc6a94e5 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 @@ -20,6 +20,7 @@ package org.elasticsearch.common.util.concurrent; import org.elasticsearch.ExceptionsHelper; +import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ESTestCase; import org.hamcrest.Matcher; @@ -38,12 +39,13 @@ import static org.hamcrest.Matchers.lessThan; */ public class EsExecutorsTests extends ESTestCase { + private final ThreadContext threadContext = new ThreadContext(Settings.EMPTY); private TimeUnit randomTimeUnit() { return TimeUnit.values()[between(0, TimeUnit.values().length - 1)]; } public void testFixedForcedExecution() throws Exception { - EsThreadPoolExecutor executor = EsExecutors.newFixed(getTestName(), 1, 1, EsExecutors.daemonThreadFactory("test")); + EsThreadPoolExecutor executor = EsExecutors.newFixed(getTestName(), 1, 1, EsExecutors.daemonThreadFactory("test"), threadContext); final CountDownLatch wait = new CountDownLatch(1); final CountDownLatch exec1Wait = new CountDownLatch(1); @@ -105,7 +107,7 @@ public class EsExecutorsTests extends ESTestCase { } public void testFixedRejected() throws Exception { - EsThreadPoolExecutor executor = EsExecutors.newFixed(getTestName(), 1, 1, EsExecutors.daemonThreadFactory("test")); + EsThreadPoolExecutor executor = EsExecutors.newFixed(getTestName(), 1, 1, EsExecutors.daemonThreadFactory("test"), threadContext); final CountDownLatch wait = new CountDownLatch(1); final CountDownLatch exec1Wait = new CountDownLatch(1); @@ -163,7 +165,7 @@ public class EsExecutorsTests extends ESTestCase { final int max = between(min + 1, 6); final ThreadBarrier barrier = new ThreadBarrier(max + 1); - ThreadPoolExecutor pool = EsExecutors.newScaling(getTestName(), min, max, between(1, 100), randomTimeUnit(), EsExecutors.daemonThreadFactory("test")); + ThreadPoolExecutor pool = EsExecutors.newScaling(getTestName(), min, max, between(1, 100), randomTimeUnit(), EsExecutors.daemonThreadFactory("test"), threadContext); assertThat("Min property", pool.getCorePoolSize(), equalTo(min)); assertThat("Max property", pool.getMaximumPoolSize(), equalTo(max)); @@ -199,7 +201,7 @@ public class EsExecutorsTests extends ESTestCase { final int max = between(min + 1, 6); final ThreadBarrier barrier = new ThreadBarrier(max + 1); - final ThreadPoolExecutor pool = EsExecutors.newScaling(getTestName(), min, max, between(1, 100), TimeUnit.MILLISECONDS, EsExecutors.daemonThreadFactory("test")); + final ThreadPoolExecutor pool = EsExecutors.newScaling(getTestName(), min, max, between(1, 100), TimeUnit.MILLISECONDS, EsExecutors.daemonThreadFactory("test"), threadContext); assertThat("Min property", pool.getCorePoolSize(), equalTo(min)); assertThat("Max property", pool.getMaximumPoolSize(), equalTo(max)); @@ -242,7 +244,7 @@ public class EsExecutorsTests extends ESTestCase { int queue = between(0, 100); int actions = queue + pool; final CountDownLatch latch = new CountDownLatch(1); - EsThreadPoolExecutor executor = EsExecutors.newFixed(getTestName(), pool, queue, EsExecutors.daemonThreadFactory("dummy")); + EsThreadPoolExecutor executor = EsExecutors.newFixed(getTestName(), pool, queue, EsExecutors.daemonThreadFactory("dummy"), threadContext); try { for (int i = 0; i < actions; i++) { executor.execute(new Runnable() { @@ -321,4 +323,42 @@ public class EsExecutorsTests extends ESTestCase { assertThat(message, containsString("completed tasks = " + actions)); } } + + public void testInheritContext() throws InterruptedException { + int pool = between(1, 10); + int queue = between(0, 100); + final CountDownLatch latch = new CountDownLatch(1); + final CountDownLatch executed = new CountDownLatch(1); + + threadContext.putHeader("foo", "bar"); + final Integer one = new Integer(1); + threadContext.putTransient("foo", one); + EsThreadPoolExecutor executor = EsExecutors.newFixed(getTestName(), pool, queue, EsExecutors.daemonThreadFactory("dummy"), threadContext); + try { + executor.execute(new Runnable() { + @Override + public void run() { + try { + latch.await(); + } catch (InterruptedException e) { + fail(); + } + assertEquals(threadContext.getHeader("foo"), "bar"); + assertSame(threadContext.getTransient("foo"), one); + assertNull(threadContext.getHeader("bar")); + assertNull(threadContext.getTransient("bar")); + executed.countDown(); + } + }); + threadContext.putTransient("bar", "boom"); + threadContext.putHeader("bar", "boom"); + latch.countDown(); + executed.await(); + + } finally { + latch.countDown(); + terminate(executor); + } + + } } diff --git a/core/src/test/java/org/elasticsearch/common/util/concurrent/PrioritizedExecutorsTests.java b/core/src/test/java/org/elasticsearch/common/util/concurrent/PrioritizedExecutorsTests.java index 685e06afb16..50b7d5f775c 100644 --- a/core/src/test/java/org/elasticsearch/common/util/concurrent/PrioritizedExecutorsTests.java +++ b/core/src/test/java/org/elasticsearch/common/util/concurrent/PrioritizedExecutorsTests.java @@ -19,6 +19,7 @@ package org.elasticsearch.common.util.concurrent; import org.elasticsearch.common.Priority; +import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.ThreadPool; @@ -43,6 +44,9 @@ import static org.hamcrest.Matchers.is; * */ public class PrioritizedExecutorsTests extends ESTestCase { + + private final ThreadContext holder = new ThreadContext(Settings.EMPTY); + public void testPriorityQueue() throws Exception { PriorityBlockingQueue queue = new PriorityBlockingQueue<>(); List priorities = Arrays.asList(Priority.values()); @@ -63,7 +67,7 @@ public class PrioritizedExecutorsTests extends ESTestCase { } public void testSubmitPrioritizedExecutorWithRunnables() throws Exception { - ExecutorService executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName())); + ExecutorService executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName()), holder); List results = new ArrayList<>(8); CountDownLatch awaitingLatch = new CountDownLatch(1); CountDownLatch finishedLatch = new CountDownLatch(8); @@ -92,7 +96,7 @@ public class PrioritizedExecutorsTests extends ESTestCase { } public void testExecutePrioritizedExecutorWithRunnables() throws Exception { - ExecutorService executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName())); + ExecutorService executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName()), holder); List results = new ArrayList<>(8); CountDownLatch awaitingLatch = new CountDownLatch(1); CountDownLatch finishedLatch = new CountDownLatch(8); @@ -121,7 +125,7 @@ public class PrioritizedExecutorsTests extends ESTestCase { } public void testSubmitPrioritizedExecutorWithCallables() throws Exception { - ExecutorService executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName())); + ExecutorService executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName()), holder); List results = new ArrayList<>(8); CountDownLatch awaitingLatch = new CountDownLatch(1); CountDownLatch finishedLatch = new CountDownLatch(8); @@ -150,7 +154,7 @@ public class PrioritizedExecutorsTests extends ESTestCase { } public void testSubmitPrioritizedExecutorWithMixed() throws Exception { - ExecutorService executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName())); + ExecutorService executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName()), holder); List results = new ArrayList<>(8); CountDownLatch awaitingLatch = new CountDownLatch(1); CountDownLatch finishedLatch = new CountDownLatch(8); @@ -180,7 +184,7 @@ public class PrioritizedExecutorsTests extends ESTestCase { public void testTimeout() throws Exception { ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(EsExecutors.daemonThreadFactory(getTestName())); - PrioritizedEsThreadPoolExecutor executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName())); + PrioritizedEsThreadPoolExecutor executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName()), holder); final CountDownLatch invoked = new CountDownLatch(1); final CountDownLatch block = new CountDownLatch(1); executor.execute(new Runnable() { @@ -243,7 +247,7 @@ public class PrioritizedExecutorsTests extends ESTestCase { ThreadPool threadPool = new ThreadPool("test"); final ScheduledThreadPoolExecutor timer = (ScheduledThreadPoolExecutor) threadPool.scheduler(); final AtomicBoolean timeoutCalled = new AtomicBoolean(); - PrioritizedEsThreadPoolExecutor executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName())); + PrioritizedEsThreadPoolExecutor executor = EsExecutors.newSinglePrioritizing(getTestName(), EsExecutors.daemonThreadFactory(getTestName()), holder); final CountDownLatch invoked = new CountDownLatch(1); executor.execute(new Runnable() { @Override 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 new file mode 100644 index 00000000000..bbe5136f57a --- /dev/null +++ b/core/src/test/java/org/elasticsearch/common/util/concurrent/ThreadContextTests.java @@ -0,0 +1,138 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.elasticsearch.common.util.concurrent; + +import org.elasticsearch.common.io.stream.BytesStreamOutput; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.test.ESTestCase; + +import java.io.IOException; +import java.util.Collections; + +public class ThreadContextTests extends ESTestCase { + + public void testStashContext() { + Settings build = Settings.builder().put("request.headers.default", "1").build(); + ThreadContext threadContext = new ThreadContext(build); + threadContext.putHeader("foo", "bar"); + threadContext.putTransient("ctx.foo", new Integer(1)); + assertEquals("bar", threadContext.getHeader("foo")); + assertEquals(new Integer(1), threadContext.getTransient("ctx.foo")); + assertEquals("1", threadContext.getHeader("default")); + try (ThreadContext.StoredContext ctx = threadContext.stashContext()) { + assertNull(threadContext.getHeader("foo")); + assertNull(threadContext.getTransient("ctx.foo")); + assertEquals("1", threadContext.getHeader("default")); + } + + assertEquals("bar", threadContext.getHeader("foo")); + assertEquals(new Integer(1), threadContext.getTransient("ctx.foo")); + assertEquals("1", threadContext.getHeader("default")); + } + + public void testStoreContext() { + Settings build = Settings.builder().put("request.headers.default", "1").build(); + ThreadContext threadContext = new ThreadContext(build); + threadContext.putHeader("foo", "bar"); + threadContext.putTransient("ctx.foo", new Integer(1)); + assertEquals("bar", threadContext.getHeader("foo")); + assertEquals(new Integer(1), threadContext.getTransient("ctx.foo")); + assertEquals("1", threadContext.getHeader("default")); + ThreadContext.StoredContext storedContext = threadContext.newStoredContext(); + threadContext.putHeader("foo.bar", "baz"); + try (ThreadContext.StoredContext ctx = threadContext.stashContext()) { + assertNull(threadContext.getHeader("foo")); + assertNull(threadContext.getTransient("ctx.foo")); + assertEquals("1", threadContext.getHeader("default")); + } + + assertEquals("bar", threadContext.getHeader("foo")); + assertEquals(new Integer(1), threadContext.getTransient("ctx.foo")); + assertEquals("1", threadContext.getHeader("default")); + assertEquals("baz", threadContext.getHeader("foo.bar")); + if (randomBoolean()) { + storedContext.restore(); + } else { + storedContext.close(); + } + assertEquals("bar", threadContext.getHeader("foo")); + assertEquals(new Integer(1), threadContext.getTransient("ctx.foo")); + assertEquals("1", threadContext.getHeader("default")); + assertNull(threadContext.getHeader("foo.bar")); + } + + public void testCopyHeaders() { + Settings build = Settings.builder().put("request.headers.default", "1").build(); + ThreadContext threadContext = new ThreadContext(build); + threadContext.copyHeaders(Collections.emptyMap().entrySet()); + threadContext.copyHeaders(Collections.singletonMap("foo", "bar").entrySet()); + assertEquals("bar", threadContext.getHeader("foo")); + } + + public void testAccessClosed() throws IOException { + Settings build = Settings.builder().put("request.headers.default", "1").build(); + ThreadContext threadContext = new ThreadContext(build); + threadContext.putHeader("foo", "bar"); + threadContext.putTransient("ctx.foo", new Integer(1)); + + threadContext.close(); + try { + threadContext.getHeader("foo"); + fail(); + } catch (IllegalStateException ise) { + assertEquals("threadcontext is already closed", ise.getMessage()); + } + + try { + threadContext.putTransient("foo", new Object()); + fail(); + } catch (IllegalStateException ise) { + assertEquals("threadcontext is already closed", ise.getMessage()); + } + + try { + threadContext.putHeader("boom", "boom"); + fail(); + } catch (IllegalStateException ise) { + assertEquals("threadcontext is already closed", ise.getMessage()); + } + } + + public void testSerialize() throws IOException { + Settings build = Settings.builder().put("request.headers.default", "1").build(); + ThreadContext threadContext = new ThreadContext(build); + threadContext.putHeader("foo", "bar"); + threadContext.putTransient("ctx.foo", new Integer(1)); + BytesStreamOutput out = new BytesStreamOutput(); + threadContext.writeTo(out); + try (ThreadContext.StoredContext ctx = threadContext.stashContext()) { + assertNull(threadContext.getHeader("foo")); + assertNull(threadContext.getTransient("ctx.foo")); + assertEquals("1", threadContext.getHeader("default")); + + threadContext.readHeaders(StreamInput.wrap(out.bytes())); + assertEquals("bar", threadContext.getHeader("foo")); + assertNull(threadContext.getTransient("ctx.foo")); + } + assertEquals("bar", threadContext.getHeader("foo")); + assertEquals(new Integer(1), threadContext.getTransient("ctx.foo")); + assertEquals("1", threadContext.getHeader("default")); + } +} diff --git a/core/src/test/java/org/elasticsearch/http/netty/NettyHttpChannelTests.java b/core/src/test/java/org/elasticsearch/http/netty/NettyHttpChannelTests.java index cb111a71988..179d1d13295 100644 --- a/core/src/test/java/org/elasticsearch/http/netty/NettyHttpChannelTests.java +++ b/core/src/test/java/org/elasticsearch/http/netty/NettyHttpChannelTests.java @@ -83,7 +83,7 @@ public class NettyHttpChannelTests extends ESTestCase { Settings settings = Settings.builder() .put(NettyHttpServerTransport.SETTING_CORS_ENABLED, true) .build(); - httpServerTransport = new NettyHttpServerTransport(settings, networkService, bigArrays); + httpServerTransport = new NettyHttpServerTransport(settings, networkService, bigArrays, threadPool); HttpRequest httpRequest = new TestHttpRequest(); httpRequest.headers().add(HttpHeaders.Names.ORIGIN, "remote"); httpRequest.headers().add(HttpHeaders.Names.USER_AGENT, "Mozilla fake"); @@ -107,7 +107,7 @@ public class NettyHttpChannelTests extends ESTestCase { .put(NettyHttpServerTransport.SETTING_CORS_ENABLED, true) .put(NettyHttpServerTransport.SETTING_CORS_ALLOW_ORIGIN, "remote-host") .build(); - httpServerTransport = new NettyHttpServerTransport(settings, networkService, bigArrays); + httpServerTransport = new NettyHttpServerTransport(settings, networkService, bigArrays, threadPool); HttpRequest httpRequest = new TestHttpRequest(); httpRequest.headers().add(HttpHeaders.Names.ORIGIN, "remote"); httpRequest.headers().add(HttpHeaders.Names.USER_AGENT, "Mozilla fake"); diff --git a/core/src/test/java/org/elasticsearch/http/netty/NettyHttpServerPipeliningTests.java b/core/src/test/java/org/elasticsearch/http/netty/NettyHttpServerPipeliningTests.java index 95cb5b46b5f..6afe8a0aefc 100644 --- a/core/src/test/java/org/elasticsearch/http/netty/NettyHttpServerPipeliningTests.java +++ b/core/src/test/java/org/elasticsearch/http/netty/NettyHttpServerPipeliningTests.java @@ -23,6 +23,7 @@ import org.elasticsearch.common.network.NetworkService; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.util.MockBigArrays; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.http.netty.NettyHttpServerTransport.HttpChannelPipelineFactory; import org.elasticsearch.http.netty.pipelining.OrderedDownstreamChannelEvent; @@ -132,13 +133,13 @@ public class NettyHttpServerPipeliningTests extends ESTestCase { private final ExecutorService executorService; public CustomNettyHttpServerTransport(Settings settings) { - super(settings, NettyHttpServerPipeliningTests.this.networkService, NettyHttpServerPipeliningTests.this.bigArrays); + super(settings, NettyHttpServerPipeliningTests.this.networkService, NettyHttpServerPipeliningTests.this.bigArrays, NettyHttpServerPipeliningTests.this.threadPool); this.executorService = Executors.newFixedThreadPool(5); } @Override public ChannelPipelineFactory configureServerChannelPipelineFactory() { - return new CustomHttpChannelPipelineFactory(this, executorService); + return new CustomHttpChannelPipelineFactory(this, executorService, NettyHttpServerPipeliningTests.this.threadPool.getThreadContext()); } @Override @@ -152,8 +153,8 @@ public class NettyHttpServerPipeliningTests extends ESTestCase { private final ExecutorService executorService; - public CustomHttpChannelPipelineFactory(NettyHttpServerTransport transport, ExecutorService executorService) { - super(transport, randomBoolean()); + public CustomHttpChannelPipelineFactory(NettyHttpServerTransport transport, ExecutorService executorService, ThreadContext threadContext) { + super(transport, randomBoolean(), threadContext); this.executorService = executorService; } diff --git a/core/src/test/java/org/elasticsearch/indices/store/IndicesStoreTests.java b/core/src/test/java/org/elasticsearch/indices/store/IndicesStoreTests.java index ec6a3b38491..a7b08be39d9 100644 --- a/core/src/test/java/org/elasticsearch/indices/store/IndicesStoreTests.java +++ b/core/src/test/java/org/elasticsearch/indices/store/IndicesStoreTests.java @@ -30,9 +30,12 @@ import org.elasticsearch.cluster.routing.IndexShardRoutingTable; import org.elasticsearch.cluster.routing.ShardRoutingState; import org.elasticsearch.cluster.routing.TestShardRouting; import org.elasticsearch.cluster.routing.UnassignedInfo; +import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.LocalTransportAddress; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.test.cluster.TestClusterService; +import org.elasticsearch.transport.TransportService; import org.junit.Before; import java.util.Arrays; @@ -60,7 +63,7 @@ public class IndicesStoreTests extends ESTestCase { @Before public void before() { localNode = new DiscoveryNode("abc", new LocalTransportAddress("abc"), Version.CURRENT); - indicesStore = new IndicesStore(); + indicesStore = new IndicesStore(Settings.EMPTY, null, new TestClusterService(), new TransportService(null, null), null); } public void testShardCanBeDeletedNoShardRouting() throws Exception { diff --git a/core/src/test/java/org/elasticsearch/indices/template/IndexTemplateFilteringIT.java b/core/src/test/java/org/elasticsearch/indices/template/IndexTemplateFilteringIT.java index ee0f8748083..8e0d5a882c3 100644 --- a/core/src/test/java/org/elasticsearch/indices/template/IndexTemplateFilteringIT.java +++ b/core/src/test/java/org/elasticsearch/indices/template/IndexTemplateFilteringIT.java @@ -57,7 +57,7 @@ public class IndexTemplateFilteringIT extends ESIntegTestCase { .setTemplate("no_match") .addMapping("type3", "field3", "type=string").get(); - assertAcked(prepareCreate("test").putHeader("header_test", "header_value")); + assertAcked(prepareCreate("test")); GetMappingsResponse response = client().admin().indices().prepareGetMappings("test").get(); assertThat(response, notNullValue()); @@ -70,7 +70,7 @@ public class IndexTemplateFilteringIT extends ESIntegTestCase { @Override public boolean apply(CreateIndexClusterStateUpdateRequest request, IndexTemplateMetaData template) { //make sure that no_match template is filtered out before the custom filters as it doesn't match the index name - return (template.name().equals("template2") || template.name().equals("no_match")) && request.originalMessage().getHeader("header_test").equals("header_value"); + return (template.name().equals("template2") || template.name().equals("no_match")); } } diff --git a/core/src/test/java/org/elasticsearch/plugins/responseheader/TestResponseHeaderRestAction.java b/core/src/test/java/org/elasticsearch/plugins/responseheader/TestResponseHeaderRestAction.java index 4b1645a4ec6..39432bd01ea 100644 --- a/core/src/test/java/org/elasticsearch/plugins/responseheader/TestResponseHeaderRestAction.java +++ b/core/src/test/java/org/elasticsearch/plugins/responseheader/TestResponseHeaderRestAction.java @@ -33,7 +33,7 @@ public class TestResponseHeaderRestAction extends BaseRestHandler { @Inject public TestResponseHeaderRestAction(Settings settings, RestController controller, Client client) { - super(settings, controller, client); + super(settings, client); controller.registerHandler(RestRequest.Method.GET, "/_protected", this); } diff --git a/core/src/test/java/org/elasticsearch/rest/HeadersAndContextCopyClientTests.java b/core/src/test/java/org/elasticsearch/rest/HeadersAndContextCopyClientTests.java deleted file mode 100644 index 238e16d4b44..00000000000 --- a/core/src/test/java/org/elasticsearch/rest/HeadersAndContextCopyClientTests.java +++ /dev/null @@ -1,425 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.rest; - -import org.elasticsearch.action.ActionRequest; -import org.elasticsearch.action.ActionRequestBuilder; -import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; -import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest; -import org.elasticsearch.action.admin.cluster.stats.ClusterStatsRequest; -import org.elasticsearch.action.admin.indices.close.CloseIndexRequest; -import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; -import org.elasticsearch.action.admin.indices.flush.FlushRequest; -import org.elasticsearch.action.get.GetRequest; -import org.elasticsearch.action.index.IndexRequest; -import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.client.Client; -import org.elasticsearch.client.Requests; -import org.elasticsearch.common.collect.ImmutableOpenMap; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.test.ESTestCase; -import org.elasticsearch.test.rest.FakeRestRequest; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.Matchers.is; - -public class HeadersAndContextCopyClientTests extends ESTestCase { - - public void testRegisterRelevantHeaders() throws InterruptedException { - - final RestController restController = new RestController(Settings.EMPTY); - - int iterations = randomIntBetween(1, 5); - - Set headers = new HashSet<>(); - ExecutorService executorService = Executors.newFixedThreadPool(iterations); - for (int i = 0; i < iterations; i++) { - int headersCount = randomInt(10); - final Set newHeaders = new HashSet<>(); - for (int j = 0; j < headersCount; j++) { - String usefulHeader = randomRealisticUnicodeOfLengthBetween(1, 30); - newHeaders.add(usefulHeader); - } - headers.addAll(newHeaders); - - executorService.submit(new Runnable() { - @Override - public void run() { - restController.registerRelevantHeaders(newHeaders.toArray(new String[newHeaders.size()])); - } - }); - } - - executorService.shutdown(); - assertThat(executorService.awaitTermination(1, TimeUnit.SECONDS), equalTo(true)); - String[] relevantHeaders = restController.relevantHeaders().toArray(new String[restController.relevantHeaders().size()]); - assertThat(relevantHeaders.length, equalTo(headers.size())); - - Arrays.sort(relevantHeaders); - String[] headersArray = new String[headers.size()]; - headersArray = headers.toArray(headersArray); - Arrays.sort(headersArray); - assertThat(relevantHeaders, equalTo(headersArray)); - } - - public void testCopyHeadersRequest() { - Map transportHeaders = randomHeaders(randomIntBetween(0, 10)); - Map restHeaders = randomHeaders(randomIntBetween(0, 10)); - Map copiedHeaders = randomHeadersFrom(restHeaders); - Set usefulRestHeaders = new HashSet<>(copiedHeaders.keySet()); - usefulRestHeaders.addAll(randomMap(randomIntBetween(0, 10), "useful-").keySet()); - Map restContext = randomContext(randomIntBetween(0, 10)); - Map transportContext = onlyOnLeft(randomContext(randomIntBetween(0, 10)), restContext); - - Map expectedHeaders = new HashMap<>(); - expectedHeaders.putAll(transportHeaders); - expectedHeaders.putAll(copiedHeaders); - - Map expectedContext = new HashMap<>(); - expectedContext.putAll(transportContext); - expectedContext.putAll(restContext); - - try (Client client = client(new NoOpClient(getTestName()), new FakeRestRequest(restHeaders, restContext), usefulRestHeaders)) { - - SearchRequest searchRequest = Requests.searchRequest(); - putHeaders(searchRequest, transportHeaders); - putContext(searchRequest, transportContext); - assertHeaders(searchRequest, transportHeaders); - client.search(searchRequest); - assertHeaders(searchRequest, expectedHeaders); - assertContext(searchRequest, expectedContext); - - GetRequest getRequest = Requests.getRequest("index"); - putHeaders(getRequest, transportHeaders); - putContext(getRequest, transportContext); - assertHeaders(getRequest, transportHeaders); - client.get(getRequest); - assertHeaders(getRequest, expectedHeaders); - assertContext(getRequest, expectedContext); - - IndexRequest indexRequest = Requests.indexRequest(); - putHeaders(indexRequest, transportHeaders); - putContext(indexRequest, transportContext); - assertHeaders(indexRequest, transportHeaders); - client.index(indexRequest); - assertHeaders(indexRequest, expectedHeaders); - assertContext(indexRequest, expectedContext); - } - } - - public void testCopyHeadersClusterAdminRequest() { - Map transportHeaders = randomHeaders(randomIntBetween(0, 10)); - Map restHeaders = randomHeaders(randomIntBetween(0, 10)); - Map copiedHeaders = randomHeadersFrom(restHeaders); - Set usefulRestHeaders = new HashSet<>(copiedHeaders.keySet()); - usefulRestHeaders.addAll(randomMap(randomIntBetween(0, 10), "useful-").keySet()); - Map restContext = randomContext(randomIntBetween(0, 10)); - Map transportContext = onlyOnLeft(randomContext(randomIntBetween(0, 10)), restContext); - - HashMap expectedHeaders = new HashMap<>(); - expectedHeaders.putAll(transportHeaders); - expectedHeaders.putAll(copiedHeaders); - - Map expectedContext = new HashMap<>(); - expectedContext.putAll(transportContext); - expectedContext.putAll(restContext); - - try (Client client = client(new NoOpClient(getTestName()), new FakeRestRequest(restHeaders, expectedContext), usefulRestHeaders)) { - - ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest(); - putHeaders(clusterHealthRequest, transportHeaders); - putContext(clusterHealthRequest, transportContext); - assertHeaders(clusterHealthRequest, transportHeaders); - client.admin().cluster().health(clusterHealthRequest); - assertHeaders(clusterHealthRequest, expectedHeaders); - assertContext(clusterHealthRequest, expectedContext); - - ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest(); - putHeaders(clusterStateRequest, transportHeaders); - putContext(clusterStateRequest, transportContext); - assertHeaders(clusterStateRequest, transportHeaders); - client.admin().cluster().state(clusterStateRequest); - assertHeaders(clusterStateRequest, expectedHeaders); - assertContext(clusterStateRequest, expectedContext); - - ClusterStatsRequest clusterStatsRequest = Requests.clusterStatsRequest(); - putHeaders(clusterStatsRequest, transportHeaders); - putContext(clusterStatsRequest, transportContext); - assertHeaders(clusterStatsRequest, transportHeaders); - client.admin().cluster().clusterStats(clusterStatsRequest); - assertHeaders(clusterStatsRequest, expectedHeaders); - assertContext(clusterStatsRequest, expectedContext); - } - } - - public void testCopyHeadersIndicesAdminRequest() { - Map transportHeaders = randomHeaders(randomIntBetween(0, 10)); - Map restHeaders = randomHeaders(randomIntBetween(0, 10)); - Map copiedHeaders = randomHeadersFrom(restHeaders); - Set usefulRestHeaders = new HashSet<>(copiedHeaders.keySet()); - usefulRestHeaders.addAll(randomMap(randomIntBetween(0, 10), "useful-").keySet()); - Map restContext = randomContext(randomIntBetween(0, 10)); - Map transportContext = onlyOnLeft(randomContext(randomIntBetween(0, 10)), restContext); - - HashMap expectedHeaders = new HashMap<>(); - expectedHeaders.putAll(transportHeaders); - expectedHeaders.putAll(copiedHeaders); - - Map expectedContext = new HashMap<>(); - expectedContext.putAll(transportContext); - expectedContext.putAll(restContext); - - try (Client client = client(new NoOpClient(getTestName()), new FakeRestRequest(restHeaders, restContext), usefulRestHeaders)) { - - CreateIndexRequest createIndexRequest = Requests.createIndexRequest("test"); - putHeaders(createIndexRequest, transportHeaders); - putContext(createIndexRequest, transportContext); - assertHeaders(createIndexRequest, transportHeaders); - client.admin().indices().create(createIndexRequest); - assertHeaders(createIndexRequest, expectedHeaders); - assertContext(createIndexRequest, expectedContext); - - CloseIndexRequest closeIndexRequest = Requests.closeIndexRequest("test"); - putHeaders(closeIndexRequest, transportHeaders); - putContext(closeIndexRequest, transportContext); - assertHeaders(closeIndexRequest, transportHeaders); - client.admin().indices().close(closeIndexRequest); - assertHeaders(closeIndexRequest, expectedHeaders); - assertContext(closeIndexRequest, expectedContext); - - FlushRequest flushRequest = Requests.flushRequest(); - putHeaders(flushRequest, transportHeaders); - putContext(flushRequest, transportContext); - assertHeaders(flushRequest, transportHeaders); - client.admin().indices().flush(flushRequest); - assertHeaders(flushRequest, expectedHeaders); - assertContext(flushRequest, expectedContext); - } - } - - public void testCopyHeadersRequestBuilder() { - Map transportHeaders = randomHeaders(randomIntBetween(0, 10)); - Map restHeaders = randomHeaders(randomIntBetween(0, 10)); - Map copiedHeaders = randomHeadersFrom(restHeaders); - Set usefulRestHeaders = new HashSet<>(copiedHeaders.keySet()); - usefulRestHeaders.addAll(randomMap(randomIntBetween(0, 10), "useful-").keySet()); - Map restContext = randomContext(randomIntBetween(0, 10)); - Map transportContext = onlyOnLeft(randomContext(randomIntBetween(0, 10)), restContext); - - HashMap expectedHeaders = new HashMap<>(); - expectedHeaders.putAll(transportHeaders); - expectedHeaders.putAll(copiedHeaders); - - Map expectedContext = new HashMap<>(); - expectedContext.putAll(transportContext); - expectedContext.putAll(restContext); - - try (Client client = client(new NoOpClient(getTestName()), new FakeRestRequest(restHeaders, restContext), usefulRestHeaders)) { - - ActionRequestBuilder requestBuilders[] = new ActionRequestBuilder[]{ - client.prepareIndex("index", "type"), - client.prepareGet("index", "type", "id"), - client.prepareBulk(), - client.prepareDelete(), - client.prepareIndex(), - client.prepareClearScroll(), - client.prepareMultiGet(), - }; - - for (ActionRequestBuilder requestBuilder : requestBuilders) { - putHeaders(requestBuilder.request(), transportHeaders); - putContext(requestBuilder.request(), transportContext); - assertHeaders(requestBuilder.request(), transportHeaders); - requestBuilder.get(); - assertHeaders(requestBuilder.request(), expectedHeaders); - assertContext(requestBuilder.request(), expectedContext); - } - } - } - - public void testCopyHeadersClusterAdminRequestBuilder() { - Map transportHeaders = randomHeaders(randomIntBetween(0, 10)); - Map restHeaders = randomHeaders(randomIntBetween(0, 10)); - Map copiedHeaders = randomHeadersFrom(restHeaders); - Set usefulRestHeaders = new HashSet<>(copiedHeaders.keySet()); - usefulRestHeaders.addAll(randomMap(randomIntBetween(0, 10), "useful-").keySet()); - Map restContext = randomContext(randomIntBetween(0, 10)); - Map transportContext = onlyOnLeft(randomContext(randomIntBetween(0, 10)), restContext); - - HashMap expectedHeaders = new HashMap<>(); - expectedHeaders.putAll(transportHeaders); - expectedHeaders.putAll(copiedHeaders); - - Map expectedContext = new HashMap<>(); - expectedContext.putAll(transportContext); - expectedContext.putAll(restContext); - - try (Client client = client(new NoOpClient(getTestName()), new FakeRestRequest(restHeaders, restContext), usefulRestHeaders)) { - - ActionRequestBuilder requestBuilders[] = new ActionRequestBuilder[]{ - client.admin().cluster().prepareNodesInfo(), - client.admin().cluster().prepareClusterStats(), - client.admin().cluster().prepareState(), - client.admin().cluster().prepareCreateSnapshot("repo", "name"), - client.admin().cluster().prepareHealth(), - client.admin().cluster().prepareReroute() - }; - - for (ActionRequestBuilder requestBuilder : requestBuilders) { - putHeaders(requestBuilder.request(), transportHeaders); - putContext(requestBuilder.request(), transportContext); - assertHeaders(requestBuilder.request(), transportHeaders); - requestBuilder.get(); - assertHeaders(requestBuilder.request(), expectedHeaders); - assertContext(requestBuilder.request(), expectedContext); - } - } - } - - public void testCopyHeadersIndicesAdminRequestBuilder() { - Map transportHeaders = randomHeaders(randomIntBetween(0, 10)); - Map restHeaders = randomHeaders(randomIntBetween(0, 10)); - Map copiedHeaders = randomHeadersFrom(restHeaders); - Set usefulRestHeaders = new HashSet<>(copiedHeaders.keySet()); - usefulRestHeaders.addAll(randomMap(randomIntBetween(0, 10), "useful-").keySet()); - Map restContext = randomContext(randomIntBetween(0, 10)); - Map transportContext = onlyOnLeft(randomContext(randomIntBetween(0, 10)), restContext); - - HashMap expectedHeaders = new HashMap<>(); - expectedHeaders.putAll(transportHeaders); - expectedHeaders.putAll(copiedHeaders); - - Map expectedContext = new HashMap<>(); - expectedContext.putAll(transportContext); - expectedContext.putAll(restContext); - - try (Client client = client(new NoOpClient(getTestName()), new FakeRestRequest(restHeaders, restContext), usefulRestHeaders)) { - - ActionRequestBuilder requestBuilders[] = new ActionRequestBuilder[]{ - client.admin().indices().prepareValidateQuery(), - client.admin().indices().prepareCreate("test"), - client.admin().indices().prepareAliases(), - client.admin().indices().prepareAnalyze("text"), - client.admin().indices().prepareTypesExists("type"), - client.admin().indices().prepareClose() - }; - - for (ActionRequestBuilder requestBuilder : requestBuilders) { - putHeaders(requestBuilder.request(), transportHeaders); - putContext(requestBuilder.request(), transportContext); - assertHeaders(requestBuilder.request(), transportHeaders); - requestBuilder.get(); - assertHeaders(requestBuilder.request(), expectedHeaders); - assertContext(requestBuilder.request(), expectedContext); - } - } - } - - private static Map randomHeaders(int count) { - return randomMap(count, "header-"); - } - - private static Map randomContext(int count) { - return randomMap(count, "context-"); - } - - private static Map randomMap(int count, String prefix) { - Map headers = new HashMap<>(); - for (int i = 0; i < count; i++) { - headers.put(prefix + randomInt(30), randomAsciiOfLength(10)); - } - return headers; - } - - private static Map randomHeadersFrom(Map headers) { - Map newHeaders = new HashMap<>(); - if (headers.isEmpty()) { - return newHeaders; - } - int i = randomInt(headers.size() - 1); - for (Map.Entry entry : headers.entrySet()) { - if (randomInt(i) == 0) { - newHeaders.put(entry.getKey(), entry.getValue()); - } - } - return newHeaders; - } - - private static Client client(Client noOpClient, RestRequest restRequest, Set usefulRestHeaders) { - return new BaseRestHandler.HeadersAndContextCopyClient(noOpClient, restRequest, usefulRestHeaders); - } - - private static void putHeaders(ActionRequest request, Map headers) { - for (Map.Entry header : headers.entrySet()) { - request.putHeader(header.getKey(), header.getValue()); - } - } - - private static void putContext(ActionRequest request, Map context) { - for (Map.Entry header : context.entrySet()) { - request.putInContext(header.getKey(), header.getValue()); - } - } - - private static void assertHeaders(ActionRequest request, Map headers) { - if (headers.size() == 0) { - assertThat(request.getHeaders() == null || request.getHeaders().size() == 0, equalTo(true)); - } else { - assertThat(request.getHeaders(), notNullValue()); - assertThat(request.getHeaders().size(), equalTo(headers.size())); - for (String key : request.getHeaders()) { - assertThat(headers.get(key), equalTo(request.getHeader(key))); - } - } - } - - private static void assertContext(ActionRequest request, Map context) { - if (context.size() == 0) { - assertThat(request.isContextEmpty(), is(true)); - } else { - ImmutableOpenMap map = request.getContext(); - assertThat(map, notNullValue()); - assertThat(map.size(), equalTo(context.size())); - for (Object key : map.keys()) { - assertThat(context.get(key), equalTo(request.getFromContext(key))); - } - } - } - - private static Map onlyOnLeft(Map left, Map right) { - Map map = new HashMap<>(); - for (Map.Entry entry : left.entrySet()) { - if (!right.containsKey(entry.getKey())) { - map.put(entry.getKey(), entry.getValue()); - } - } - return map; - } -} diff --git a/core/src/test/java/org/elasticsearch/rest/NoOpClient.java b/core/src/test/java/org/elasticsearch/rest/NoOpClient.java index 245bdb96a33..4f2a1ab07bf 100644 --- a/core/src/test/java/org/elasticsearch/rest/NoOpClient.java +++ b/core/src/test/java/org/elasticsearch/rest/NoOpClient.java @@ -26,7 +26,6 @@ import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequestBuilder; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.client.support.AbstractClient; -import org.elasticsearch.client.support.Headers; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.threadpool.ThreadPool; @@ -35,7 +34,7 @@ import java.util.concurrent.TimeUnit; public class NoOpClient extends AbstractClient { public NoOpClient(String testName) { - super(Settings.EMPTY, new ThreadPool(testName), Headers.EMPTY); + super(Settings.EMPTY, new ThreadPool(testName)); } @Override @@ -51,4 +50,4 @@ public class NoOpClient extends AbstractClient { throw new ElasticsearchException(t.getMessage(), t); } } -} \ No newline at end of file +} diff --git a/core/src/test/java/org/elasticsearch/rest/RestControllerTests.java b/core/src/test/java/org/elasticsearch/rest/RestControllerTests.java new file mode 100644 index 00000000000..d6e1a97ac8f --- /dev/null +++ b/core/src/test/java/org/elasticsearch/rest/RestControllerTests.java @@ -0,0 +1,99 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.elasticsearch.rest; + +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.util.concurrent.ThreadContext; +import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.test.rest.FakeRestRequest; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.hamcrest.CoreMatchers.equalTo; + +public class RestControllerTests extends ESTestCase { + + public void testRegisterRelevantHeaders() throws InterruptedException { + + final RestController restController = new RestController(Settings.EMPTY); + + int iterations = randomIntBetween(1, 5); + + Set headers = new HashSet<>(); + ExecutorService executorService = Executors.newFixedThreadPool(iterations); + for (int i = 0; i < iterations; i++) { + int headersCount = randomInt(10); + final Set newHeaders = new HashSet<>(); + for (int j = 0; j < headersCount; j++) { + String usefulHeader = randomRealisticUnicodeOfLengthBetween(1, 30); + newHeaders.add(usefulHeader); + } + headers.addAll(newHeaders); + + executorService.submit((Runnable) () -> restController.registerRelevantHeaders(newHeaders.toArray(new String[newHeaders.size()]))); + } + + executorService.shutdown(); + assertThat(executorService.awaitTermination(1, TimeUnit.SECONDS), equalTo(true)); + String[] relevantHeaders = restController.relevantHeaders().toArray(new String[restController.relevantHeaders().size()]); + assertThat(relevantHeaders.length, equalTo(headers.size())); + + Arrays.sort(relevantHeaders); + String[] headersArray = new String[headers.size()]; + headersArray = headers.toArray(headersArray); + Arrays.sort(headersArray); + assertThat(relevantHeaders, equalTo(headersArray)); + } + + public void testApplyRelevantHeaders() { + final ThreadContext threadContext = new ThreadContext(Settings.EMPTY); + final RestController restController = new RestController(Settings.EMPTY) { + @Override + boolean checkRequestParameters(RestRequest request, RestChannel channel) { + return true; + } + + @Override + void executeHandler(RestRequest request, RestChannel channel) throws Exception { + assertEquals("true", threadContext.getHeader("header.1")); + assertEquals("true", threadContext.getHeader("header.2")); + assertNull(threadContext.getHeader("header.3")); + + } + }; + threadContext.putHeader("header.3", "true"); + restController.registerRelevantHeaders("header.1", "header.2"); + Map restHeaders = new HashMap<>(); + restHeaders.put("header.1", "true"); + restHeaders.put("header.2", "true"); + restHeaders.put("header.3", "false"); + restController.dispatchRequest(new FakeRestRequest(restHeaders), null, threadContext); + assertNull(threadContext.getHeader("header.1")); + assertNull(threadContext.getHeader("header.2")); + assertEquals("true", threadContext.getHeader("header.3")); + } +} diff --git a/core/src/test/java/org/elasticsearch/rest/RestFilterChainTests.java b/core/src/test/java/org/elasticsearch/rest/RestFilterChainTests.java index b66d00cd6a8..56ae8e2183d 100644 --- a/core/src/test/java/org/elasticsearch/rest/RestFilterChainTests.java +++ b/core/src/test/java/org/elasticsearch/rest/RestFilterChainTests.java @@ -23,6 +23,7 @@ import org.elasticsearch.common.Nullable; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.rest.FakeRestRequest; @@ -84,7 +85,7 @@ public class RestFilterChainTests extends ESTestCase { FakeRestRequest fakeRestRequest = new FakeRestRequest(); FakeRestChannel fakeRestChannel = new FakeRestChannel(fakeRestRequest, 1); - restController.dispatchRequest(fakeRestRequest, fakeRestChannel); + restController.dispatchRequest(fakeRestRequest, fakeRestChannel, new ThreadContext(Settings.EMPTY)); assertThat(fakeRestChannel.await(), equalTo(true)); @@ -142,7 +143,7 @@ public class RestFilterChainTests extends ESTestCase { FakeRestRequest fakeRestRequest = new FakeRestRequest(); FakeRestChannel fakeRestChannel = new FakeRestChannel(fakeRestRequest, additionalContinueCount + 1); - restController.dispatchRequest(fakeRestRequest, fakeRestChannel); + restController.dispatchRequest(fakeRestRequest, fakeRestChannel, new ThreadContext(Settings.EMPTY)); fakeRestChannel.await(); assertThat(testFilter.runs.get(), equalTo(1)); diff --git a/core/src/test/java/org/elasticsearch/rest/RestRequestTests.java b/core/src/test/java/org/elasticsearch/rest/RestRequestTests.java deleted file mode 100644 index 8e60b28f376..00000000000 --- a/core/src/test/java/org/elasticsearch/rest/RestRequestTests.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.rest; - -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.collect.ImmutableOpenMap; -import org.elasticsearch.test.ESTestCase; - -import java.util.Map; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; - -/** - * - */ -public class RestRequestTests extends ESTestCase { - public void testContext() throws Exception { - int count = randomInt(10); - Request request = new Request(); - for (int i = 0; i < count; i++) { - request.putInContext("key" + i, "val" + i); - } - assertThat(request.isContextEmpty(), is(count == 0)); - assertThat(request.contextSize(), is(count)); - ImmutableOpenMap ctx = request.getContext(); - for (int i = 0; i < count; i++) { - assertThat(request.hasInContext("key" + i), is(true)); - assertThat((String) request.getFromContext("key" + i), equalTo("val" + i)); - assertThat((String) ctx.get("key" + i), equalTo("val" + i)); - } - } - - public static class Request extends RestRequest { - @Override - public Method method() { - return null; - } - - @Override - public String uri() { - return null; - } - - @Override - public String rawPath() { - return null; - } - - @Override - public boolean hasContent() { - return false; - } - - @Override - public BytesReference content() { - return null; - } - - @Override - public String header(String name) { - return null; - } - - @Override - public Iterable> headers() { - return null; - } - - @Override - public boolean hasParam(String key) { - return false; - } - - @Override - public String param(String key) { - return null; - } - - @Override - public Map params() { - return null; - } - - @Override - public String param(String key, String defaultValue) { - return null; - } - } -} diff --git a/core/src/test/java/org/elasticsearch/script/FileScriptTests.java b/core/src/test/java/org/elasticsearch/script/FileScriptTests.java index 987aef90bc3..7b891777b33 100644 --- a/core/src/test/java/org/elasticsearch/script/FileScriptTests.java +++ b/core/src/test/java/org/elasticsearch/script/FileScriptTests.java @@ -18,7 +18,6 @@ */ package org.elasticsearch.script; -import org.elasticsearch.common.ContextAndHeaderHolder; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.test.ESTestCase; @@ -49,16 +48,14 @@ public class FileScriptTests extends ESTestCase { } public void testFileScriptFound() throws Exception { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); Settings settings = Settings.builder() .put("script.engine." + MockScriptEngine.NAME + ".file.aggs", false).build(); ScriptService scriptService = makeScriptService(settings); Script script = new Script("script1", ScriptService.ScriptType.FILE, MockScriptEngine.NAME, null); - assertNotNull(scriptService.compile(script, ScriptContext.Standard.SEARCH, contextAndHeaders, Collections.emptyMap())); + assertNotNull(scriptService.compile(script, ScriptContext.Standard.SEARCH, Collections.emptyMap())); } public void testAllOpsDisabled() throws Exception { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); Settings settings = Settings.builder() .put("script.engine." + MockScriptEngine.NAME + ".file.aggs", false) .put("script.engine." + MockScriptEngine.NAME + ".file.search", false) @@ -68,7 +65,7 @@ public class FileScriptTests extends ESTestCase { Script script = new Script("script1", ScriptService.ScriptType.FILE, MockScriptEngine.NAME, null); for (ScriptContext context : ScriptContext.Standard.values()) { try { - scriptService.compile(script, context, contextAndHeaders, Collections.emptyMap()); + scriptService.compile(script, context, Collections.emptyMap()); fail(context.getKey() + " script should have been rejected"); } catch(Exception e) { assertTrue(e.getMessage(), e.getMessage().contains("scripts of type [file], operation [" + context.getKey() + "] and lang [" + MockScriptEngine.NAME + "] are disabled")); diff --git a/core/src/test/java/org/elasticsearch/script/NativeScriptTests.java b/core/src/test/java/org/elasticsearch/script/NativeScriptTests.java index 47adeabe02f..78314c7a7b9 100644 --- a/core/src/test/java/org/elasticsearch/script/NativeScriptTests.java +++ b/core/src/test/java/org/elasticsearch/script/NativeScriptTests.java @@ -19,7 +19,6 @@ package org.elasticsearch.script; -import org.elasticsearch.common.ContextAndHeaderHolder; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.inject.Injector; import org.elasticsearch.common.inject.ModulesBuilder; @@ -47,7 +46,6 @@ import static org.hamcrest.Matchers.notNullValue; public class NativeScriptTests extends ESTestCase { public void testNativeScript() throws InterruptedException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); Settings settings = Settings.settingsBuilder() .put("name", "testNativeScript") .put("path.home", createTempDir()) @@ -63,13 +61,12 @@ public class NativeScriptTests extends ESTestCase { ScriptService scriptService = injector.getInstance(ScriptService.class); ExecutableScript executable = scriptService.executable(new Script("my", ScriptType.INLINE, NativeScriptEngineService.NAME, null), - ScriptContext.Standard.SEARCH, contextAndHeaders, Collections.emptyMap()); + ScriptContext.Standard.SEARCH, Collections.emptyMap()); assertThat(executable.run().toString(), equalTo("test")); terminate(injector.getInstance(ThreadPool.class)); } public void testFineGrainedSettingsDontAffectNativeScripts() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); Settings.Builder builder = Settings.settingsBuilder(); if (randomBoolean()) { ScriptType scriptType = randomFrom(ScriptType.values()); @@ -89,7 +86,7 @@ public class NativeScriptTests extends ESTestCase { for (ScriptContext scriptContext : scriptContextRegistry.scriptContexts()) { assertThat(scriptService.compile(new Script("my", ScriptType.INLINE, NativeScriptEngineService.NAME, null), scriptContext, - contextAndHeaders, Collections.emptyMap()), notNullValue()); + Collections.emptyMap()), notNullValue()); } } diff --git a/core/src/test/java/org/elasticsearch/script/ScriptContextTests.java b/core/src/test/java/org/elasticsearch/script/ScriptContextTests.java index 019eb7c74a0..42378cb7024 100644 --- a/core/src/test/java/org/elasticsearch/script/ScriptContextTests.java +++ b/core/src/test/java/org/elasticsearch/script/ScriptContextTests.java @@ -19,7 +19,6 @@ package org.elasticsearch.script; -import org.elasticsearch.common.ContextAndHeaderHolder; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.test.ESTestCase; @@ -53,12 +52,11 @@ public class ScriptContextTests extends ESTestCase { } public void testCustomGlobalScriptContextSettings() throws Exception { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); ScriptService scriptService = makeScriptService(); for (ScriptService.ScriptType scriptType : ScriptService.ScriptType.values()) { try { Script script = new Script("1", scriptType, MockScriptEngine.NAME, null); - scriptService.compile(script, new ScriptContext.Plugin(PLUGIN_NAME, "custom_globally_disabled_op"), contextAndHeaders, Collections.emptyMap()); + scriptService.compile(script, new ScriptContext.Plugin(PLUGIN_NAME, "custom_globally_disabled_op"), Collections.emptyMap()); fail("script compilation should have been rejected"); } catch (ScriptException e) { assertThat(e.getMessage(), containsString("scripts of type [" + scriptType + "], operation [" + PLUGIN_NAME + "_custom_globally_disabled_op] and lang [" + MockScriptEngine.NAME + "] are disabled")); @@ -67,29 +65,27 @@ public class ScriptContextTests extends ESTestCase { } public void testCustomScriptContextSettings() throws Exception { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); ScriptService scriptService = makeScriptService(); Script script = new Script("1", ScriptService.ScriptType.INLINE, MockScriptEngine.NAME, null); try { - scriptService.compile(script, new ScriptContext.Plugin(PLUGIN_NAME, "custom_exp_disabled_op"), contextAndHeaders, Collections.emptyMap()); + scriptService.compile(script, new ScriptContext.Plugin(PLUGIN_NAME, "custom_exp_disabled_op"), Collections.emptyMap()); fail("script compilation should have been rejected"); } catch (ScriptException e) { assertTrue(e.getMessage(), e.getMessage().contains("scripts of type [inline], operation [" + PLUGIN_NAME + "_custom_exp_disabled_op] and lang [" + MockScriptEngine.NAME + "] are disabled")); } // still works for other script contexts - assertNotNull(scriptService.compile(script, ScriptContext.Standard.AGGS, contextAndHeaders, Collections.emptyMap())); - assertNotNull(scriptService.compile(script, ScriptContext.Standard.SEARCH, contextAndHeaders, Collections.emptyMap())); - assertNotNull(scriptService.compile(script, new ScriptContext.Plugin(PLUGIN_NAME, "custom_op"), contextAndHeaders, Collections.emptyMap())); + assertNotNull(scriptService.compile(script, ScriptContext.Standard.AGGS, Collections.emptyMap())); + assertNotNull(scriptService.compile(script, ScriptContext.Standard.SEARCH, Collections.emptyMap())); + assertNotNull(scriptService.compile(script, new ScriptContext.Plugin(PLUGIN_NAME, "custom_op"), Collections.emptyMap())); } public void testUnknownPluginScriptContext() throws Exception { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); ScriptService scriptService = makeScriptService(); for (ScriptService.ScriptType scriptType : ScriptService.ScriptType.values()) { try { Script script = new Script("1", scriptType, MockScriptEngine.NAME, null); - scriptService.compile(script, new ScriptContext.Plugin(PLUGIN_NAME, "unknown"), contextAndHeaders, Collections.emptyMap()); + scriptService.compile(script, new ScriptContext.Plugin(PLUGIN_NAME, "unknown"), Collections.emptyMap()); fail("script compilation should have been rejected"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage(), e.getMessage().contains("script context [" + PLUGIN_NAME + "_unknown] not supported")); @@ -98,7 +94,6 @@ public class ScriptContextTests extends ESTestCase { } public void testUnknownCustomScriptContext() throws Exception { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); ScriptContext context = new ScriptContext() { @Override public String getKey() { @@ -109,7 +104,7 @@ public class ScriptContextTests extends ESTestCase { for (ScriptService.ScriptType scriptType : ScriptService.ScriptType.values()) { try { Script script = new Script("1", scriptType, MockScriptEngine.NAME, null); - scriptService.compile(script, context, contextAndHeaders, Collections.emptyMap()); + scriptService.compile(script, context, Collections.emptyMap()); fail("script compilation should have been rejected"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage(), e.getMessage().contains("script context [test] not supported")); diff --git a/core/src/test/java/org/elasticsearch/script/ScriptServiceTests.java b/core/src/test/java/org/elasticsearch/script/ScriptServiceTests.java index 3c939e7e91a..f94835e90ab 100644 --- a/core/src/test/java/org/elasticsearch/script/ScriptServiceTests.java +++ b/core/src/test/java/org/elasticsearch/script/ScriptServiceTests.java @@ -18,8 +18,6 @@ */ package org.elasticsearch.script; -import org.elasticsearch.common.ContextAndHeaderHolder; -import org.elasticsearch.common.HasContextAndHeaders; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.io.Streams; import org.elasticsearch.common.settings.Settings; @@ -101,7 +99,7 @@ public class ScriptServiceTests extends ESTestCase { Environment environment = new Environment(finalSettings); scriptService = new ScriptService(finalSettings, environment, Collections.singleton(scriptEngineService), resourceWatcherService, scriptContextRegistry) { @Override - String getScriptFromIndex(String scriptLang, String id, HasContextAndHeaders headersContext) { + String getScriptFromIndex(String scriptLang, String id) { //mock the script that gets retrieved from an index return "100"; } @@ -119,7 +117,6 @@ public class ScriptServiceTests extends ESTestCase { public void testScriptsWithoutExtensions() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); buildScriptService(Settings.EMPTY); logger.info("--> setup two test files one with extension and another without"); Path testFileNoExt = scriptsFilePath.resolve("test_no_ext"); @@ -130,7 +127,7 @@ public class ScriptServiceTests extends ESTestCase { logger.info("--> verify that file with extension was correctly processed"); CompiledScript compiledScript = scriptService.compile(new Script("test_script", ScriptType.FILE, "test", null), - ScriptContext.Standard.SEARCH, contextAndHeaders, Collections.emptyMap()); + ScriptContext.Standard.SEARCH, Collections.emptyMap()); assertThat(compiledScript.compiled(), equalTo((Object) "compiled_test_file")); logger.info("--> delete both files"); @@ -141,7 +138,7 @@ public class ScriptServiceTests extends ESTestCase { logger.info("--> verify that file with extension was correctly removed"); try { scriptService.compile(new Script("test_script", ScriptType.FILE, "test", null), ScriptContext.Standard.SEARCH, - contextAndHeaders, Collections.emptyMap()); + Collections.emptyMap()); fail("the script test_script should no longer exist"); } catch (IllegalArgumentException ex) { assertThat(ex.getMessage(), containsString("Unable to find on disk file script [test_script] using lang [test]")); @@ -149,38 +146,34 @@ public class ScriptServiceTests extends ESTestCase { } public void testInlineScriptCompiledOnceCache() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); buildScriptService(Settings.EMPTY); CompiledScript compiledScript1 = scriptService.compile(new Script("1+1", ScriptType.INLINE, "test", null), - randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); + randomFrom(scriptContexts), Collections.emptyMap()); CompiledScript compiledScript2 = scriptService.compile(new Script("1+1", ScriptType.INLINE, "test", null), - randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); + randomFrom(scriptContexts), Collections.emptyMap()); assertThat(compiledScript1.compiled(), sameInstance(compiledScript2.compiled())); } public void testInlineScriptCompiledOnceMultipleLangAcronyms() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); buildScriptService(Settings.EMPTY); CompiledScript compiledScript1 = scriptService.compile(new Script("script", ScriptType.INLINE, "test", null), - randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); + randomFrom(scriptContexts), Collections.emptyMap()); CompiledScript compiledScript2 = scriptService.compile(new Script("script", ScriptType.INLINE, "test2", null), - randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); + randomFrom(scriptContexts), Collections.emptyMap()); assertThat(compiledScript1.compiled(), sameInstance(compiledScript2.compiled())); } public void testFileScriptCompiledOnceMultipleLangAcronyms() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); buildScriptService(Settings.EMPTY); createFileScripts("test"); CompiledScript compiledScript1 = scriptService.compile(new Script("file_script", ScriptType.FILE, "test", null), - randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); + randomFrom(scriptContexts), Collections.emptyMap()); CompiledScript compiledScript2 = scriptService.compile(new Script("file_script", ScriptType.FILE, "test2", null), - randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); + randomFrom(scriptContexts), Collections.emptyMap()); assertThat(compiledScript1.compiled(), sameInstance(compiledScript2.compiled())); } public void testDefaultBehaviourFineGrainedSettings() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); Settings.Builder builder = Settings.builder(); //rarely inject the default settings, which have no effect if (rarely()) { @@ -197,14 +190,13 @@ public class ScriptServiceTests extends ESTestCase { for (ScriptContext scriptContext : scriptContexts) { //custom engine is sandboxed, all scripts are enabled by default - assertCompileAccepted("test", "script", ScriptType.INLINE, scriptContext, contextAndHeaders); - assertCompileAccepted("test", "script", ScriptType.INDEXED, scriptContext, contextAndHeaders); - assertCompileAccepted("test", "file_script", ScriptType.FILE, scriptContext, contextAndHeaders); + assertCompileAccepted("test", "script", ScriptType.INLINE, scriptContext); + assertCompileAccepted("test", "script", ScriptType.INDEXED, scriptContext); + assertCompileAccepted("test", "file_script", ScriptType.FILE, scriptContext); } } public void testFineGrainedSettings() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); //collect the fine-grained settings to set for this run int numScriptSettings = randomIntBetween(0, ScriptType.values().length); Map scriptSourceSettings = new HashMap<>(); @@ -305,16 +297,16 @@ public class ScriptServiceTests extends ESTestCase { for (String lang : scriptEngineService.types()) { switch (scriptMode) { case ON: - assertCompileAccepted(lang, script, scriptType, scriptContext, contextAndHeaders); + assertCompileAccepted(lang, script, scriptType, scriptContext); break; case OFF: - assertCompileRejected(lang, script, scriptType, scriptContext, contextAndHeaders); + assertCompileRejected(lang, script, scriptType, scriptContext); break; case SANDBOX: if (scriptEngineService.sandboxed()) { - assertCompileAccepted(lang, script, scriptType, scriptContext, contextAndHeaders); + assertCompileAccepted(lang, script, scriptType, scriptContext); } else { - assertCompileRejected(lang, script, scriptType, scriptContext, contextAndHeaders); + assertCompileRejected(lang, script, scriptType, scriptContext); } break; } @@ -324,7 +316,6 @@ public class ScriptServiceTests extends ESTestCase { } public void testCompileNonRegisteredContext() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); buildScriptService(Settings.EMPTY); String pluginName; String unknownContext; @@ -336,7 +327,7 @@ public class ScriptServiceTests extends ESTestCase { for (String type : scriptEngineService.types()) { try { scriptService.compile(new Script("test", randomFrom(ScriptType.values()), type, null), new ScriptContext.Plugin( - pluginName, unknownContext), contextAndHeaders, Collections.emptyMap()); + pluginName, unknownContext), Collections.emptyMap()); fail("script compilation should have been rejected"); } catch(IllegalArgumentException e) { assertThat(e.getMessage(), containsString("script context [" + pluginName + "_" + unknownContext + "] not supported")); @@ -345,16 +336,14 @@ public class ScriptServiceTests extends ESTestCase { } public void testCompileCountedInCompilationStats() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); buildScriptService(Settings.EMPTY); - scriptService.compile(new Script("1+1", ScriptType.INLINE, "test", null), randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); + scriptService.compile(new Script("1+1", ScriptType.INLINE, "test", null), randomFrom(scriptContexts), Collections.emptyMap()); assertEquals(1L, scriptService.stats().getCompilations()); } public void testExecutableCountedInCompilationStats() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); buildScriptService(Settings.EMPTY); - scriptService.executable(new Script("1+1", ScriptType.INLINE, "test", null), randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); + scriptService.executable(new Script("1+1", ScriptType.INLINE, "test", null), randomFrom(scriptContexts), Collections.emptyMap()); assertEquals(1L, scriptService.stats().getCompilations()); } @@ -365,48 +354,43 @@ public class ScriptServiceTests extends ESTestCase { } public void testMultipleCompilationsCountedInCompilationStats() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); buildScriptService(Settings.EMPTY); int numberOfCompilations = randomIntBetween(1, 1024); for (int i = 0; i < numberOfCompilations; i++) { scriptService - .compile(new Script(i + " + " + i, ScriptType.INLINE, "test", null), randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); + .compile(new Script(i + " + " + i, ScriptType.INLINE, "test", null), randomFrom(scriptContexts), Collections.emptyMap()); } assertEquals(numberOfCompilations, scriptService.stats().getCompilations()); } public void testCompilationStatsOnCacheHit() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); Settings.Builder builder = Settings.builder(); builder.put(ScriptService.SCRIPT_CACHE_SIZE_SETTING, 1); buildScriptService(builder.build()); - scriptService.executable(new Script("1+1", ScriptType.INLINE, "test", null), randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); - scriptService.executable(new Script("1+1", ScriptType.INLINE, "test", null), randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); + scriptService.executable(new Script("1+1", ScriptType.INLINE, "test", null), randomFrom(scriptContexts), Collections.emptyMap()); + scriptService.executable(new Script("1+1", ScriptType.INLINE, "test", null), randomFrom(scriptContexts), Collections.emptyMap()); assertEquals(1L, scriptService.stats().getCompilations()); } public void testFileScriptCountedInCompilationStats() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); buildScriptService(Settings.EMPTY); createFileScripts("test"); - scriptService.compile(new Script("file_script", ScriptType.FILE, "test", null), randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); + scriptService.compile(new Script("file_script", ScriptType.FILE, "test", null), randomFrom(scriptContexts), Collections.emptyMap()); assertEquals(1L, scriptService.stats().getCompilations()); } public void testIndexedScriptCountedInCompilationStats() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); buildScriptService(Settings.EMPTY); - scriptService.compile(new Script("script", ScriptType.INDEXED, "test", null), randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); + scriptService.compile(new Script("script", ScriptType.INDEXED, "test", null), randomFrom(scriptContexts), Collections.emptyMap()); assertEquals(1L, scriptService.stats().getCompilations()); } public void testCacheEvictionCountedInCacheEvictionsStats() throws IOException { - ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder(); Settings.Builder builder = Settings.builder(); builder.put(ScriptService.SCRIPT_CACHE_SIZE_SETTING, 1); buildScriptService(builder.build()); - scriptService.executable(new Script("1+1", ScriptType.INLINE, "test", null), randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); - scriptService.executable(new Script("2+2", ScriptType.INLINE, "test", null), randomFrom(scriptContexts), contextAndHeaders, Collections.emptyMap()); + scriptService.executable(new Script("1+1", ScriptType.INLINE, "test", null), randomFrom(scriptContexts), Collections.emptyMap()); + scriptService.executable(new Script("2+2", ScriptType.INLINE, "test", null), randomFrom(scriptContexts), Collections.emptyMap()); assertEquals(2L, scriptService.stats().getCompilations()); assertEquals(1L, scriptService.stats().getCacheEvictions()); } @@ -419,19 +403,17 @@ public class ScriptServiceTests extends ESTestCase { resourceWatcherService.notifyNow(); } - private void assertCompileRejected(String lang, String script, ScriptType scriptType, ScriptContext scriptContext, - HasContextAndHeaders contextAndHeaders) { + private void assertCompileRejected(String lang, String script, ScriptType scriptType, ScriptContext scriptContext) { try { - scriptService.compile(new Script(script, scriptType, lang, null), scriptContext, contextAndHeaders, Collections.emptyMap()); + scriptService.compile(new Script(script, scriptType, lang, null), scriptContext, Collections.emptyMap()); fail("compile should have been rejected for lang [" + lang + "], script_type [" + scriptType + "], scripted_op [" + scriptContext + "]"); } catch(ScriptException e) { //all good } } - private void assertCompileAccepted(String lang, String script, ScriptType scriptType, ScriptContext scriptContext, - HasContextAndHeaders contextAndHeaders) { - assertThat(scriptService.compile(new Script(script, scriptType, lang, null), scriptContext, contextAndHeaders, Collections.emptyMap()), notNullValue()); + private void assertCompileAccepted(String lang, String script, ScriptType scriptType, ScriptContext scriptContext) { + assertThat(scriptService.compile(new Script(script, scriptType, lang, null), scriptContext, Collections.emptyMap()), notNullValue()); } public static class TestEngineService implements ScriptEngineService { diff --git a/core/src/test/java/org/elasticsearch/search/suggest/CustomSuggester.java b/core/src/test/java/org/elasticsearch/search/suggest/CustomSuggester.java index 419316b5265..35d495272ca 100644 --- a/core/src/test/java/org/elasticsearch/search/suggest/CustomSuggester.java +++ b/core/src/test/java/org/elasticsearch/search/suggest/CustomSuggester.java @@ -54,7 +54,7 @@ public class CustomSuggester extends Suggester { + return (parser, mapperService, fieldData) -> { Map options = parser.map(); CustomSuggestionsContext suggestionContext = new CustomSuggestionsContext(CustomSuggester.this, options); suggestionContext.setField((String) options.get("field")); diff --git a/core/src/test/java/org/elasticsearch/transport/AbstractSimpleTransportTestCase.java b/core/src/test/java/org/elasticsearch/transport/AbstractSimpleTransportTestCase.java index a5b6e08de3f..747b218b797 100644 --- a/core/src/test/java/org/elasticsearch/transport/AbstractSimpleTransportTestCase.java +++ b/core/src/test/java/org/elasticsearch/transport/AbstractSimpleTransportTestCase.java @@ -37,6 +37,7 @@ import org.junit.Before; import java.io.IOException; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; @@ -204,6 +205,61 @@ public abstract class AbstractSimpleTransportTestCase extends ESTestCase { serviceA.removeHandler("sayHello"); } + public void testThreadContext() throws ExecutionException, InterruptedException { + + serviceA.registerRequestHandler("ping_pong", StringMessageRequest::new, ThreadPool.Names.GENERIC, (request, channel) -> { + assertEquals("ping_user", threadPool.getThreadContext().getHeader("test.ping.user")); + assertNull(threadPool.getThreadContext().getTransient("my_private_context")); + try { + StringMessageResponse response = new StringMessageResponse("pong"); + threadPool.getThreadContext().putHeader("test.pong.user", "pong_user"); + channel.sendResponse(response); + } catch (IOException e) { + assertThat(e.getMessage(), false, equalTo(true)); + } + }); + final Object context = new Object(); + final String executor = randomFrom(ThreadPool.THREAD_POOL_TYPES.keySet().toArray(new String[0])); + BaseTransportResponseHandler baseTransportResponseHandler = new BaseTransportResponseHandler() { + @Override + public StringMessageResponse newInstance() { + return new StringMessageResponse(); + } + + @Override + public String executor() { + return executor; + } + + @Override + public void handleResponse(StringMessageResponse response) { + assertThat("pong", equalTo(response.message)); + assertEquals("ping_user", threadPool.getThreadContext().getHeader("test.ping.user")); + assertNull(threadPool.getThreadContext().getHeader("test.pong.user")); + assertSame(context, threadPool.getThreadContext().getTransient("my_private_context")); + threadPool.getThreadContext().putHeader("some.temp.header", "booooom"); + } + + @Override + public void handleException(TransportException exp) { + assertThat("got exception instead of a response: " + exp.getMessage(), false, equalTo(true)); + } + }; + StringMessageRequest ping = new StringMessageRequest("ping"); + threadPool.getThreadContext().putHeader("test.ping.user", "ping_user"); + threadPool.getThreadContext().putTransient("my_private_context", context); + + TransportFuture res = serviceB.submitRequest(nodeA, "ping_pong", ping, baseTransportResponseHandler); + + StringMessageResponse message = res.get(); + assertThat("pong", equalTo(message.message)); + assertEquals("ping_user", threadPool.getThreadContext().getHeader("test.ping.user")); + assertSame(context, threadPool.getThreadContext().getTransient("my_private_context")); + assertNull("this header is only visible in the handler context", threadPool.getThreadContext().getHeader("some.temp.header")); + + serviceA.removeHandler("sayHello"); + } + public void testLocalNodeConnection() throws InterruptedException { assertTrue("serviceA is not connected to nodeA", serviceA.nodeConnected(nodeA)); if (((TransportService) serviceA).getLocalNode() != null) { diff --git a/core/src/test/java/org/elasticsearch/transport/TransportMessageTests.java b/core/src/test/java/org/elasticsearch/transport/TransportMessageTests.java deleted file mode 100644 index a94b06f6f06..00000000000 --- a/core/src/test/java/org/elasticsearch/transport/TransportMessageTests.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.transport; - -import org.elasticsearch.Version; -import org.elasticsearch.common.io.stream.BytesStreamOutput; -import org.elasticsearch.common.io.stream.StreamInput; -import org.elasticsearch.test.ESTestCase; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; - -/** - * - */ -public class TransportMessageTests extends ESTestCase { - public void testSerialization() throws Exception { - Message message = new Message(); - message.putHeader("key1", "value1"); - message.putHeader("key2", "value2"); - message.putInContext("key3", "value3"); - - BytesStreamOutput out = new BytesStreamOutput(); - out.setVersion(Version.CURRENT); - message.writeTo(out); - StreamInput in = StreamInput.wrap(out.bytes()); - in.setVersion(Version.CURRENT); - message = new Message(); - message.readFrom(in); - assertThat(message.getHeaders().size(), is(2)); - assertThat((String) message.getHeader("key1"), equalTo("value1")); - assertThat((String) message.getHeader("key2"), equalTo("value2")); - assertThat(message.isContextEmpty(), is(true)); - - // ensure that casting is not needed - String key1 = message.getHeader("key1"); - assertThat(key1, is("value1")); - } - - public void testCopyHeadersAndContext() throws Exception { - Message m1 = new Message(); - m1.putHeader("key1", "value1"); - m1.putHeader("key2", "value2"); - m1.putInContext("key3", "value3"); - - Message m2 = new Message(m1); - - assertThat(m2.getHeaders().size(), is(2)); - assertThat((String) m2.getHeader("key1"), equalTo("value1")); - assertThat((String) m2.getHeader("key2"), equalTo("value2")); - assertThat((String) m2.getFromContext("key3"), equalTo("value3")); - - // ensure that casting is not needed - String key3 = m2.getFromContext("key3"); - assertThat(key3, is("value3")); - testContext(m2, "key3", "value3"); - } - - // ensure that generic arg like this is not needed: TransportMessage transportMessage - private void testContext(TransportMessage transportMessage, String key, String expectedValue) { - String result = transportMessage.getFromContext(key); - assertThat(result, is(expectedValue)); - - } - - private static class Message extends TransportMessage { - - private Message() { - } - - private Message(Message message) { - super(message); - } - } -} diff --git a/core/src/test/java/org/elasticsearch/transport/netty/NettyTransportIT.java b/core/src/test/java/org/elasticsearch/transport/netty/NettyTransportIT.java index 55f9bc49df3..f7b8ede6023 100644 --- a/core/src/test/java/org/elasticsearch/transport/netty/NettyTransportIT.java +++ b/core/src/test/java/org/elasticsearch/transport/netty/NettyTransportIT.java @@ -22,6 +22,7 @@ import org.elasticsearch.ElasticsearchException; import org.elasticsearch.Version; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.client.Client; +import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.component.Lifecycle; import org.elasticsearch.common.inject.Inject; @@ -34,6 +35,7 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.common.util.concurrent.AbstractRunnable; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; @@ -49,6 +51,7 @@ import org.jboss.netty.channel.ChannelPipelineFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Collection; +import java.util.Collections; import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.hamcrest.Matchers.containsString; @@ -78,9 +81,8 @@ public class NettyTransportIT extends ESIntegTestCase { Client transportClient = internalCluster().transportClient(); ClusterHealthResponse clusterIndexHealths = transportClient.admin().cluster().prepareHealth().get(); assertThat(clusterIndexHealths.getStatus(), is(ClusterHealthStatus.GREEN)); - try { - transportClient.admin().cluster().prepareHealth().putHeader("ERROR", "MY MESSAGE").get(); + transportClient.filterWithHeader(Collections.singletonMap("ERROR", "MY MESSAGE")).admin().cluster().prepareHealth().get(); fail("Expected exception, but didnt happen"); } catch (ElasticsearchException e) { assertThat(e.getMessage(), containsString("MY MESSAGE")); @@ -141,8 +143,9 @@ public class NettyTransportIT extends ESIntegTestCase { final TransportRequest request = reg.newRequest(); request.remoteAddress(new InetSocketTransportAddress((InetSocketAddress) channel.getRemoteAddress())); request.readFrom(buffer); - if (request.hasHeader("ERROR")) { - throw new ElasticsearchException((String) request.getHeader("ERROR")); + String error = threadPool.getThreadContext().getHeader("ERROR"); + if (error != null) { + throw new ElasticsearchException(error); } if (reg.getExecutor() == ThreadPool.Names.SAME) { //noinspection unchecked diff --git a/modules/lang-groovy/src/test/java/org/elasticsearch/messy/tests/ContextAndHeaderTransportTests.java b/modules/lang-groovy/src/test/java/org/elasticsearch/messy/tests/ContextAndHeaderTransportTests.java index 9b2e0041462..423a660f70a 100644 --- a/modules/lang-groovy/src/test/java/org/elasticsearch/messy/tests/ContextAndHeaderTransportTests.java +++ b/modules/lang-groovy/src/test/java/org/elasticsearch/messy/tests/ContextAndHeaderTransportTests.java @@ -21,11 +21,9 @@ package org.elasticsearch.messy.tests; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; -import org.elasticsearch.action.Action; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionModule; import org.elasticsearch.action.ActionRequest; -import org.elasticsearch.action.ActionRequestBuilder; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.get.GetRequest; @@ -38,12 +36,12 @@ import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.ActionFilter; import org.elasticsearch.action.termvectors.MultiTermVectorsRequest; import org.elasticsearch.client.Client; -import org.elasticsearch.client.FilterClient; import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Module; import org.elasticsearch.common.lucene.search.function.CombineFunction; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.GeoShapeQueryBuilder; @@ -63,6 +61,7 @@ import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; import org.elasticsearch.test.rest.client.http.HttpResponse; +import org.elasticsearch.threadpool.ThreadPool; import org.junit.After; import org.junit.Before; @@ -71,6 +70,7 @@ import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; @@ -89,7 +89,7 @@ import static org.hamcrest.Matchers.is; @ClusterScope(scope = SUITE) public class ContextAndHeaderTransportTests extends ESIntegTestCase { - private static final List requests = new CopyOnWriteArrayList<>(); + private static final List requests = new CopyOnWriteArrayList<>(); private String randomHeaderKey = randomAsciiOfLength(10); private String randomHeaderValue = randomAsciiOfLength(20); private String queryIndex = "query-" + randomAsciiOfLength(10).toLowerCase(Locale.ROOT); @@ -127,7 +127,6 @@ public class ContextAndHeaderTransportTests extends ESIntegTestCase { assertAcked(transportClient().admin().indices().prepareCreate(queryIndex) .setSettings(settings).addMapping("type", mapping)); ensureGreen(queryIndex, lookupIndex); - requests.clear(); } @@ -139,58 +138,60 @@ public class ContextAndHeaderTransportTests extends ESIntegTestCase { public void testThatTermsLookupGetRequestContainsContextAndHeaders() throws Exception { transportClient().prepareIndex(lookupIndex, "type", "1") - .setSource(jsonBuilder().startObject().array("followers", "foo", "bar", "baz").endObject()).get(); + .setSource(jsonBuilder().startObject().array("followers", "foo", "bar", "baz").endObject()).get(); transportClient().prepareIndex(queryIndex, "type", "1") - .setSource(jsonBuilder().startObject().field("username", "foo").endObject()).get(); + .setSource(jsonBuilder().startObject().field("username", "foo").endObject()).get(); transportClient().admin().indices().prepareRefresh(queryIndex, lookupIndex).get(); TermsQueryBuilder termsLookupFilterBuilder = QueryBuilders.termsLookupQuery("username", new TermsLookup(lookupIndex, "type", "1", "followers")); BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.matchAllQuery()).must(termsLookupFilterBuilder); SearchResponse searchResponse = transportClient() - .prepareSearch(queryIndex) - .setQuery(queryBuilder) - .get(); + .prepareSearch(queryIndex) + .setQuery(queryBuilder) + .get(); assertNoFailures(searchResponse); assertHitCount(searchResponse, 1); assertGetRequestsContainHeaders(); } + + public void testThatGeoShapeQueryGetRequestContainsContextAndHeaders() throws Exception { transportClient().prepareIndex(lookupIndex, "type", "1").setSource(jsonBuilder().startObject() - .field("name", "Munich Suburban Area") - .startObject("location") - .field("type", "polygon") - .startArray("coordinates").startArray() - .startArray().value(11.34).value(48.25).endArray() - .startArray().value(11.68).value(48.25).endArray() - .startArray().value(11.65).value(48.06).endArray() - .startArray().value(11.37).value(48.13).endArray() - .startArray().value(11.34).value(48.25).endArray() // close the polygon - .endArray().endArray() - .endObject() - .endObject()) - .get(); + .field("name", "Munich Suburban Area") + .startObject("location") + .field("type", "polygon") + .startArray("coordinates").startArray() + .startArray().value(11.34).value(48.25).endArray() + .startArray().value(11.68).value(48.25).endArray() + .startArray().value(11.65).value(48.06).endArray() + .startArray().value(11.37).value(48.13).endArray() + .startArray().value(11.34).value(48.25).endArray() // close the polygon + .endArray().endArray() + .endObject() + .endObject()) + .get(); // second document transportClient().prepareIndex(queryIndex, "type", "1").setSource(jsonBuilder().startObject() - .field("name", "Munich Center") - .startObject("location") - .field("type", "point") - .startArray("coordinates").value(11.57).value(48.13).endArray() - .endObject() - .endObject()) - .get(); + .field("name", "Munich Center") + .startObject("location") + .field("type", "point") + .startArray("coordinates").value(11.57).value(48.13).endArray() + .endObject() + .endObject()) + .get(); transportClient().admin().indices().prepareRefresh(lookupIndex, queryIndex).get(); GeoShapeQueryBuilder queryBuilder = QueryBuilders.geoShapeQuery("location", "1", "type") - .indexedShapeIndex(lookupIndex) - .indexedShapePath("location"); + .indexedShapeIndex(lookupIndex) + .indexedShapePath("location"); SearchResponse searchResponse = transportClient() - .prepareSearch(queryIndex) - .setQuery(queryBuilder) - .get(); + .prepareSearch(queryIndex) + .setQuery(queryBuilder) + .get(); assertNoFailures(searchResponse); assertHitCount(searchResponse, 1); assertThat(requests, hasSize(greaterThan(0))); @@ -200,25 +201,25 @@ public class ContextAndHeaderTransportTests extends ESIntegTestCase { public void testThatMoreLikeThisQueryMultiTermVectorRequestContainsContextAndHeaders() throws Exception { transportClient().prepareIndex(lookupIndex, "type", "1") - .setSource(jsonBuilder().startObject().field("name", "Star Wars - The new republic").endObject()) - .get(); + .setSource(jsonBuilder().startObject().field("name", "Star Wars - The new republic").endObject()) + .get(); transportClient().prepareIndex(queryIndex, "type", "1") - .setSource(jsonBuilder().startObject().field("name", "Jar Jar Binks - A horrible mistake").endObject()) - .get(); + .setSource(jsonBuilder().startObject().field("name", "Jar Jar Binks - A horrible mistake").endObject()) + .get(); transportClient().prepareIndex(queryIndex, "type", "2") - .setSource(jsonBuilder().startObject().field("name", "Star Wars - Return of the jedi").endObject()) - .get(); + .setSource(jsonBuilder().startObject().field("name", "Star Wars - Return of the jedi").endObject()) + .get(); transportClient().admin().indices().prepareRefresh(lookupIndex, queryIndex).get(); - MoreLikeThisQueryBuilder moreLikeThisQueryBuilder = QueryBuilders.moreLikeThisQuery(new String[] {"name"}, null, - new Item[] {new Item(lookupIndex, "type", "1")}) - .minTermFreq(1) - .minDocFreq(1); + MoreLikeThisQueryBuilder moreLikeThisQueryBuilder = QueryBuilders.moreLikeThisQuery(new String[]{"name"}, null, + new Item[]{new Item(lookupIndex, "type", "1")}) + .minTermFreq(1) + .minDocFreq(1); SearchResponse searchResponse = transportClient() - .prepareSearch(queryIndex) - .setQuery(moreLikeThisQueryBuilder) - .get(); + .prepareSearch(queryIndex) + .setQuery(moreLikeThisQueryBuilder) + .get(); assertNoFailures(searchResponse); assertHitCount(searchResponse, 1); @@ -226,16 +227,17 @@ public class ContextAndHeaderTransportTests extends ESIntegTestCase { } public void testThatPercolatingExistingDocumentGetRequestContainsContextAndHeaders() throws Exception { - transportClient().prepareIndex(lookupIndex, ".percolator", "1") - .setSource(jsonBuilder().startObject().startObject("query").startObject("match").field("name", "star wars").endObject().endObject().endObject()) - .get(); - transportClient().prepareIndex(lookupIndex, "type", "1") - .setSource(jsonBuilder().startObject().field("name", "Star Wars - The new republic").endObject()) - .get(); - transportClient().admin().indices().prepareRefresh(lookupIndex).get(); + Client client = transportClient(); + client.prepareIndex(lookupIndex, ".percolator", "1") + .setSource(jsonBuilder().startObject().startObject("query").startObject("match").field("name", "star wars").endObject().endObject().endObject()) + .get(); + client.prepareIndex(lookupIndex, "type", "1") + .setSource(jsonBuilder().startObject().field("name", "Star Wars - The new republic").endObject()) + .get(); + client.admin().indices().prepareRefresh(lookupIndex).get(); - GetRequest getRequest = transportClient().prepareGet(lookupIndex, "type", "1").request(); - PercolateResponse response = transportClient().preparePercolate().setDocumentType("type").setGetRequest(getRequest).get(); + GetRequest getRequest = client.prepareGet(lookupIndex, "type", "1").request(); + PercolateResponse response = client.preparePercolate().setDocumentType("type").setGetRequest(getRequest).get(); assertThat(response.getCount(), is(1l)); assertGetRequestsContainHeaders(); @@ -243,21 +245,21 @@ public class ContextAndHeaderTransportTests extends ESIntegTestCase { public void testThatIndexedScriptGetRequestContainsContextAndHeaders() throws Exception { PutIndexedScriptResponse scriptResponse = transportClient().preparePutIndexedScript(GroovyScriptEngineService.NAME, "my_script", - jsonBuilder().startObject().field("script", "_score * 10").endObject().string() + jsonBuilder().startObject().field("script", "_score * 10").endObject().string() ).get(); assertThat(scriptResponse.isCreated(), is(true)); transportClient().prepareIndex(queryIndex, "type", "1") - .setSource(jsonBuilder().startObject().field("name", "Star Wars - The new republic").endObject()) - .get(); + .setSource(jsonBuilder().startObject().field("name", "Star Wars - The new republic").endObject()) + .get(); transportClient().admin().indices().prepareRefresh(queryIndex).get(); SearchResponse searchResponse = transportClient() - .prepareSearch(queryIndex) - .setQuery( - QueryBuilders.functionScoreQuery( - new ScriptScoreFunctionBuilder(new Script("my_script", ScriptType.INDEXED, "groovy", null))).boostMode( - CombineFunction.REPLACE)).get(); + .prepareSearch(queryIndex) + .setQuery( + QueryBuilders.functionScoreQuery( + new ScriptScoreFunctionBuilder(new Script("my_script", ScriptType.INDEXED, "groovy", null))).boostMode( + CombineFunction.REPLACE)).get(); assertNoFailures(searchResponse); assertHitCount(searchResponse, 1); assertThat(searchResponse.getHits().getMaxScore(), is(10.0f)); @@ -274,27 +276,27 @@ public class ContextAndHeaderTransportTests extends ESIntegTestCase { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpResponse response = new HttpRequestBuilder(httpClient) - .httpTransport(internalCluster().getDataNodeInstance(HttpServerTransport.class)) - .addHeader(randomHeaderKey, randomHeaderValue) - .addHeader(releventHeaderName, randomHeaderValue) - .path("/" + queryIndex + "/_search") - .execute(); + .httpTransport(internalCluster().getDataNodeInstance(HttpServerTransport.class)) + .addHeader(randomHeaderKey, randomHeaderValue) + .addHeader(releventHeaderName, randomHeaderValue) + .path("/" + queryIndex + "/_search") + .execute(); assertThat(response, hasStatus(OK)); - List searchRequests = getRequests(SearchRequest.class); + List searchRequests = getRequests(SearchRequest.class); assertThat(searchRequests, hasSize(greaterThan(0))); - for (SearchRequest searchRequest : searchRequests) { - assertThat(searchRequest.hasHeader(releventHeaderName), is(true)); + for (RequestAndHeaders requestAndHeaders : searchRequests) { + assertThat(requestAndHeaders.headers.containsKey(releventHeaderName), is(true)); // was not specified, thus is not included - assertThat(searchRequest.hasHeader(randomHeaderKey), is(false)); + assertThat(requestAndHeaders.headers.containsKey(randomHeaderKey), is(false)); } } - private List getRequests(Class clazz) { - List results = new ArrayList<>(); - for (ActionRequest request : requests) { - if (request.getClass().equals(clazz)) { - results.add((T) request); + private List getRequests(Class clazz) { + List results = new ArrayList<>(); + for (RequestAndHeaders request : requests) { + if (request.request.getClass().equals(clazz)) { + results.add(request); } } @@ -302,9 +304,9 @@ public class ContextAndHeaderTransportTests extends ESIntegTestCase { } private void assertRequestsContainHeader(Class clazz) { - List classRequests = getRequests(clazz); - for (ActionRequest request : classRequests) { - assertRequestContainsHeader(request); + List classRequests = getRequests(clazz); + for (RequestAndHeaders request : classRequests) { + assertRequestContainsHeader(request.request, request.headers); } } @@ -313,42 +315,33 @@ public class ContextAndHeaderTransportTests extends ESIntegTestCase { } private void assertGetRequestsContainHeaders(String index) { - List getRequests = getRequests(GetRequest.class); + List getRequests = getRequests(GetRequest.class); assertThat(getRequests, hasSize(greaterThan(0))); - for (GetRequest request : getRequests) { - if (!request.index().equals(index)) { + for (RequestAndHeaders request : getRequests) { + if (!((GetRequest)request.request).index().equals(index)) { continue; } - assertRequestContainsHeader(request); + assertRequestContainsHeader(request.request, request.headers); } } - private void assertRequestContainsHeader(ActionRequest request) { + private void assertRequestContainsHeader(ActionRequest request, Map context) { String msg = String.format(Locale.ROOT, "Expected header %s to be in request %s", randomHeaderKey, request.getClass().getName()); if (request instanceof IndexRequest) { IndexRequest indexRequest = (IndexRequest) request; msg = String.format(Locale.ROOT, "Expected header %s to be in index request %s/%s/%s", randomHeaderKey, indexRequest.index(), indexRequest.type(), indexRequest.id()); } - assertThat(msg, request.hasHeader(randomHeaderKey), is(true)); - assertThat(request.getHeader(randomHeaderKey).toString(), is(randomHeaderValue)); + assertThat(msg, context.containsKey(randomHeaderKey), is(true)); + assertThat(context.get(randomHeaderKey).toString(), is(randomHeaderValue)); } /** * a transport client that adds our random header */ private Client transportClient() { - Client transportClient = internalCluster().transportClient(); - FilterClient filterClient = new FilterClient(transportClient) { - @Override - protected > void doExecute(Action action, Request request, ActionListener listener) { - request.putHeader(randomHeaderKey, randomHeaderValue); - super.doExecute(action, request, listener); - } - }; - - return filterClient; + return internalCluster().transportClient().filterWithHeader(Collections.singletonMap(randomHeaderKey, randomHeaderValue)); } public static class ActionLoggingPlugin extends Plugin { @@ -383,9 +376,12 @@ public class ContextAndHeaderTransportTests extends ESIntegTestCase { public static class LoggingFilter extends ActionFilter.Simple { + private final ThreadPool threadPool; + @Inject - public LoggingFilter(Settings settings) { + public LoggingFilter(Settings settings, ThreadPool pool) { super(settings); + this.threadPool = pool; } @Override @@ -395,7 +391,7 @@ public class ContextAndHeaderTransportTests extends ESIntegTestCase { @Override protected boolean apply(String action, ActionRequest request, ActionListener listener) { - requests.add(request); + requests.add(new RequestAndHeaders(threadPool.getThreadContext().getHeaders(), request)); return true; } @@ -404,4 +400,14 @@ public class ContextAndHeaderTransportTests extends ESIntegTestCase { return true; } } + + private static class RequestAndHeaders { + final Map headers; + final ActionRequest request; + + private RequestAndHeaders(Map headers, ActionRequest request) { + this.headers = headers; + this.request = request; + } + } } diff --git a/modules/lang-mustache/src/test/java/org/elasticsearch/messy/tests/ContextAndHeaderTransportTests.java b/modules/lang-mustache/src/test/java/org/elasticsearch/messy/tests/ContextAndHeaderTransportTests.java deleted file mode 100644 index 92d15332780..00000000000 --- a/modules/lang-mustache/src/test/java/org/elasticsearch/messy/tests/ContextAndHeaderTransportTests.java +++ /dev/null @@ -1,389 +0,0 @@ -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.elasticsearch.messy.tests; - -import org.elasticsearch.action.Action; -import org.elasticsearch.action.ActionListener; -import org.elasticsearch.action.ActionModule; -import org.elasticsearch.action.ActionRequest; -import org.elasticsearch.action.ActionRequestBuilder; -import org.elasticsearch.action.ActionResponse; -import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder; -import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; -import org.elasticsearch.action.get.GetRequest; -import org.elasticsearch.action.index.IndexRequest; -import org.elasticsearch.action.index.IndexRequestBuilder; -import org.elasticsearch.action.indexedscripts.put.PutIndexedScriptRequest; -import org.elasticsearch.action.indexedscripts.put.PutIndexedScriptResponse; -import org.elasticsearch.action.search.SearchRequestBuilder; -import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.action.support.ActionFilter; -import org.elasticsearch.client.Client; -import org.elasticsearch.client.FilterClient; -import org.elasticsearch.common.inject.AbstractModule; -import org.elasticsearch.common.inject.Inject; -import org.elasticsearch.common.inject.Module; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.common.xcontent.XContentFactory; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.plugins.Plugin; -import org.elasticsearch.script.ScriptService.ScriptType; -import org.elasticsearch.script.Template; -import org.elasticsearch.script.mustache.MustachePlugin; -import org.elasticsearch.script.mustache.MustacheScriptEngineService; -import org.elasticsearch.search.suggest.Suggest; -import org.elasticsearch.search.suggest.SuggestBuilder; -import org.elasticsearch.search.suggest.phrase.PhraseSuggestionBuilder; -import org.elasticsearch.test.ESIntegTestCase; -import org.elasticsearch.test.ESIntegTestCase.ClusterScope; -import org.junit.After; -import org.junit.Before; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; - -import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; -import static org.elasticsearch.common.settings.Settings.settingsBuilder; -import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.elasticsearch.node.Node.HTTP_ENABLED; -import static org.elasticsearch.search.suggest.SuggestBuilders.phraseSuggestion; -import static org.elasticsearch.test.ESIntegTestCase.Scope.SUITE; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures; -import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSuggestionSize; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; - -@ClusterScope(scope = SUITE) -public class ContextAndHeaderTransportTests extends ESIntegTestCase { - private static final List requests = new CopyOnWriteArrayList<>(); - private String randomHeaderKey = randomAsciiOfLength(10); - private String randomHeaderValue = randomAsciiOfLength(20); - private String queryIndex = "query-" + randomAsciiOfLength(10).toLowerCase(Locale.ROOT); - private String lookupIndex = "lookup-" + randomAsciiOfLength(10).toLowerCase(Locale.ROOT); - - @Override - protected Settings nodeSettings(int nodeOrdinal) { - return settingsBuilder() - .put(super.nodeSettings(nodeOrdinal)) - .put("script.indexed", "on") - .put(HTTP_ENABLED, true) - .build(); - } - - @Override - protected Collection> nodePlugins() { - return pluginList(ActionLoggingPlugin.class, MustachePlugin.class); - } - - @Before - public void createIndices() throws Exception { - String mapping = jsonBuilder().startObject().startObject("type") - .startObject("properties") - .startObject("location").field("type", "geo_shape").endObject() - .startObject("name").field("type", "string").endObject() - .endObject() - .endObject().endObject().string(); - - Settings settings = settingsBuilder() - .put(indexSettings()) - .put(SETTING_NUMBER_OF_SHARDS, 1) // A single shard will help to keep the tests repeatable. - .build(); - assertAcked(transportClient().admin().indices().prepareCreate(lookupIndex) - .setSettings(settings).addMapping("type", mapping)); - assertAcked(transportClient().admin().indices().prepareCreate(queryIndex) - .setSettings(settings).addMapping("type", mapping)); - ensureGreen(queryIndex, lookupIndex); - - requests.clear(); - } - - @After - public void checkAllRequestsContainHeaders() { - assertRequestsContainHeader(IndexRequest.class); - assertRequestsContainHeader(RefreshRequest.class); - } - - public void testThatIndexedScriptGetRequestInTemplateQueryContainsContextAndHeaders() throws Exception { - PutIndexedScriptResponse scriptResponse = transportClient() - .preparePutIndexedScript( - MustacheScriptEngineService.NAME, - "my_script", - jsonBuilder().startObject().field("script", "{ \"match\": { \"name\": \"Star Wars\" }}").endObject() - .string()).get(); - assertThat(scriptResponse.isCreated(), is(true)); - - transportClient().prepareIndex(queryIndex, "type", "1") - .setSource(jsonBuilder().startObject().field("name", "Star Wars - The new republic").endObject()).get(); - transportClient().admin().indices().prepareRefresh(queryIndex).get(); - - SearchResponse searchResponse = transportClient() - .prepareSearch(queryIndex) - .setQuery( - QueryBuilders.templateQuery(new Template("my_script", ScriptType.INDEXED, - MustacheScriptEngineService.NAME, null, null))).get(); - assertNoFailures(searchResponse); - assertHitCount(searchResponse, 1); - - assertGetRequestsContainHeaders(".scripts"); - assertRequestsContainHeader(PutIndexedScriptRequest.class); - } - - public void testThatSearchTemplatesWithIndexedTemplatesGetRequestContainsContextAndHeaders() throws Exception { - PutIndexedScriptResponse scriptResponse = transportClient().preparePutIndexedScript(MustacheScriptEngineService.NAME, "the_template", - jsonBuilder().startObject().startObject("template").startObject("query").startObject("match") - .field("name", "{{query_string}}").endObject().endObject().endObject().endObject().string() - ).get(); - assertThat(scriptResponse.isCreated(), is(true)); - - transportClient().prepareIndex(queryIndex, "type", "1") - .setSource(jsonBuilder().startObject().field("name", "Star Wars - The new republic").endObject()) - .get(); - transportClient().admin().indices().prepareRefresh(queryIndex).get(); - - Map params = new HashMap<>(); - params.put("query_string", "star wars"); - - SearchResponse searchResponse = transportClient().prepareSearch(queryIndex).setTemplate(new Template("the_template", ScriptType.INDEXED, MustacheScriptEngineService.NAME, null, params)) - .get(); - - assertNoFailures(searchResponse); - assertHitCount(searchResponse, 1); - - assertGetRequestsContainHeaders(".scripts"); - assertRequestsContainHeader(PutIndexedScriptRequest.class); - } - - public void testThatIndexedScriptGetRequestInPhraseSuggestContainsContextAndHeaders() throws Exception { - CreateIndexRequestBuilder builder = transportClient().admin().indices().prepareCreate("test").setSettings(settingsBuilder() - .put(indexSettings()) - .put(SETTING_NUMBER_OF_SHARDS, 1) // A single shard will help to keep the tests repeatable. - .put("index.analysis.analyzer.text.tokenizer", "standard") - .putArray("index.analysis.analyzer.text.filter", "lowercase", "my_shingle") - .put("index.analysis.filter.my_shingle.type", "shingle") - .put("index.analysis.filter.my_shingle.output_unigrams", true) - .put("index.analysis.filter.my_shingle.min_shingle_size", 2) - .put("index.analysis.filter.my_shingle.max_shingle_size", 3)); - - XContentBuilder mapping = XContentFactory.jsonBuilder() - .startObject() - .startObject("type1") - .startObject("properties") - .startObject("title") - .field("type", "string") - .field("analyzer", "text") - .endObject() - .endObject() - .endObject() - .endObject(); - assertAcked(builder.addMapping("type1", mapping)); - ensureGreen(); - - List titles = new ArrayList<>(); - - titles.add("United States House of Representatives Elections in Washington 2006"); - titles.add("United States House of Representatives Elections in Washington 2005"); - titles.add("State"); - titles.add("Houses of Parliament"); - titles.add("Representative Government"); - titles.add("Election"); - - List builders = new ArrayList<>(); - for (String title: titles) { - transportClient().prepareIndex("test", "type1").setSource("title", title).get(); - } - transportClient().admin().indices().prepareRefresh("test").get(); - - String filterStringAsFilter = XContentFactory.jsonBuilder() - .startObject() - .startObject("match_phrase") - .field("title", "{{suggestion}}") - .endObject() - .endObject() - .string(); - - PutIndexedScriptResponse scriptResponse = transportClient() - .preparePutIndexedScript( - MustacheScriptEngineService.NAME, - "my_script", - jsonBuilder().startObject().field("script", filterStringAsFilter).endObject() - .string()).get(); - assertThat(scriptResponse.isCreated(), is(true)); - - PhraseSuggestionBuilder suggest = phraseSuggestion("title") - .field("title") - .addCandidateGenerator(PhraseSuggestionBuilder.candidateGenerator("title") - .suggestMode("always") - .maxTermFreq(.99f) - .size(10) - .maxInspections(200) - ) - .confidence(0f) - .maxErrors(2f) - .shardSize(30000) - .size(10); - - PhraseSuggestionBuilder filteredFilterSuggest = suggest.collateQuery(new Template("my_script", ScriptType.INDEXED, - MustacheScriptEngineService.NAME, null, null)); - - SearchRequestBuilder searchRequestBuilder = transportClient().prepareSearch("test").setSize(0); - SuggestBuilder suggestBuilder = new SuggestBuilder(); - String suggestText = "united states house of representatives elections in washington 2006"; - if (suggestText != null) { - suggestBuilder.setText(suggestText); - } - suggestBuilder.addSuggestion(filteredFilterSuggest); - searchRequestBuilder.suggest(suggestBuilder); - SearchResponse actionGet = searchRequestBuilder.execute().actionGet(); - assertThat(Arrays.toString(actionGet.getShardFailures()), actionGet.getFailedShards(), equalTo(0)); - Suggest searchSuggest = actionGet.getSuggest(); - - assertSuggestionSize(searchSuggest, 0, 2, "title"); - - assertGetRequestsContainHeaders(".scripts"); - assertRequestsContainHeader(PutIndexedScriptRequest.class); - } - - private List getRequests(Class clazz) { - List results = new ArrayList<>(); - for (ActionRequest request : requests) { - if (request.getClass().equals(clazz)) { - results.add((T) request); - } - } - - return results; - } - - private void assertRequestsContainHeader(Class clazz) { - List classRequests = getRequests(clazz); - for (ActionRequest request : classRequests) { - assertRequestContainsHeader(request); - } - } - - private void assertGetRequestsContainHeaders() { - assertGetRequestsContainHeaders(this.lookupIndex); - } - - private void assertGetRequestsContainHeaders(String index) { - List getRequests = getRequests(GetRequest.class); - assertThat(getRequests, hasSize(greaterThan(0))); - - for (GetRequest request : getRequests) { - if (!request.index().equals(index)) { - continue; - } - assertRequestContainsHeader(request); - } - } - - private void assertRequestContainsHeader(ActionRequest request) { - String msg = String.format(Locale.ROOT, "Expected header %s to be in request %s", randomHeaderKey, request.getClass().getName()); - if (request instanceof IndexRequest) { - IndexRequest indexRequest = (IndexRequest) request; - msg = String.format(Locale.ROOT, "Expected header %s to be in index request %s/%s/%s", randomHeaderKey, - indexRequest.index(), indexRequest.type(), indexRequest.id()); - } - assertThat(msg, request.hasHeader(randomHeaderKey), is(true)); - assertThat(request.getHeader(randomHeaderKey).toString(), is(randomHeaderValue)); - } - - /** - * a transport client that adds our random header - */ - private Client transportClient() { - Client transportClient = internalCluster().transportClient(); - FilterClient filterClient = new FilterClient(transportClient) { - @Override - protected > void doExecute(Action action, Request request, ActionListener listener) { - request.putHeader(randomHeaderKey, randomHeaderValue); - super.doExecute(action, request, listener); - } - }; - - return filterClient; - } - - public static class ActionLoggingPlugin extends Plugin { - - @Override - public String name() { - return "test-action-logging"; - } - - @Override - public String description() { - return "Test action logging"; - } - - @Override - public Collection nodeModules() { - return Collections.singletonList(new ActionLoggingModule()); - } - - public void onModule(ActionModule module) { - module.registerFilter(LoggingFilter.class); - } - } - - public static class ActionLoggingModule extends AbstractModule { - @Override - protected void configure() { - bind(LoggingFilter.class).asEagerSingleton(); - } - - } - - public static class LoggingFilter extends ActionFilter.Simple { - - @Inject - public LoggingFilter(Settings settings) { - super(settings); - } - - @Override - public int order() { - return 999; - } - - @Override - protected boolean apply(String action, ActionRequest request, ActionListener listener) { - requests.add(request); - return true; - } - - @Override - protected boolean apply(String action, ActionResponse response, ActionListener listener) { - return true; - } - } -} diff --git a/plugins/delete-by-query/src/main/java/org/elasticsearch/action/deletebyquery/TransportDeleteByQueryAction.java b/plugins/delete-by-query/src/main/java/org/elasticsearch/action/deletebyquery/TransportDeleteByQueryAction.java index 9fd42ae513a..f4127c4e532 100644 --- a/plugins/delete-by-query/src/main/java/org/elasticsearch/action/deletebyquery/TransportDeleteByQueryAction.java +++ b/plugins/delete-by-query/src/main/java/org/elasticsearch/action/deletebyquery/TransportDeleteByQueryAction.java @@ -110,7 +110,7 @@ public class TransportDeleteByQueryAction extends HandledTransportAction() { + scrollAction.execute(new SearchScrollRequest().scrollId(scrollId).scroll(request.scroll()), new ActionListener() { @Override public void onResponse(SearchResponse scrollResponse) { deleteHits(scrollId, scrollResponse); @@ -202,9 +202,9 @@ public class TransportDeleteByQueryAction extends HandledTransportAction() { @Override @@ -319,10 +319,6 @@ public class TransportDeleteByQueryAction extends HandledTransportAction= (startTime + request.timeout().millis())); } - void addShardFailure(ShardOperationFailedException failure) { - addShardFailures(new ShardOperationFailedException[]{failure}); - } - void addShardFailures(ShardOperationFailedException[] failures) { if (!CollectionUtils.isEmpty(failures)) { ShardOperationFailedException[] duplicates = new ShardOperationFailedException[shardFailures.length + failures.length]; diff --git a/plugins/delete-by-query/src/main/java/org/elasticsearch/rest/action/deletebyquery/RestDeleteByQueryAction.java b/plugins/delete-by-query/src/main/java/org/elasticsearch/rest/action/deletebyquery/RestDeleteByQueryAction.java index 2b8dc02289c..a7146c2a768 100644 --- a/plugins/delete-by-query/src/main/java/org/elasticsearch/rest/action/deletebyquery/RestDeleteByQueryAction.java +++ b/plugins/delete-by-query/src/main/java/org/elasticsearch/rest/action/deletebyquery/RestDeleteByQueryAction.java @@ -49,7 +49,7 @@ public class RestDeleteByQueryAction extends BaseRestHandler { @Inject public RestDeleteByQueryAction(Settings settings, RestController controller, Client client, IndicesQueriesRegistry indicesQueriesRegistry) { - super(settings, controller, client); + super(settings, client); this.indicesQueriesRegistry = indicesQueriesRegistry; controller.registerHandler(DELETE, "/{index}/_query", this); controller.registerHandler(DELETE, "/{index}/{type}/_query", this); 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 81dbc387a14..35ebf4143df 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/InternalTestCluster.java +++ b/test/framework/src/main/java/org/elasticsearch/test/InternalTestCluster.java @@ -61,6 +61,7 @@ import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.EsExecutors; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.discovery.DiscoveryService; import org.elasticsearch.env.NodeEnvironment; import org.elasticsearch.http.HttpServerTransport; @@ -316,7 +317,7 @@ public final class InternalTestCluster extends TestCluster { // always reduce this - it can make tests really slow builder.put(RecoverySettings.INDICES_RECOVERY_RETRY_DELAY_STATE_SYNC_SETTING.getKey(), TimeValue.timeValueMillis(RandomInts.randomIntBetween(random, 20, 50))); defaultSettings = builder.build(); - executor = EsExecutors.newCached("test runner", 0, TimeUnit.SECONDS, EsExecutors.daemonThreadFactory("test_" + clusterName)); + executor = EsExecutors.newCached("test runner", 0, TimeUnit.SECONDS, EsExecutors.daemonThreadFactory("test_" + clusterName), new ThreadContext(Settings.EMPTY)); } public static String configuredNodeMode() { diff --git a/test/framework/src/main/java/org/elasticsearch/test/TestSearchContext.java b/test/framework/src/main/java/org/elasticsearch/test/TestSearchContext.java index 796872bd350..3445895fec1 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/TestSearchContext.java +++ b/test/framework/src/main/java/org/elasticsearch/test/TestSearchContext.java @@ -25,9 +25,6 @@ import org.apache.lucene.search.Sort; import org.apache.lucene.util.Counter; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.cache.recycler.PageCacheRecycler; -import org.elasticsearch.common.HasContext; -import org.elasticsearch.common.HasContextAndHeaders; -import org.elasticsearch.common.HasHeaders; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.util.BigArrays; @@ -98,7 +95,7 @@ public class TestSearchContext extends SearchContext { private final Map subPhaseContexts = new HashMap<>(); public TestSearchContext(ThreadPool threadPool,PageCacheRecycler pageCacheRecycler, BigArrays bigArrays, ScriptService scriptService, IndexService indexService) { - super(ParseFieldMatcher.STRICT, null); + super(ParseFieldMatcher.STRICT); this.pageCacheRecycler = pageCacheRecycler; this.bigArrays = bigArrays.withCircuitBreaking(); this.indexService = indexService; @@ -110,7 +107,7 @@ public class TestSearchContext extends SearchContext { } public TestSearchContext() { - super(ParseFieldMatcher.STRICT, null); + super(ParseFieldMatcher.STRICT); this.pageCacheRecycler = null; this.bigArrays = null; this.indexService = null; @@ -584,73 +581,6 @@ public class TestSearchContext extends SearchContext { throw new UnsupportedOperationException(); } - @Override - public V putInContext(Object key, Object value) { - return null; - } - - @Override - public void putAllInContext(ObjectObjectAssociativeContainer map) { - } - - @Override - public V getFromContext(Object key) { - return null; - } - - @Override - public V getFromContext(Object key, V defaultValue) { - return defaultValue; - } - - @Override - public boolean hasInContext(Object key) { - return false; - } - - @Override - public int contextSize() { - return 0; - } - - @Override - public boolean isContextEmpty() { - return true; - } - - @Override - public ImmutableOpenMap getContext() { - return ImmutableOpenMap.of(); - } - - @Override - public void copyContextFrom(HasContext other) { - } - - @Override - public void putHeader(String key, V value) {} - - @Override - public V getHeader(String key) { - return null; - } - - @Override - public boolean hasHeader(String key) { - return false; - } - - @Override - public Set getHeaders() { - return Collections.emptySet(); - } - - @Override - public void copyHeadersFrom(HasHeaders from) {} - - @Override - public void copyContextAndHeadersFrom(HasContextAndHeaders other) {} - @Override public Profilers getProfilers() { return null; // no profiling diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/FakeRestRequest.java b/test/framework/src/main/java/org/elasticsearch/test/rest/FakeRestRequest.java index a24869b40bd..9b1d55be081 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/FakeRestRequest.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/FakeRestRequest.java @@ -32,14 +32,11 @@ public class FakeRestRequest extends RestRequest { private final Map params; public FakeRestRequest() { - this(new HashMap(), new HashMap()); + this(new HashMap<>()); } - public FakeRestRequest(Map headers, Map context) { + public FakeRestRequest(Map headers) { this.headers = headers; - for (Map.Entry entry : context.entrySet()) { - putInContext(entry.getKey(), entry.getValue()); - } this.params = new HashMap<>(); } @@ -101,4 +98,4 @@ public class FakeRestRequest extends RestRequest { public Map params() { return params; } -} \ No newline at end of file +} diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/client/RestClient.java b/test/framework/src/main/java/org/elasticsearch/test/rest/client/RestClient.java index 63a8b397c45..f21cde40e24 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/client/RestClient.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/client/RestClient.java @@ -30,13 +30,13 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.lucene.util.IOUtils; import org.elasticsearch.Version; -import org.elasticsearch.client.support.Headers; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.PathUtils; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.network.NetworkAddress; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.util.set.Sets; import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; import org.elasticsearch.test.rest.client.http.HttpResponse; @@ -79,17 +79,17 @@ public class RestClient implements Closeable { private final String protocol; private final RestSpec restSpec; private final CloseableHttpClient httpClient; - private final Headers headers; private final InetSocketAddress[] addresses; private final Version esVersion; + private final ThreadContext threadContext; public RestClient(RestSpec restSpec, Settings settings, InetSocketAddress[] addresses) throws IOException, RestException { assert addresses.length > 0; this.restSpec = restSpec; - this.headers = new Headers(settings); this.protocol = settings.get(PROTOCOL, "http"); this.httpClient = createHttpClient(settings); this.addresses = addresses; + this.threadContext = new ThreadContext(settings); this.esVersion = readAndCheckVersion(); logger.info("REST client initialized {}, elasticsearch version: [{}]", addresses, esVersion); } @@ -248,7 +248,7 @@ public class RestClient implements Closeable { protected HttpRequestBuilder httpRequestBuilder(InetSocketAddress address) { return new HttpRequestBuilder(httpClient) - .addHeaders(headers) + .addHeaders(threadContext.getHeaders()) .protocol(protocol) .host(NetworkAddress.formatAddress(address.getAddress())).port(address.getPort()); } diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/client/http/HttpRequestBuilder.java b/test/framework/src/main/java/org/elasticsearch/test/rest/client/http/HttpRequestBuilder.java index e4c8849a92f..6a484e9ae69 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/client/http/HttpRequestBuilder.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/client/http/HttpRequestBuilder.java @@ -27,7 +27,6 @@ import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; -import org.elasticsearch.client.support.Headers; import org.elasticsearch.common.Strings; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; @@ -135,10 +134,8 @@ public class HttpRequestBuilder { } } - public HttpRequestBuilder addHeaders(Headers headers) { - for (String header : headers.headers().names()) { - this.headers.put(header, headers.headers().get(header)); - } + public HttpRequestBuilder addHeaders(Map headers) { + this.headers.putAll(headers); return this; }