diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
index 5ea58046f49..53e964188f6 100644
--- a/.github/ISSUE_TEMPLATE.md
+++ b/.github/ISSUE_TEMPLATE.md
@@ -3,7 +3,11 @@ GitHub is reserved for bug reports and feature requests. The best place
to ask a general question is at the Elastic Discourse forums at
https://discuss.elastic.co. If you are in fact posting a bug report or
a feature request, please include one and only one of the below blocks
-in your new issue.
+in your new issue. Note that whether you're filing a bug report or a
+feature request, ensure that your submission is for an
+[OS that we support](https://www.elastic.co/support/matrix#show_os).
+Bug reports on an OS that we do not support or feature requests
+specific to an OS that we do not support will be closed.
-->
+
+
+
+
waiting for 3 nodes to be up");
- assertBusy(new Runnable() {
- @Override
- public void run() {
- NodesStatsResponse resp = client().admin().cluster().prepareNodesStats().get();
- assertThat(resp.getNodes().size(), equalTo(3));
- }
+ assertBusy(() -> {
+ NodesStatsResponse resp = client().admin().cluster().prepareNodesStats().get();
+ assertThat(resp.getNodes().size(), equalTo(3));
});
logger.info("--> creating 'test' index");
- prepareCreate("test").setSettings(Settings.builder()
+ assertAcked(prepareCreate("test").setSettings(Settings.builder()
.put(UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING.getKey(), "1m")
.put(IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 5)
- .put(IndexMetaData.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 1)).get();
- ensureGreen("test");
+ .put(IndexMetaData.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 1))
+ .setWaitForActiveShards(ActiveShardCount.ALL).get());
logger.info("--> stopping a random node");
assertTrue(internalCluster().stopRandomDataNode());
@@ -92,6 +90,7 @@ public final class ClusterAllocationExplainIT extends ESIntegTestCase {
.setSettings(Settings.builder()
.put("index.number_of_shards", 5)
.put("index.number_of_replicas", 1))
+ .setWaitForActiveShards(ActiveShardCount.ALL) // wait on all shards
.get();
client().admin().indices().prepareCreate("only-baz")
@@ -99,6 +98,7 @@ public final class ClusterAllocationExplainIT extends ESIntegTestCase {
.put("index.routing.allocation.include.bar", "baz")
.put("index.number_of_shards", 5)
.put("index.number_of_replicas", 1))
+ .setWaitForActiveShards(ActiveShardCount.ALL)
.get();
client().admin().indices().prepareCreate("only-foo")
@@ -108,9 +108,6 @@ public final class ClusterAllocationExplainIT extends ESIntegTestCase {
.put("index.number_of_replicas", 1))
.get();
- ensureGreen("anywhere", "only-baz");
- ensureYellow("only-foo");
-
ClusterAllocationExplainResponse resp = client().admin().cluster().prepareAllocationExplain()
.setIndex("only-foo")
.setShard(0)
@@ -126,7 +123,6 @@ public final class ClusterAllocationExplainIT extends ESIntegTestCase {
Map explanations = cae.getNodeExplanations();
- Float noAttrWeight = -1f;
Float barAttrWeight = -1f;
Float fooBarAttrWeight = -1f;
for (Map.Entry entry : explanations.entrySet()) {
@@ -134,7 +130,6 @@ public final class ClusterAllocationExplainIT extends ESIntegTestCase {
String nodeName = node.getName();
NodeExplanation explanation = entry.getValue();
ClusterAllocationExplanation.FinalDecision finalDecision = explanation.getFinalDecision();
- String finalExplanation = explanation.getFinalExplanation();
ClusterAllocationExplanation.StoreCopy storeCopy = explanation.getStoreCopy();
Decision d = explanation.getDecision();
float weight = explanation.getWeight();
@@ -143,7 +138,6 @@ public final class ClusterAllocationExplainIT extends ESIntegTestCase {
assertEquals(d.type(), Decision.Type.NO);
if (noAttrNode.equals(nodeName)) {
assertThat(d.toString(), containsString("node does not match index include filters [foo:\"bar\"]"));
- noAttrWeight = weight;
assertNull(storeStatus);
assertEquals("the shard cannot be assigned because one or more allocation decider returns a 'NO' decision",
explanation.getFinalExplanation());
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainRequestTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainRequestTests.java
new file mode 100644
index 00000000000..926de8b253e
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainRequestTests.java
@@ -0,0 +1,44 @@
+/*
+ * 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.action.admin.cluster.allocation;
+
+import org.elasticsearch.common.io.stream.BytesStreamOutput;
+import org.elasticsearch.test.ESTestCase;
+
+public class ClusterAllocationExplainRequestTests extends ESTestCase {
+
+ public void testSerialization() throws Exception {
+ ClusterAllocationExplainRequest request =
+ new ClusterAllocationExplainRequest(randomAsciiOfLength(4), randomIntBetween(0, Integer.MAX_VALUE), randomBoolean());
+ request.includeYesDecisions(randomBoolean());
+ request.includeDiskInfo(randomBoolean());
+ BytesStreamOutput output = new BytesStreamOutput();
+ request.writeTo(output);
+
+ ClusterAllocationExplainRequest actual = new ClusterAllocationExplainRequest();
+ actual.readFrom(output.bytes().streamInput());
+ assertEquals(request.getIndex(), actual.getIndex());
+ assertEquals(request.getShard(), actual.getShard());
+ assertEquals(request.isPrimary(), actual.isPrimary());
+ assertEquals(request.includeYesDecisions(), actual.includeYesDecisions());
+ assertEquals(request.includeDiskInfo(), actual.includeDiskInfo());
+ }
+
+}
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainTests.java
index d5cefc6d1f3..895450e6d5b 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainTests.java
@@ -32,7 +32,6 @@ public final class ClusterAllocationExplainTests extends ESSingleNodeTestCase {
public void testShardExplain() throws Exception {
client().admin().indices().prepareCreate("test")
.setSettings("index.number_of_shards", 1, "index.number_of_replicas", 1).get();
- client().admin().cluster().health(Requests.clusterHealthRequest("test").waitForYellowStatus()).get();
ClusterAllocationExplainResponse resp = client().admin().cluster().prepareAllocationExplain()
.setIndex("test").setShard(0).setPrimary(false).get();
@@ -47,7 +46,6 @@ public final class ClusterAllocationExplainTests extends ESSingleNodeTestCase {
NodeExplanation explanation = cae.getNodeExplanations().values().iterator().next();
ClusterAllocationExplanation.FinalDecision fd = explanation.getFinalDecision();
ClusterAllocationExplanation.StoreCopy storeCopy = explanation.getStoreCopy();
- String finalExplanation = explanation.getFinalExplanation();
Decision d = explanation.getDecision();
assertNotNull("should have a decision", d);
assertEquals(Decision.Type.NO, d.type());
@@ -76,7 +74,6 @@ public final class ClusterAllocationExplainTests extends ESSingleNodeTestCase {
d = explanation.getDecision();
fd = explanation.getFinalDecision();
storeCopy = explanation.getStoreCopy();
- finalExplanation = explanation.getFinalExplanation();
assertNotNull("should have a decision", d);
assertEquals(Decision.Type.NO, d.type());
assertEquals(ClusterAllocationExplanation.FinalDecision.ALREADY_ASSIGNED, fd);
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplanationTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplanationTests.java
index d0e8ef14d01..425edeb1065 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplanationTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplanationTests.java
@@ -31,7 +31,7 @@ import org.elasticsearch.cluster.routing.allocation.decider.Decision;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
@@ -41,7 +41,6 @@ import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
-import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@@ -66,7 +65,7 @@ public final class ClusterAllocationExplanationTests extends ESTestCase {
.numberOfShards(1)
.numberOfReplicas(1)
.build();
- private DiscoveryNode node = new DiscoveryNode("node-0", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ private DiscoveryNode node = new DiscoveryNode("node-0", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT);
private static Decision.Multi yesDecision = new Decision.Multi();
private static Decision.Multi noDecision = new Decision.Multi();
@@ -202,10 +201,10 @@ public final class ClusterAllocationExplanationTests extends ESTestCase {
yesDecision, nodeWeight, storeStatus, "", activeAllocationIds, false);
nodeExplanations.put(ne.getNode(), ne);
ClusterAllocationExplanation cae = new ClusterAllocationExplanation(shard, true,
- "assignedNode", allocationDelay, remainingDelay, null, false, nodeExplanations);
+ "assignedNode", allocationDelay, remainingDelay, null, false, nodeExplanations, null);
BytesStreamOutput out = new BytesStreamOutput();
cae.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
ClusterAllocationExplanation cae2 = new ClusterAllocationExplanation(in);
assertEquals(shard, cae2.getShard());
assertTrue(cae2.isPrimary());
@@ -215,9 +214,7 @@ public final class ClusterAllocationExplanationTests extends ESTestCase {
assertEquals(allocationDelay, cae2.getAllocationDelayMillis());
assertEquals(remainingDelay, cae2.getRemainingDelayMillis());
for (Map.Entry entry : cae2.getNodeExplanations().entrySet()) {
- DiscoveryNode node = entry.getKey();
NodeExplanation explanation = entry.getValue();
- IndicesShardStoresResponse.StoreStatus status = explanation.getStoreStatus();
assertNotNull(explanation.getStoreStatus());
assertNotNull(explanation.getDecision());
assertEquals(nodeWeight, explanation.getWeight());
@@ -240,7 +237,7 @@ public final class ClusterAllocationExplanationTests extends ESTestCase {
Map nodeExplanations = new HashMap<>(1);
nodeExplanations.put(ne.getNode(), ne);
ClusterAllocationExplanation cae = new ClusterAllocationExplanation(shardId, true,
- "assignedNode", 42, 42, null, false, nodeExplanations);
+ "assignedNode", 42, 42, null, false, nodeExplanations, null);
XContentBuilder builder = XContentFactory.jsonBuilder();
cae.toXContent(builder, ToXContent.EMPTY_PARAMS);
assertEquals("{\"shard\":{\"index\":\"foo\",\"index_uuid\":\"uuid\",\"id\":0,\"primary\":true},\"assigned\":true," +
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthResponsesTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthResponsesTests.java
index 704c1348b7e..d0d452df478 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthResponsesTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthResponsesTests.java
@@ -84,7 +84,7 @@ public class ClusterHealthResponsesTests extends ESTestCase {
if (randomBoolean()) {
BytesStreamOutput out = new BytesStreamOutput();
clusterHealth.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
clusterHealth = ClusterHealthResponse.readResponseFrom(in);
}
return clusterHealth;
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/CancellableTasksTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/CancellableTasksTests.java
index 594028f4e6f..9027b3d372e 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/CancellableTasksTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/CancellableTasksTests.java
@@ -230,7 +230,7 @@ public class CancellableTasksTests extends TaskManagerTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
throwableReference.set(e);
responseLatch.countDown();
}
@@ -308,7 +308,7 @@ public class CancellableTasksTests extends TaskManagerTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
throwableReference.set(e);
responseLatch.countDown();
}
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TasksIT.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TasksIT.java
index 6f8e3fda156..d479af2b1be 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TasksIT.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TasksIT.java
@@ -98,6 +98,11 @@ public class TasksIT extends ESIntegTestCase {
private Map, RecordingTaskManagerListener> listeners = new HashMap<>();
+ @Override
+ protected boolean addMockTransportService() {
+ return false;
+ }
+
@Override
protected Collection> nodePlugins() {
return pluginList(MockTransportService.TestPlugin.class, TestTaskPlugin.class);
@@ -738,12 +743,12 @@ public class TasksIT extends ESIntegTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
throw new RuntimeException(e);
}
});
b.await();
-
+
// Now we can find it!
GetTaskResponse response = expectFinishedTask(new TaskId("fake:1"));
assertEquals("test", response.getTask().getTask().getAction());
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java
index c4d49d899b9..2c78786ab04 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java
@@ -249,7 +249,7 @@ public class TransportTasksActionTests extends TaskManagerTestCase {
/**
* Test class for testing task operations
*/
- static abstract class TestTasksAction extends TransportTasksAction {
+ abstract static class TestTasksAction extends TransportTasksAction {
protected TestTasksAction(Settings settings, String actionName, ThreadPool threadPool,
ClusterService clusterService, TransportService transportService) {
@@ -338,7 +338,7 @@ public class TransportTasksActionTests extends TaskManagerTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
logger.warn("Couldn't get list of tasks", e);
responseLatch.countDown();
}
@@ -526,7 +526,7 @@ public class TransportTasksActionTests extends TaskManagerTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
responseLatch.countDown();
}
});
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java
index b736751b781..4f553dfb88a 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java
@@ -166,7 +166,7 @@ public class ClusterRerouteRequestTests extends ESTestCase {
private ClusterRerouteRequest roundTripThroughBytes(ClusterRerouteRequest original) throws IOException {
try (BytesStreamOutput output = new BytesStreamOutput()) {
original.writeTo(output);
- try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) {
+ try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry)) {
ClusterRerouteRequest copy = new ClusterRerouteRequest();
copy.readFrom(in);
return copy;
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteTests.java
index 00fcbf60a5a..657fec558b8 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteTests.java
@@ -66,7 +66,7 @@ public class ClusterRerouteTests extends ESAllocationTestCase {
BytesReference bytes = out.bytes();
NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry();
new NetworkModule(null, Settings.EMPTY, true, namedWriteableRegistry);
- StreamInput wrap = new NamedWriteableAwareStreamInput(StreamInput.wrap(bytes.toBytes()),
+ StreamInput wrap = new NamedWriteableAwareStreamInput(bytes.streamInput(),
namedWriteableRegistry);
ClusterRerouteRequest deserializedReq = new ClusterRerouteRequest();
deserializedReq.readFrom(wrap);
@@ -94,7 +94,7 @@ public class ClusterRerouteTests extends ESAllocationTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
}
};
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/state/ClusterStateRequestTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/state/ClusterStateRequestTests.java
index fc04de81254..b515829b72a 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/state/ClusterStateRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/state/ClusterStateRequestTests.java
@@ -45,7 +45,7 @@ public class ClusterStateRequestTests extends ESTestCase {
output.setVersion(testVersion);
clusterStateRequest.writeTo(output);
- StreamInput streamInput = StreamInput.wrap(output.bytes());
+ StreamInput streamInput = output.bytes().streamInput();
streamInput.setVersion(testVersion);
ClusterStateRequest deserializedCSRequest = new ClusterStateRequest();
deserializedCSRequest.readFrom(streamInput);
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/stats/ClusterStatsIT.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/stats/ClusterStatsIT.java
index 0a63dd46095..f2ed690bb9c 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/stats/ClusterStatsIT.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/stats/ClusterStatsIT.java
@@ -120,7 +120,7 @@ public class ClusterStatsIT extends ESIntegTestCase {
assertThat(response.getStatus(), Matchers.equalTo(ClusterHealthStatus.GREEN));
prepareCreate("test1").setSettings("number_of_shards", 2, "number_of_replicas", 1).get();
- ensureYellow();
+
response = client().admin().cluster().prepareClusterStats().get();
assertThat(response.getStatus(), Matchers.equalTo(ClusterHealthStatus.YELLOW));
assertThat(response.indicesStats.getDocs().getCount(), Matchers.equalTo(0L));
@@ -161,12 +161,7 @@ public class ClusterStatsIT extends ESIntegTestCase {
public void testValuesSmokeScreen() throws IOException, ExecutionException, InterruptedException {
internalCluster().startNodesAsync(randomIntBetween(1, 3)).get();
index("test1", "type", "1", "f", "f");
- /*
- * Ensure at least one shard is allocated otherwise the FS stats might
- * return 0. This happens if the File#getTotalSpace() and friends is called
- * on a directory that doesn't exist or has not yet been created.
- */
- ensureYellow("test1");
+
ClusterStatsResponse response = client().admin().cluster().prepareClusterStats().get();
String msg = response.toString();
assertThat(msg, response.getTimestamp(), Matchers.greaterThan(946681200000L)); // 1 Jan 2000
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestTests.java
index e4c2849b907..2e9239a2c3b 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestTests.java
@@ -37,7 +37,7 @@ public class GetStoredScriptRequestTests extends ESTestCase {
out.setVersion(randomVersion(random()));
request.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
in.setVersion(out.getVersion());
GetStoredScriptRequest request2 = new GetStoredScriptRequest();
request2.readFrom(in);
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/TransportAnalyzeActionTests.java b/core/src/test/java/org/elasticsearch/action/admin/indices/TransportAnalyzeActionTests.java
index 5e2c503eba1..24edbf47a2d 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/TransportAnalyzeActionTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/TransportAnalyzeActionTests.java
@@ -73,7 +73,8 @@ public class TransportAnalyzeActionTests extends ESTestCase {
request.analyzer(null);
request.tokenizer("whitespace");
- request.tokenFilters("lowercase", "word_delimiter");
+ request.addTokenFilter("lowercase");
+ request.addTokenFilter("word_delimiter");
request.text("the qu1ck brown fox");
analyze = TransportAnalyzeAction.analyze(request, AllFieldMapper.NAME, null, randomBoolean() ? analysisService : null, registry, environment);
tokens = analyze.getTokens();
@@ -84,8 +85,9 @@ public class TransportAnalyzeActionTests extends ESTestCase {
request.analyzer(null);
request.tokenizer("whitespace");
- request.charFilters("html_strip");
- request.tokenFilters("lowercase", "word_delimiter");
+ request.addCharFilter("html_strip");
+ request.addTokenFilter("lowercase");
+ request.addTokenFilter("word_delimiter");
request.text("the qu1ck brown fox
");
analyze = TransportAnalyzeAction.analyze(request, AllFieldMapper.NAME, null, randomBoolean() ? analysisService : null, registry, environment);
tokens = analyze.getTokens();
@@ -155,7 +157,8 @@ public class TransportAnalyzeActionTests extends ESTestCase {
request.analyzer(null);
request.tokenizer("whitespace");
- request.tokenFilters("lowercase", "wordDelimiter");
+ request.addTokenFilter("lowercase");
+ request.addTokenFilter("wordDelimiter");
request.text("the qu1ck brown fox-dog");
analyze = TransportAnalyzeAction.analyze(request, AllFieldMapper.NAME, null, analysisService, registry, environment);
tokens = analyze.getTokens();
@@ -211,7 +214,7 @@ public class TransportAnalyzeActionTests extends ESTestCase {
try {
AnalyzeRequest request = new AnalyzeRequest();
request.tokenizer("whitespace");
- request.tokenFilters("foobar");
+ request.addTokenFilter("foobar");
request.text("the qu1ck brown fox");
TransportAnalyzeAction.analyze(request, AllFieldMapper.NAME, null, notGlobal ? analysisService : null, registry, environment);
fail("no such analyzer");
@@ -226,8 +229,8 @@ public class TransportAnalyzeActionTests extends ESTestCase {
try {
AnalyzeRequest request = new AnalyzeRequest();
request.tokenizer("whitespace");
- request.tokenFilters("lowercase");
- request.charFilters("foobar");
+ request.addTokenFilter("lowercase");
+ request.addCharFilter("foobar");
request.text("the qu1ck brown fox");
TransportAnalyzeAction.analyze(request, AllFieldMapper.NAME, null, notGlobal ? analysisService : null, registry, environment);
fail("no such analyzer");
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/create/CreateIndexIT.java b/core/src/test/java/org/elasticsearch/action/admin/indices/create/CreateIndexIT.java
index 3e7323dceeb..7231bee0bef 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/create/CreateIndexIT.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/create/CreateIndexIT.java
@@ -25,6 +25,7 @@ import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteResponse;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.search.SearchResponse;
+import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.cluster.ClusterInfoService;
import org.elasticsearch.cluster.ClusterState;
@@ -41,14 +42,11 @@ import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
-import org.elasticsearch.node.service.NodeService;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope;
-import org.junit.Ignore;
import java.util.HashMap;
-import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
@@ -232,7 +230,7 @@ public class CreateIndexIT extends ESIntegTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
throw new RuntimeException(e);
}
}
@@ -292,7 +290,7 @@ public class CreateIndexIT extends ESIntegTestCase {
public void testRestartIndexCreationAfterFullClusterRestart() throws Exception {
client().admin().cluster().prepareUpdateSettings().setTransientSettings(Settings.builder().put("cluster.routing.allocation.enable",
"none")).get();
- client().admin().indices().prepareCreate("test").setSettings(indexSettings()).get();
+ client().admin().indices().prepareCreate("test").setWaitForActiveShards(ActiveShardCount.NONE).setSettings(indexSettings()).get();
internalCluster().fullRestart();
ensureGreen("test");
}
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/flush/SyncedFlushUnitTests.java b/core/src/test/java/org/elasticsearch/action/admin/indices/flush/SyncedFlushUnitTests.java
index 04f6037f64b..7040c92ec1d 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/flush/SyncedFlushUnitTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/flush/SyncedFlushUnitTests.java
@@ -84,7 +84,7 @@ public class SyncedFlushUnitTests extends ESTestCase {
assertThat(testPlan.result.restStatus(), equalTo(testPlan.totalCounts.failed > 0 ? RestStatus.CONFLICT : RestStatus.OK));
BytesStreamOutput out = new BytesStreamOutput();
testPlan.result.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
SyncedFlushResponse readResponse = new SyncedFlushResponse();
readResponse.readFrom(in);
assertThat(readResponse.totalShards(), equalTo(testPlan.totalCounts.total));
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/rollover/TransportRolloverActionTests.java b/core/src/test/java/org/elasticsearch/action/admin/indices/rollover/TransportRolloverActionTests.java
index 7d163630afb..8a4a62f9728 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/rollover/TransportRolloverActionTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/rollover/TransportRolloverActionTests.java
@@ -22,6 +22,7 @@ package org.elasticsearch.action.admin.indices.rollover;
import org.elasticsearch.Version;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesClusterStateUpdateRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest;
+import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.cluster.metadata.AliasAction;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.cluster.metadata.IndexMetaData;
@@ -166,6 +167,8 @@ public class TransportRolloverActionTests extends ESTestCase {
String alias = randomAsciiOfLength(10);
String rolloverIndex = randomAsciiOfLength(10);
final RolloverRequest rolloverRequest = new RolloverRequest(alias, randomAsciiOfLength(10));
+ final ActiveShardCount activeShardCount = randomBoolean() ? ActiveShardCount.ALL : ActiveShardCount.ONE;
+ rolloverRequest.setWaitForActiveShards(activeShardCount);
final Settings settings = Settings.builder()
.put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
.put(IndexMetaData.SETTING_INDEX_UUID, UUIDs.randomBase64UUID())
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoreRequestIT.java b/core/src/test/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoreRequestIT.java
index 6e3e5d76224..1cd1704e164 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoreRequestIT.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoreRequestIT.java
@@ -215,7 +215,7 @@ public class IndicesShardStoreRequestIT extends ESIntegTestCase {
client().admin().indices().prepareFlush().setForce(true).setWaitIfOngoing(true).execute().actionGet();
}
- private final static class IndexNodePredicate implements Predicate {
+ private static final class IndexNodePredicate implements Predicate {
private final Set nodesWithShard;
public IndexNodePredicate(String index) {
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoreResponseTests.java b/core/src/test/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoreResponseTests.java
index 3c12d7d9b10..9705009a044 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoreResponseTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoreResponseTests.java
@@ -26,7 +26,7 @@ import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.ImmutableOpenIntMap;
import org.elasticsearch.common.collect.ImmutableOpenMap;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
@@ -53,8 +53,8 @@ public class IndicesShardStoreResponseTests extends ESTestCase {
List failures = new ArrayList<>();
ImmutableOpenIntMap.Builder> storeStatuses = ImmutableOpenIntMap.builder();
- DiscoveryNode node1 = new DiscoveryNode("node1", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
- DiscoveryNode node2 = new DiscoveryNode("node2", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ DiscoveryNode node1 = new DiscoveryNode("node1", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT);
+ DiscoveryNode node2 = new DiscoveryNode("node2", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT);
List storeStatusList = new ArrayList<>();
storeStatusList.add(new IndicesShardStoresResponse.StoreStatus(node1, 3, null, IndicesShardStoresResponse.StoreStatus.AllocationStatus.PRIMARY, null));
storeStatusList.add(new IndicesShardStoresResponse.StoreStatus(node2, ShardStateMetaData.NO_VERSION, UUIDs.randomBase64UUID(), IndicesShardStoresResponse.StoreStatus.AllocationStatus.REPLICA, null));
@@ -122,7 +122,7 @@ public class IndicesShardStoreResponseTests extends ESTestCase {
}
public void testStoreStatusOrdering() throws Exception {
- DiscoveryNode node1 = new DiscoveryNode("node1", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ DiscoveryNode node1 = new DiscoveryNode("node1", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT);
List orderedStoreStatuses = new ArrayList<>();
orderedStoreStatuses.add(new IndicesShardStoresResponse.StoreStatus(node1, ShardStateMetaData.NO_VERSION, UUIDs.randomBase64UUID(), IndicesShardStoresResponse.StoreStatus.AllocationStatus.PRIMARY, null));
orderedStoreStatuses.add(new IndicesShardStoresResponse.StoreStatus(node1, ShardStateMetaData.NO_VERSION, UUIDs.randomBase64UUID(), IndicesShardStoresResponse.StoreStatus.AllocationStatus.REPLICA, null));
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/shrink/TransportShrinkActionTests.java b/core/src/test/java/org/elasticsearch/action/admin/indices/shrink/TransportShrinkActionTests.java
index d78374d446f..3fcade05839 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/shrink/TransportShrinkActionTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/shrink/TransportShrinkActionTests.java
@@ -22,6 +22,7 @@ package org.elasticsearch.action.admin.indices.shrink;
import org.apache.lucene.index.IndexWriter;
import org.elasticsearch.Version;
import org.elasticsearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest;
+import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.EmptyClusterInfoService;
@@ -38,7 +39,7 @@ import org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllo
import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders;
import org.elasticsearch.cluster.routing.allocation.decider.MaxRetryAllocationDecider;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.index.shard.DocsStats;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.gateway.NoopGatewayAllocator;
@@ -130,6 +131,8 @@ public class TransportShrinkActionTests extends ESTestCase {
int numSourceShards = clusterState.metaData().index(indexName).getNumberOfShards();
DocsStats stats = new DocsStats(randomIntBetween(0, (IndexWriter.MAX_DOCS) / numSourceShards), randomIntBetween(1, 1000));
ShrinkRequest target = new ShrinkRequest("target", indexName);
+ final ActiveShardCount activeShardCount = randomBoolean() ? ActiveShardCount.ALL : ActiveShardCount.ONE;
+ target.setWaitForActiveShards(activeShardCount);
CreateIndexClusterStateUpdateRequest request = TransportShrinkAction.prepareCreateIndexRequest(
target, clusterState, (i) -> stats,
new IndexNameExpressionResolver(Settings.EMPTY));
@@ -137,10 +140,11 @@ public class TransportShrinkActionTests extends ESTestCase {
assertEquals(indexName, request.shrinkFrom().getName());
assertEquals("1", request.settings().get("index.number_of_shards"));
assertEquals("shrink_index", request.cause());
+ assertEquals(request.waitForActiveShards(), activeShardCount);
}
private DiscoveryNode newNode(String nodeId) {
- return new DiscoveryNode(nodeId, DummyTransportAddress.INSTANCE, emptyMap(),
+ return new DiscoveryNode(nodeId, LocalTransportAddress.buildUnique(), emptyMap(),
Collections.unmodifiableSet(new HashSet<>(Arrays.asList(DiscoveryNode.Role.MASTER, DiscoveryNode.Role.DATA))), Version.CURRENT);
}
}
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/stats/IndicesStatsTests.java b/core/src/test/java/org/elasticsearch/action/admin/indices/stats/IndicesStatsTests.java
index 726dccee597..dfc10169e70 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/stats/IndicesStatsTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/stats/IndicesStatsTests.java
@@ -19,6 +19,7 @@
package org.elasticsearch.action.admin.indices.stats;
+import org.elasticsearch.action.ShardOperationFailedException;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.engine.CommitStats;
@@ -26,6 +27,8 @@ import org.elasticsearch.index.engine.SegmentsStats;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.test.ESSingleNodeTestCase;
+import java.util.List;
+
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasKey;
@@ -108,4 +111,12 @@ public class IndicesStatsTests extends ESSingleNodeTestCase {
}
}
+ /**
+ * Gives access to package private IndicesStatsResponse constructor for test purpose.
+ **/
+ public static IndicesStatsResponse newIndicesStatsResponse(ShardStats[] shards, int totalShards, int successfulShards,
+ int failedShards, List shardFailures) {
+ return new IndicesStatsResponse(shards, totalShards, successfulShards, failedShards, shardFailures);
+ }
+
}
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/template/put/MetaDataIndexTemplateServiceTests.java b/core/src/test/java/org/elasticsearch/action/admin/indices/template/put/MetaDataIndexTemplateServiceTests.java
index d62fe30f6fa..8493c58729d 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/template/put/MetaDataIndexTemplateServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/template/put/MetaDataIndexTemplateServiceTests.java
@@ -19,7 +19,6 @@
package org.elasticsearch.action.admin.indices.template.put;
-import org.elasticsearch.Version;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.cluster.metadata.AliasValidator;
import org.elasticsearch.cluster.metadata.IndexMetaData;
@@ -161,7 +160,7 @@ public class MetaDataIndexTemplateServiceTests extends ESSingleNodeTestCase {
null,
new HashSet<>(),
null,
- null, null);
+ null, null, null);
MetaDataIndexTemplateService service = new MetaDataIndexTemplateService(Settings.EMPTY, null, createIndexService, new AliasValidator(Settings.EMPTY), null, null);
final List throwables = new ArrayList<>();
@@ -172,8 +171,8 @@ public class MetaDataIndexTemplateServiceTests extends ESSingleNodeTestCase {
}
@Override
- public void onFailure(Throwable t) {
- throwables.add(t);
+ public void onFailure(Exception e) {
+ throwables.add(e);
}
});
return throwables;
@@ -192,6 +191,7 @@ public class MetaDataIndexTemplateServiceTests extends ESSingleNodeTestCase {
new HashSet<>(),
null,
nodeServicesProvider,
+ null,
null);
MetaDataIndexTemplateService service = new MetaDataIndexTemplateService(
Settings.EMPTY, clusterService, createIndexService, new AliasValidator(Settings.EMPTY), indicesService, nodeServicesProvider);
@@ -205,8 +205,8 @@ public class MetaDataIndexTemplateServiceTests extends ESSingleNodeTestCase {
}
@Override
- public void onFailure(Throwable t) {
- throwables.add(t);
+ public void onFailure(Exception e) {
+ throwables.add(e);
latch.countDown();
}
});
diff --git a/core/src/test/java/org/elasticsearch/action/bulk/BackoffPolicyTests.java b/core/src/test/java/org/elasticsearch/action/bulk/BackoffPolicyTests.java
new file mode 100644
index 00000000000..e3cfeb2a4ac
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/action/bulk/BackoffPolicyTests.java
@@ -0,0 +1,65 @@
+/*
+ * 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.action.bulk;
+
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.test.ESTestCase;
+
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.elasticsearch.common.unit.TimeValue.timeValueMillis;
+
+public class BackoffPolicyTests extends ESTestCase {
+ public void testWrapBackoffPolicy() {
+ TimeValue timeValue = timeValueMillis(between(0, Integer.MAX_VALUE));
+ int maxNumberOfRetries = between(1, 1000);
+ BackoffPolicy policy = BackoffPolicy.constantBackoff(timeValue, maxNumberOfRetries);
+ AtomicInteger retries = new AtomicInteger();
+ policy = BackoffPolicy.wrap(policy, retries::getAndIncrement);
+
+ int expectedRetries = 0;
+ {
+ // Fetching the iterator doesn't call the callback
+ Iterator itr = policy.iterator();
+ assertEquals(expectedRetries, retries.get());
+
+ while (itr.hasNext()) {
+ // hasNext doesn't trigger the callback
+ assertEquals(expectedRetries, retries.get());
+ // next does
+ itr.next();
+ expectedRetries += 1;
+ assertEquals(expectedRetries, retries.get());
+ }
+ // next doesn't call the callback when there isn't a backoff available
+ expectThrows(NoSuchElementException.class, () -> itr.next());
+ assertEquals(expectedRetries, retries.get());
+ }
+ {
+ // The second iterator also calls the callback
+ Iterator itr = policy.iterator();
+ itr.next();
+ expectedRetries += 1;
+ assertEquals(expectedRetries, retries.get());
+ }
+ }
+}
diff --git a/core/src/test/java/org/elasticsearch/action/bulk/BulkProcessorIT.java b/core/src/test/java/org/elasticsearch/action/bulk/BulkProcessorIT.java
index e5cabd417b8..6bac7c2f8a4 100644
--- a/core/src/test/java/org/elasticsearch/action/bulk/BulkProcessorIT.java
+++ b/core/src/test/java/org/elasticsearch/action/bulk/BulkProcessorIT.java
@@ -25,7 +25,6 @@ import org.elasticsearch.action.get.MultiGetRequestBuilder;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Client;
-import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeUnit;
@@ -33,6 +32,7 @@ import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.Environment;
import org.elasticsearch.test.ESIntegTestCase;
+import org.elasticsearch.transport.MockTransportClient;
import java.util.Arrays;
import java.util.HashSet;
@@ -159,7 +159,7 @@ public class BulkProcessorIT extends ESIntegTestCase {
Settings settings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
- Client transportClient = TransportClient.builder().settings(settings).build();
+ Client transportClient = new MockTransportClient(settings);
int bulkActions = randomIntBetween(10, 100);
int numDocs = randomIntBetween(bulkActions, bulkActions + 100);
diff --git a/core/src/test/java/org/elasticsearch/action/bulk/BulkRequestTests.java b/core/src/test/java/org/elasticsearch/action/bulk/BulkRequestTests.java
index 337f881d41b..142fb282c20 100644
--- a/core/src/test/java/org/elasticsearch/action/bulk/BulkRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/bulk/BulkRequestTests.java
@@ -55,9 +55,9 @@ public class BulkRequestTests extends ESTestCase {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, null);
assertThat(bulkRequest.numberOfActions(), equalTo(3));
- assertThat(((IndexRequest) bulkRequest.requests().get(0)).source().toBytes(), equalTo(new BytesArray("{ \"field1\" : \"value1\" }").toBytes()));
+ assertThat(((IndexRequest) bulkRequest.requests().get(0)).source(), equalTo(new BytesArray("{ \"field1\" : \"value1\" }")));
assertThat(bulkRequest.requests().get(1), instanceOf(DeleteRequest.class));
- assertThat(((IndexRequest) bulkRequest.requests().get(2)).source().toBytes(), equalTo(new BytesArray("{ \"field1\" : \"value3\" }").toBytes()));
+ assertThat(((IndexRequest) bulkRequest.requests().get(2)).source(), equalTo(new BytesArray("{ \"field1\" : \"value3\" }")));
}
public void testSimpleBulk2() throws Exception {
@@ -81,7 +81,7 @@ public class BulkRequestTests extends ESTestCase {
assertThat(bulkRequest.numberOfActions(), equalTo(4));
assertThat(((UpdateRequest) bulkRequest.requests().get(0)).id(), equalTo("1"));
assertThat(((UpdateRequest) bulkRequest.requests().get(0)).retryOnConflict(), equalTo(2));
- assertThat(((UpdateRequest) bulkRequest.requests().get(0)).doc().source().toUtf8(), equalTo("{\"field\":\"value\"}"));
+ assertThat(((UpdateRequest) bulkRequest.requests().get(0)).doc().source().utf8ToString(), equalTo("{\"field\":\"value\"}"));
assertThat(((UpdateRequest) bulkRequest.requests().get(1)).id(), equalTo("0"));
assertThat(((UpdateRequest) bulkRequest.requests().get(1)).type(), equalTo("type1"));
assertThat(((UpdateRequest) bulkRequest.requests().get(1)).index(), equalTo("index1"));
@@ -93,7 +93,7 @@ public class BulkRequestTests extends ESTestCase {
assertThat(scriptParams, notNullValue());
assertThat(scriptParams.size(), equalTo(1));
assertThat(((Integer) scriptParams.get("param1")), equalTo(1));
- assertThat(((UpdateRequest) bulkRequest.requests().get(1)).upsertRequest().source().toUtf8(), equalTo("{\"counter\":1}"));
+ assertThat(((UpdateRequest) bulkRequest.requests().get(1)).upsertRequest().source().utf8ToString(), equalTo("{\"counter\":1}"));
}
public void testBulkAllowExplicitIndex() throws Exception {
diff --git a/core/src/test/java/org/elasticsearch/action/bulk/BulkShardRequestTests.java b/core/src/test/java/org/elasticsearch/action/bulk/BulkShardRequestTests.java
index b26d2531ff0..bb406366d25 100644
--- a/core/src/test/java/org/elasticsearch/action/bulk/BulkShardRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/bulk/BulkShardRequestTests.java
@@ -29,11 +29,11 @@ public class BulkShardRequestTests extends ESTestCase {
public void testToString() {
String index = randomSimpleString(random(), 10);
int count = between(1, 100);
- BulkShardRequest r = new BulkShardRequest(null, new ShardId(index, "ignored", 0), RefreshPolicy.NONE, new BulkItemRequest[count]);
+ BulkShardRequest r = new BulkShardRequest(new ShardId(index, "ignored", 0), RefreshPolicy.NONE, new BulkItemRequest[count]);
assertEquals("BulkShardRequest to [" + index + "] containing [" + count + "] requests", r.toString());
- r = new BulkShardRequest(null, new ShardId(index, "ignored", 0), RefreshPolicy.IMMEDIATE, new BulkItemRequest[count]);
+ r = new BulkShardRequest(new ShardId(index, "ignored", 0), RefreshPolicy.IMMEDIATE, new BulkItemRequest[count]);
assertEquals("BulkShardRequest to [" + index + "] containing [" + count + "] requests and a refresh", r.toString());
- r = new BulkShardRequest(null, new ShardId(index, "ignored", 0), RefreshPolicy.WAIT_UNTIL, new BulkItemRequest[count]);
+ r = new BulkShardRequest(new ShardId(index, "ignored", 0), RefreshPolicy.WAIT_UNTIL, new BulkItemRequest[count]);
assertEquals("BulkShardRequest to [" + index + "] containing [" + count + "] requests blocking until refresh", r.toString());
}
}
diff --git a/core/src/test/java/org/elasticsearch/action/bulk/RetryTests.java b/core/src/test/java/org/elasticsearch/action/bulk/RetryTests.java
index 6d9987394f9..4fa640b3adc 100644
--- a/core/src/test/java/org/elasticsearch/action/bulk/RetryTests.java
+++ b/core/src/test/java/org/elasticsearch/action/bulk/RetryTests.java
@@ -149,7 +149,7 @@ public class RetryTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
this.lastFailure = e;
latch.countDown();
}
diff --git a/core/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTookTests.java b/core/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTookTests.java
index 6ae7559ba62..7c39adc76f6 100644
--- a/core/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTookTests.java
+++ b/core/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTookTests.java
@@ -59,7 +59,7 @@ import static org.hamcrest.Matchers.greaterThanOrEqualTo;
public class TransportBulkActionTookTests extends ESTestCase {
- static private ThreadPool threadPool;
+ private static ThreadPool threadPool;
private ClusterService clusterService;
@BeforeClass
@@ -201,7 +201,7 @@ public class TransportBulkActionTookTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
}
});
diff --git a/core/src/test/java/org/elasticsearch/action/get/MultiGetShardRequestTests.java b/core/src/test/java/org/elasticsearch/action/get/MultiGetShardRequestTests.java
index 451ade62584..ef259463139 100644
--- a/core/src/test/java/org/elasticsearch/action/get/MultiGetShardRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/get/MultiGetShardRequestTests.java
@@ -70,7 +70,7 @@ public class MultiGetShardRequestTests extends ESTestCase {
out.setVersion(randomVersion(random()));
multiGetShardRequest.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
in.setVersion(out.getVersion());
MultiGetShardRequest multiGetShardRequest2 = new MultiGetShardRequest();
multiGetShardRequest2.readFrom(in);
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/BulkRequestModifierTests.java b/core/src/test/java/org/elasticsearch/action/ingest/BulkRequestModifierTests.java
index 3286c07e06c..9ee5036131d 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/BulkRequestModifierTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/BulkRequestModifierTests.java
@@ -111,7 +111,7 @@ public class BulkRequestModifierTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
}
});
@@ -157,7 +157,7 @@ public class BulkRequestModifierTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
}
public BulkResponse getResponse() {
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/IngestProxyActionFilterTests.java b/core/src/test/java/org/elasticsearch/action/ingest/IngestProxyActionFilterTests.java
index a62946bf0f6..3d1a1a1c69d 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/IngestProxyActionFilterTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/IngestProxyActionFilterTests.java
@@ -33,7 +33,7 @@ import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.service.ClusterService;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.VersionUtils;
@@ -78,7 +78,7 @@ public class IngestProxyActionFilterTests extends ESTestCase {
if (i < ingestNodes) {
roles.add(DiscoveryNode.Role.INGEST);
}
- DiscoveryNode node = new DiscoveryNode(nodeId, nodeId, DummyTransportAddress.INSTANCE, attributes, roles, VersionUtils.randomVersion(random()));
+ DiscoveryNode node = new DiscoveryNode(nodeId, nodeId, LocalTransportAddress.buildUnique(), attributes, roles, VersionUtils.randomVersion(random()));
builder.put(node);
if (i == totalNodes - 1) {
localNode = node;
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/SimulateDocumentSimpleResultTests.java b/core/src/test/java/org/elasticsearch/action/ingest/SimulateDocumentSimpleResultTests.java
index 323a8c0aaa6..544e2932b44 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/SimulateDocumentSimpleResultTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/SimulateDocumentSimpleResultTests.java
@@ -45,7 +45,7 @@ public class SimulateDocumentSimpleResultTests extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
simulateDocumentBaseResult.writeTo(out);
- StreamInput streamInput = StreamInput.wrap(out.bytes());
+ StreamInput streamInput = out.bytes().streamInput();
SimulateDocumentBaseResult otherSimulateDocumentBaseResult = new SimulateDocumentBaseResult(streamInput);
if (isFailure) {
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/SimulateExecutionServiceTests.java b/core/src/test/java/org/elasticsearch/action/ingest/SimulateExecutionServiceTests.java
index 5806d8c312b..5b3551b24d1 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/SimulateExecutionServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/SimulateExecutionServiceTests.java
@@ -160,7 +160,24 @@ public class SimulateExecutionServiceTests extends ESTestCase {
}
public void testExecuteVerboseItemExceptionWithIgnoreFailure() throws Exception {
- TestProcessor testProcessor = new TestProcessor("processor_0", "mock", ingestDocument -> { throw new RuntimeException("processor failed"); });
+ RuntimeException exception = new RuntimeException("processor failed");
+ TestProcessor testProcessor = new TestProcessor("processor_0", "mock", ingestDocument -> { throw exception; });
+ CompoundProcessor processor = new CompoundProcessor(true, Collections.singletonList(testProcessor), Collections.emptyList());
+ Pipeline pipeline = new Pipeline("_id", "_description", new CompoundProcessor(processor));
+ SimulateDocumentResult actualItemResponse = executionService.executeDocument(pipeline, ingestDocument, true);
+ assertThat(testProcessor.getInvokedCounter(), equalTo(1));
+ assertThat(actualItemResponse, instanceOf(SimulateDocumentVerboseResult.class));
+ SimulateDocumentVerboseResult simulateDocumentVerboseResult = (SimulateDocumentVerboseResult) actualItemResponse;
+ assertThat(simulateDocumentVerboseResult.getProcessorResults().size(), equalTo(1));
+ assertThat(simulateDocumentVerboseResult.getProcessorResults().get(0).getProcessorTag(), equalTo("processor_0"));
+ assertThat(simulateDocumentVerboseResult.getProcessorResults().get(0).getFailure(), sameInstance(exception));
+ assertThat(simulateDocumentVerboseResult.getProcessorResults().get(0).getIngestDocument(), not(sameInstance(ingestDocument)));
+ assertIngestDocument(simulateDocumentVerboseResult.getProcessorResults().get(0).getIngestDocument(), ingestDocument);
+ assertThat(simulateDocumentVerboseResult.getProcessorResults().get(0).getIngestDocument().getSourceAndMetadata(), not(sameInstance(ingestDocument.getSourceAndMetadata())));
+ }
+
+ public void testExecuteVerboseItemWithoutExceptionAndWithIgnoreFailure() throws Exception {
+ TestProcessor testProcessor = new TestProcessor("processor_0", "mock", ingestDocument -> { });
CompoundProcessor processor = new CompoundProcessor(true, Collections.singletonList(testProcessor), Collections.emptyList());
Pipeline pipeline = new Pipeline("_id", "_description", new CompoundProcessor(processor));
SimulateDocumentResult actualItemResponse = executionService.executeDocument(pipeline, ingestDocument, true);
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/SimulatePipelineRequestParsingTests.java b/core/src/test/java/org/elasticsearch/action/ingest/SimulatePipelineRequestParsingTests.java
index fa4bdc6525d..8418c886be9 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/SimulatePipelineRequestParsingTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/SimulatePipelineRequestParsingTests.java
@@ -19,19 +19,6 @@
package org.elasticsearch.action.ingest;
-import org.elasticsearch.cluster.service.ClusterService;
-import org.elasticsearch.ingest.PipelineStore;
-import org.elasticsearch.ingest.ProcessorsRegistry;
-import org.elasticsearch.ingest.TestProcessor;
-import org.elasticsearch.ingest.TestTemplateService;
-import org.elasticsearch.ingest.CompoundProcessor;
-import org.elasticsearch.ingest.IngestDocument;
-import org.elasticsearch.ingest.Pipeline;
-import org.elasticsearch.ingest.Processor;
-import org.elasticsearch.script.ScriptService;
-import org.elasticsearch.test.ESTestCase;
-import org.junit.Before;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
@@ -40,6 +27,15 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import org.elasticsearch.ingest.CompoundProcessor;
+import org.elasticsearch.ingest.IngestDocument;
+import org.elasticsearch.ingest.Pipeline;
+import org.elasticsearch.ingest.PipelineStore;
+import org.elasticsearch.ingest.Processor;
+import org.elasticsearch.ingest.TestProcessor;
+import org.elasticsearch.test.ESTestCase;
+import org.junit.Before;
+
import static org.elasticsearch.action.ingest.SimulatePipelineRequest.Fields;
import static org.elasticsearch.action.ingest.SimulatePipelineRequest.SIMULATED_PIPELINE_ID;
import static org.elasticsearch.ingest.IngestDocument.MetaData.ID;
@@ -59,12 +55,11 @@ public class SimulatePipelineRequestParsingTests extends ESTestCase {
TestProcessor processor = new TestProcessor(ingestDocument -> {});
CompoundProcessor pipelineCompoundProcessor = new CompoundProcessor(processor);
Pipeline pipeline = new Pipeline(SIMULATED_PIPELINE_ID, null, pipelineCompoundProcessor);
- ProcessorsRegistry.Builder processorRegistryBuilder = new ProcessorsRegistry.Builder();
- processorRegistryBuilder.registerProcessor("mock_processor", ((registry) -> mock(Processor.Factory.class)));
- ProcessorsRegistry processorRegistry = processorRegistryBuilder.build(mock(ScriptService.class), mock(ClusterService.class));
+ Map registry =
+ Collections.singletonMap("mock_processor", (factories, tag, config) -> processor);
store = mock(PipelineStore.class);
when(store.get(SIMULATED_PIPELINE_ID)).thenReturn(pipeline);
- when(store.getProcessorRegistry()).thenReturn(processorRegistry);
+ when(store.getProcessorFactories()).thenReturn(registry);
}
public void testParseUsingPipelineStore() throws Exception {
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/SimulatePipelineResponseTests.java b/core/src/test/java/org/elasticsearch/action/ingest/SimulatePipelineResponseTests.java
index 1376ca4280e..576e8e01724 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/SimulatePipelineResponseTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/SimulatePipelineResponseTests.java
@@ -73,7 +73,7 @@ public class SimulatePipelineResponseTests extends ESTestCase {
SimulatePipelineResponse response = new SimulatePipelineResponse(randomAsciiOfLengthBetween(1, 10), isVerbose, results);
BytesStreamOutput out = new BytesStreamOutput();
response.writeTo(out);
- StreamInput streamInput = StreamInput.wrap(out.bytes());
+ StreamInput streamInput = out.bytes().streamInput();
SimulatePipelineResponse otherResponse = new SimulatePipelineResponse();
otherResponse.readFrom(streamInput);
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/SimulateProcessorResultTests.java b/core/src/test/java/org/elasticsearch/action/ingest/SimulateProcessorResultTests.java
index f612f36c9d6..f6ffc035342 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/SimulateProcessorResultTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/SimulateProcessorResultTests.java
@@ -37,27 +37,39 @@ public class SimulateProcessorResultTests extends ESTestCase {
public void testSerialization() throws IOException {
String processorTag = randomAsciiOfLengthBetween(1, 10);
- boolean isFailure = randomBoolean();
+ boolean isSuccessful = randomBoolean();
+ boolean isIgnoredException = randomBoolean();
SimulateProcessorResult simulateProcessorResult;
- if (isFailure) {
- simulateProcessorResult = new SimulateProcessorResult(processorTag, new IllegalArgumentException("test"));
- } else {
+ if (isSuccessful) {
IngestDocument ingestDocument = RandomDocumentPicks.randomIngestDocument(random());
- simulateProcessorResult = new SimulateProcessorResult(processorTag, ingestDocument);
+ if (isIgnoredException) {
+ simulateProcessorResult = new SimulateProcessorResult(processorTag, ingestDocument, new IllegalArgumentException("test"));
+ } else {
+ simulateProcessorResult = new SimulateProcessorResult(processorTag, ingestDocument);
+ }
+ } else {
+ simulateProcessorResult = new SimulateProcessorResult(processorTag, new IllegalArgumentException("test"));
}
BytesStreamOutput out = new BytesStreamOutput();
simulateProcessorResult.writeTo(out);
- StreamInput streamInput = StreamInput.wrap(out.bytes());
+ StreamInput streamInput = out.bytes().streamInput();
SimulateProcessorResult otherSimulateProcessorResult = new SimulateProcessorResult(streamInput);
assertThat(otherSimulateProcessorResult.getProcessorTag(), equalTo(simulateProcessorResult.getProcessorTag()));
- if (isFailure) {
- assertThat(simulateProcessorResult.getIngestDocument(), is(nullValue()));
+ if (isSuccessful) {
+ assertIngestDocument(otherSimulateProcessorResult.getIngestDocument(), simulateProcessorResult.getIngestDocument());
+ if (isIgnoredException) {
+ assertThat(otherSimulateProcessorResult.getFailure(), instanceOf(IllegalArgumentException.class));
+ IllegalArgumentException e = (IllegalArgumentException) otherSimulateProcessorResult.getFailure();
+ assertThat(e.getMessage(), equalTo("test"));
+ } else {
+ assertThat(otherSimulateProcessorResult.getFailure(), nullValue());
+ }
+ } else {
+ assertThat(otherSimulateProcessorResult.getIngestDocument(), is(nullValue()));
assertThat(otherSimulateProcessorResult.getFailure(), instanceOf(IllegalArgumentException.class));
IllegalArgumentException e = (IllegalArgumentException) otherSimulateProcessorResult.getFailure();
assertThat(e.getMessage(), equalTo("test"));
- } else {
- assertIngestDocument(otherSimulateProcessorResult.getIngestDocument(), simulateProcessorResult.getIngestDocument());
}
}
}
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/TrackingResultProcessorTests.java b/core/src/test/java/org/elasticsearch/action/ingest/TrackingResultProcessorTests.java
index 5b0a0599090..999cbe435f2 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/TrackingResultProcessorTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/TrackingResultProcessorTests.java
@@ -39,6 +39,7 @@ import static org.elasticsearch.ingest.CompoundProcessor.ON_FAILURE_PROCESSOR_TY
import static org.elasticsearch.action.ingest.TrackingResultProcessor.decorate;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
+import static org.hamcrest.Matchers.sameInstance;
public class TrackingResultProcessorTests extends ESTestCase {
@@ -142,7 +143,7 @@ public class TrackingResultProcessorTests extends ESTestCase {
assertThat(testProcessor.getInvokedCounter(), equalTo(1));
assertThat(resultList.size(), equalTo(1));
assertThat(resultList.get(0).getIngestDocument(), equalTo(expectedResult.getIngestDocument()));
- assertThat(resultList.get(0).getFailure(), nullValue());
+ assertThat(resultList.get(0).getFailure(), sameInstance(exception));
assertThat(resultList.get(0).getProcessorTag(), equalTo(expectedResult.getProcessorTag()));
}
}
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/WritePipelineResponseTests.java b/core/src/test/java/org/elasticsearch/action/ingest/WritePipelineResponseTests.java
index 3f252c37072..00327603ba8 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/WritePipelineResponseTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/WritePipelineResponseTests.java
@@ -35,7 +35,7 @@ public class WritePipelineResponseTests extends ESTestCase {
response = new WritePipelineResponse(isAcknowledged);
BytesStreamOutput out = new BytesStreamOutput();
response.writeTo(out);
- StreamInput streamInput = StreamInput.wrap(out.bytes());
+ StreamInput streamInput = out.bytes().streamInput();
WritePipelineResponse otherResponse = new WritePipelineResponse();
otherResponse.readFrom(streamInput);
@@ -46,7 +46,7 @@ public class WritePipelineResponseTests extends ESTestCase {
WritePipelineResponse response = new WritePipelineResponse();
BytesStreamOutput out = new BytesStreamOutput();
response.writeTo(out);
- StreamInput streamInput = StreamInput.wrap(out.bytes());
+ StreamInput streamInput = out.bytes().streamInput();
WritePipelineResponse otherResponse = new WritePipelineResponse();
otherResponse.readFrom(streamInput);
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/WriteableIngestDocumentTests.java b/core/src/test/java/org/elasticsearch/action/ingest/WriteableIngestDocumentTests.java
index a7ce842913d..b4908846e97 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/WriteableIngestDocumentTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/WriteableIngestDocumentTests.java
@@ -112,7 +112,7 @@ public class WriteableIngestDocumentTests extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
writeableIngestDocument.writeTo(out);
- StreamInput streamInput = StreamInput.wrap(out.bytes());
+ StreamInput streamInput = out.bytes().streamInput();
WriteableIngestDocument otherWriteableIngestDocument = new WriteableIngestDocument(streamInput);
assertIngestDocument(otherWriteableIngestDocument.getIngestDocument(), writeableIngestDocument.getIngestDocument());
}
diff --git a/core/src/test/java/org/elasticsearch/action/main/MainActionTests.java b/core/src/test/java/org/elasticsearch/action/main/MainActionTests.java
index 2bff71d3c40..a8c550e01c5 100644
--- a/core/src/test/java/org/elasticsearch/action/main/MainActionTests.java
+++ b/core/src/test/java/org/elasticsearch/action/main/MainActionTests.java
@@ -64,7 +64,7 @@ public class MainActionTests extends ESTestCase {
BytesStreamOutput streamOutput = new BytesStreamOutput();
mainResponse.writeTo(streamOutput);
final MainResponse serialized = new MainResponse();
- serialized.readFrom(new ByteBufferStreamInput(ByteBuffer.wrap(streamOutput.bytes().toBytes())));
+ serialized.readFrom(streamOutput.bytes().streamInput());
assertThat(serialized.getNodeName(), equalTo(nodeName));
assertThat(serialized.getClusterName(), equalTo(clusterName));
@@ -121,7 +121,7 @@ public class MainActionTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
logger.error("unexpected error", e);
}
});
diff --git a/core/src/test/java/org/elasticsearch/action/search/MultiSearchRequestTests.java b/core/src/test/java/org/elasticsearch/action/search/MultiSearchRequestTests.java
index f0f03347773..690f49171a6 100644
--- a/core/src/test/java/org/elasticsearch/action/search/MultiSearchRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/search/MultiSearchRequestTests.java
@@ -142,7 +142,7 @@ public class MultiSearchRequestTests extends ESTestCase {
private IndicesQueriesRegistry registry() {
IndicesQueriesRegistry registry = new IndicesQueriesRegistry();
QueryParser parser = MatchAllQueryBuilder::fromXContent;
- registry.register(parser, MatchAllQueryBuilder.QUERY_NAME_FIELD);
+ registry.register(parser, MatchAllQueryBuilder.NAME);
return registry;
}
}
diff --git a/core/src/test/java/org/elasticsearch/action/search/SearchRequestBuilderTests.java b/core/src/test/java/org/elasticsearch/action/search/SearchRequestBuilderTests.java
index 9cef4d46e8b..eb2f4b6904d 100644
--- a/core/src/test/java/org/elasticsearch/action/search/SearchRequestBuilderTests.java
+++ b/core/src/test/java/org/elasticsearch/action/search/SearchRequestBuilderTests.java
@@ -20,12 +20,12 @@
package org.elasticsearch.action.search;
import org.elasticsearch.client.Client;
-import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.test.ESTestCase;
+import org.elasticsearch.transport.MockTransportClient;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@@ -41,7 +41,7 @@ public class SearchRequestBuilderTests extends ESTestCase {
Settings settings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
- client = TransportClient.builder().settings(settings).build();
+ client = new MockTransportClient(settings);
}
@AfterClass
diff --git a/core/src/test/java/org/elasticsearch/action/search/TransportSearchIT.java b/core/src/test/java/org/elasticsearch/action/search/TransportSearchIT.java
index 240b26b9287..b3c695e881d 100644
--- a/core/src/test/java/org/elasticsearch/action/search/TransportSearchIT.java
+++ b/core/src/test/java/org/elasticsearch/action/search/TransportSearchIT.java
@@ -37,7 +37,6 @@ public class TransportSearchIT extends ESIntegTestCase {
.setSettings(IndexMetaData.SETTING_NUMBER_OF_SHARDS, numPrimaries1));
assertAcked(prepareCreate("test2")
.setSettings(IndexMetaData.SETTING_NUMBER_OF_SHARDS, numPrimaries2));
- ensureYellow("test1", "test2");
// no exception
client().prepareSearch("test1").get();
diff --git a/core/src/test/java/org/elasticsearch/action/support/ActiveShardCountTests.java b/core/src/test/java/org/elasticsearch/action/support/ActiveShardCountTests.java
new file mode 100644
index 00000000000..83f0b1332c7
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/action/support/ActiveShardCountTests.java
@@ -0,0 +1,305 @@
+/*
+ * 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.action.support;
+
+import com.carrotsearch.hppc.cursors.ObjectCursor;
+import org.elasticsearch.Version;
+import org.elasticsearch.cluster.ClusterName;
+import org.elasticsearch.cluster.ClusterState;
+import org.elasticsearch.cluster.metadata.IndexMetaData;
+import org.elasticsearch.cluster.metadata.MetaData;
+import org.elasticsearch.cluster.routing.IndexRoutingTable;
+import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
+import org.elasticsearch.cluster.routing.RoutingTable;
+import org.elasticsearch.cluster.routing.ShardRouting;
+import org.elasticsearch.common.UUIDs;
+import org.elasticsearch.common.io.stream.ByteBufferStreamInput;
+import org.elasticsearch.common.io.stream.BytesStreamOutput;
+import org.elasticsearch.test.ESTestCase;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+
+import static org.hamcrest.Matchers.equalTo;
+
+/**
+ * Tests for the {@link ActiveShardCount} class
+ */
+public class ActiveShardCountTests extends ESTestCase {
+
+ public void testFromIntValue() {
+ assertSame(ActiveShardCount.from(0), ActiveShardCount.NONE);
+ final int value = randomIntBetween(1, 50);
+ IndexMetaData indexMetaData = IndexMetaData.builder("test")
+ .settings(settings(Version.CURRENT))
+ .numberOfShards(1)
+ .numberOfReplicas(0)
+ .build();
+ assertEquals(ActiveShardCount.from(value).resolve(indexMetaData), value);
+ expectThrows(IllegalArgumentException.class, () -> ActiveShardCount.from(randomIntBetween(-10, -1)));
+ }
+
+ public void testResolve() {
+ // one shard
+ IndexMetaData indexMetaData = IndexMetaData.builder("test")
+ .settings(settings(Version.CURRENT))
+ .numberOfShards(1)
+ .numberOfReplicas(0)
+ .build();
+ assertThat(ActiveShardCount.ALL.resolve(indexMetaData), equalTo(1));
+ assertThat(ActiveShardCount.DEFAULT.resolve(indexMetaData), equalTo(1));
+ assertThat(ActiveShardCount.NONE.resolve(indexMetaData), equalTo(0));
+ final int value = randomIntBetween(2, 20);
+ assertThat(ActiveShardCount.from(value).resolve(indexMetaData), equalTo(value));
+
+ // more than one shard
+ final int numNewShards = randomIntBetween(1, 20);
+ indexMetaData = IndexMetaData.builder("test")
+ .settings(settings(Version.CURRENT))
+ .numberOfShards(1)
+ .numberOfReplicas(numNewShards)
+ .build();
+ assertThat(ActiveShardCount.ALL.resolve(indexMetaData), equalTo(numNewShards + 1));
+ assertThat(ActiveShardCount.DEFAULT.resolve(indexMetaData), equalTo(1));
+ assertThat(ActiveShardCount.NONE.resolve(indexMetaData), equalTo(0));
+ assertThat(ActiveShardCount.from(value).resolve(indexMetaData), equalTo(value));
+ }
+
+ public void testSerialization() throws IOException {
+ doWriteRead(ActiveShardCount.ALL);
+ doWriteRead(ActiveShardCount.DEFAULT);
+ doWriteRead(ActiveShardCount.NONE);
+ doWriteRead(ActiveShardCount.from(randomIntBetween(1, 50)));
+ }
+
+ public void testParseString() {
+ assertSame(ActiveShardCount.parseString("all"), ActiveShardCount.ALL);
+ assertSame(ActiveShardCount.parseString(null), ActiveShardCount.DEFAULT);
+ assertSame(ActiveShardCount.parseString("0"), ActiveShardCount.NONE);
+ int value = randomIntBetween(1, 50);
+ assertEquals(ActiveShardCount.parseString(value + ""), ActiveShardCount.from(value));
+ expectThrows(IllegalArgumentException.class, () -> ActiveShardCount.parseString(randomAsciiOfLengthBetween(4, 8)));
+ expectThrows(IllegalArgumentException.class, () -> ActiveShardCount.parseString("-1")); // magic numbers not exposed through API
+ expectThrows(IllegalArgumentException.class, () -> ActiveShardCount.parseString("-2"));
+ expectThrows(IllegalArgumentException.class, () -> ActiveShardCount.parseString(randomIntBetween(-10, -3) + ""));
+ }
+
+ private void doWriteRead(ActiveShardCount activeShardCount) throws IOException {
+ final BytesStreamOutput out = new BytesStreamOutput();
+ activeShardCount.writeTo(out);
+ final ByteBufferStreamInput in = new ByteBufferStreamInput(ByteBuffer.wrap(out.bytes().toBytesRef().bytes));
+ ActiveShardCount readActiveShardCount = ActiveShardCount.readFrom(in);
+ if (activeShardCount == ActiveShardCount.DEFAULT
+ || activeShardCount == ActiveShardCount.ALL
+ || activeShardCount == ActiveShardCount.NONE) {
+ assertSame(activeShardCount, readActiveShardCount);
+ } else {
+ assertEquals(activeShardCount, readActiveShardCount);
+ }
+ }
+
+ public void testEnoughShardsActiveZero() {
+ final String indexName = "test-idx";
+ final int numberOfShards = randomIntBetween(1, 5);
+ final int numberOfReplicas = randomIntBetween(4, 7);
+ final ActiveShardCount waitForActiveShards = ActiveShardCount.from(0);
+ ClusterState clusterState = initializeWithNewIndex(indexName, numberOfShards, numberOfReplicas);
+ assertTrue(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startPrimaries(clusterState, indexName);
+ assertTrue(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startLessThanWaitOnShards(clusterState, indexName, waitForActiveShards);
+ assertTrue(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startWaitOnShards(clusterState, indexName, waitForActiveShards);
+ assertTrue(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startAllShards(clusterState, indexName);
+ assertTrue(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ }
+
+ public void testEnoughShardsActiveLevelOne() {
+ runTestForOneActiveShard(ActiveShardCount.ONE);
+ }
+
+ public void testEnoughShardsActiveLevelDefault() {
+ // default is 1
+ runTestForOneActiveShard(ActiveShardCount.DEFAULT);
+ }
+
+ public void testEnoughShardsActiveRandom() {
+ final String indexName = "test-idx";
+ final int numberOfShards = randomIntBetween(1, 5);
+ final int numberOfReplicas = randomIntBetween(4, 7);
+ final ActiveShardCount waitForActiveShards = ActiveShardCount.from(randomIntBetween(2, numberOfReplicas));
+ ClusterState clusterState = initializeWithNewIndex(indexName, numberOfShards, numberOfReplicas);
+ assertFalse(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startPrimaries(clusterState, indexName);
+ assertFalse(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startLessThanWaitOnShards(clusterState, indexName, waitForActiveShards);
+ assertFalse(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startWaitOnShards(clusterState, indexName, waitForActiveShards);
+ assertTrue(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startAllShards(clusterState, indexName);
+ assertTrue(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ }
+
+ public void testEnoughShardsActiveLevelAll() {
+ final String indexName = "test-idx";
+ final int numberOfShards = randomIntBetween(1, 5);
+ final int numberOfReplicas = randomIntBetween(4, 7);
+ // both values should represent "all"
+ final ActiveShardCount waitForActiveShards = randomBoolean() ? ActiveShardCount.from(numberOfReplicas + 1) : ActiveShardCount.ALL;
+ ClusterState clusterState = initializeWithNewIndex(indexName, numberOfShards, numberOfReplicas);
+ assertFalse(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startPrimaries(clusterState, indexName);
+ assertFalse(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startLessThanWaitOnShards(clusterState, indexName, waitForActiveShards);
+ assertFalse(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startAllShards(clusterState, indexName);
+ assertTrue(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ }
+
+ private void runTestForOneActiveShard(final ActiveShardCount activeShardCount) {
+ final String indexName = "test-idx";
+ final int numberOfShards = randomIntBetween(1, 5);
+ final int numberOfReplicas = randomIntBetween(4, 7);
+ assert activeShardCount == ActiveShardCount.ONE || activeShardCount == ActiveShardCount.DEFAULT;
+ final ActiveShardCount waitForActiveShards = activeShardCount;
+ ClusterState clusterState = initializeWithNewIndex(indexName, numberOfShards, numberOfReplicas);
+ assertFalse(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startPrimaries(clusterState, indexName);
+ assertTrue(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startLessThanWaitOnShards(clusterState, indexName, waitForActiveShards);
+ assertTrue(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startWaitOnShards(clusterState, indexName, waitForActiveShards);
+ assertTrue(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ clusterState = startAllShards(clusterState, indexName);
+ assertTrue(waitForActiveShards.enoughShardsActive(clusterState, indexName));
+ }
+
+ private ClusterState initializeWithNewIndex(final String indexName, final int numShards, final int numReplicas) {
+ // initial index creation and new routing table info
+ final IndexMetaData indexMetaData = IndexMetaData.builder(indexName)
+ .settings(settings(Version.CURRENT)
+ .put(IndexMetaData.SETTING_INDEX_UUID, UUIDs.randomBase64UUID()))
+ .numberOfShards(numShards)
+ .numberOfReplicas(numReplicas)
+ .build();
+ final MetaData metaData = MetaData.builder().put(indexMetaData, true).build();
+ final RoutingTable routingTable = RoutingTable.builder().addAsNew(indexMetaData).build();
+ return ClusterState.builder(new ClusterName("test_cluster")).metaData(metaData).routingTable(routingTable).build();
+ }
+
+ private ClusterState startPrimaries(final ClusterState clusterState, final String indexName) {
+ RoutingTable routingTable = clusterState.routingTable();
+ IndexRoutingTable indexRoutingTable = routingTable.index(indexName);
+ IndexRoutingTable.Builder newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
+ for (final ObjectCursor shardEntry : indexRoutingTable.getShards().values()) {
+ final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
+ for (ShardRouting shardRouting : shardRoutingTable.getShards()) {
+ if (shardRouting.primary()) {
+ shardRouting = shardRouting.initialize(randomAsciiOfLength(8), null, shardRouting.getExpectedShardSize())
+ .moveToStarted();
+ }
+ newIndexRoutingTable.addShard(shardRouting);
+ }
+ }
+ routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
+ return ClusterState.builder(clusterState).routingTable(routingTable).build();
+ }
+
+ private ClusterState startLessThanWaitOnShards(final ClusterState clusterState, final String indexName,
+ final ActiveShardCount waitForActiveShards) {
+ RoutingTable routingTable = clusterState.routingTable();
+ IndexRoutingTable indexRoutingTable = routingTable.index(indexName);
+ IndexRoutingTable.Builder newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
+ for (final ObjectCursor shardEntry : indexRoutingTable.getShards().values()) {
+ final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
+ assert shardRoutingTable.getSize() > 2;
+ // want less than half, and primary is already started
+ int numToStart = waitForActiveShards.resolve(clusterState.metaData().index(indexName)) - 2;
+ for (ShardRouting shardRouting : shardRoutingTable.getShards()) {
+ if (shardRouting.primary()) {
+ assertTrue(shardRouting.active());
+ } else {
+ if (numToStart > 0) {
+ shardRouting = shardRouting.initialize(randomAsciiOfLength(8), null, shardRouting.getExpectedShardSize())
+ .moveToStarted();
+ numToStart--;
+ }
+ }
+ newIndexRoutingTable.addShard(shardRouting);
+ }
+ }
+ routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
+ return ClusterState.builder(clusterState).routingTable(routingTable).build();
+ }
+
+ private ClusterState startWaitOnShards(final ClusterState clusterState, final String indexName,
+ final ActiveShardCount waitForActiveShards) {
+ RoutingTable routingTable = clusterState.routingTable();
+ IndexRoutingTable indexRoutingTable = routingTable.index(indexName);
+ IndexRoutingTable.Builder newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
+ for (final ObjectCursor shardEntry : indexRoutingTable.getShards().values()) {
+ final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
+ assert shardRoutingTable.getSize() > 2;
+ int numToStart = waitForActiveShards.resolve(clusterState.metaData().index(indexName)) - 1; // primary is already started
+ for (ShardRouting shardRouting : shardRoutingTable.getShards()) {
+ if (shardRouting.primary()) {
+ assertTrue(shardRouting.active());
+ } else {
+ if (shardRouting.active() == false) {
+ if (numToStart > 0) {
+ shardRouting = shardRouting.initialize(randomAsciiOfLength(8), null, shardRouting.getExpectedShardSize())
+ .moveToStarted();
+ numToStart--;
+ }
+ } else {
+ numToStart--;
+ }
+ }
+ newIndexRoutingTable.addShard(shardRouting);
+ }
+ }
+ routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
+ return ClusterState.builder(clusterState).routingTable(routingTable).build();
+ }
+
+ private ClusterState startAllShards(final ClusterState clusterState, final String indexName) {
+ RoutingTable routingTable = clusterState.routingTable();
+ IndexRoutingTable indexRoutingTable = routingTable.index(indexName);
+ IndexRoutingTable.Builder newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
+ for (final ObjectCursor shardEntry : indexRoutingTable.getShards().values()) {
+ final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
+ for (ShardRouting shardRouting : shardRoutingTable.getShards()) {
+ if (shardRouting.primary()) {
+ assertTrue(shardRouting.active());
+ } else {
+ if (shardRouting.active() == false) {
+ shardRouting = shardRouting.initialize(randomAsciiOfLength(8), null, shardRouting.getExpectedShardSize())
+ .moveToStarted();
+ }
+ }
+ newIndexRoutingTable.addShard(shardRouting);
+ }
+ }
+ routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
+ return ClusterState.builder(clusterState).routingTable(routingTable).build();
+ }
+
+}
diff --git a/core/src/test/java/org/elasticsearch/action/support/ActiveShardsObserverIT.java b/core/src/test/java/org/elasticsearch/action/support/ActiveShardsObserverIT.java
new file mode 100644
index 00000000000..ec3b5421e0e
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/action/support/ActiveShardsObserverIT.java
@@ -0,0 +1,148 @@
+/*
+ * 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.action.support;
+
+import org.elasticsearch.action.ListenableActionFuture;
+import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
+import org.elasticsearch.common.settings.Settings;
+import org.elasticsearch.test.ESIntegTestCase;
+
+import static org.elasticsearch.cluster.metadata.IndexMetaData.INDEX_NUMBER_OF_REPLICAS_SETTING;
+import static org.elasticsearch.cluster.metadata.IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
+
+/**
+ * Tests that the index creation operation waits for the appropriate
+ * number of active shards to be started before returning.
+ */
+public class ActiveShardsObserverIT extends ESIntegTestCase {
+
+ public void testCreateIndexNoActiveShardsTimesOut() throws Exception {
+ Settings.Builder settingsBuilder = Settings.builder()
+ .put(indexSettings())
+ .put(INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), randomIntBetween(1, 5))
+ .put(INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 0);
+ if (internalCluster().getNodeNames().length > 0) {
+ String exclude = String.join(",", internalCluster().getNodeNames());
+ settingsBuilder.put("index.routing.allocation.exclude._name", exclude);
+ }
+ Settings settings = settingsBuilder.build();
+ assertFalse(prepareCreate("test-idx")
+ .setSettings(settings)
+ .setWaitForActiveShards(randomBoolean() ? ActiveShardCount.from(1) : ActiveShardCount.ALL)
+ .setTimeout("100ms")
+ .get()
+ .isShardsAcked());
+ }
+
+ public void testCreateIndexNoActiveShardsNoWaiting() throws Exception {
+ Settings.Builder settingsBuilder = Settings.builder()
+ .put(indexSettings())
+ .put(INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), randomIntBetween(1, 5))
+ .put(INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 0);
+ if (internalCluster().getNodeNames().length > 0) {
+ String exclude = String.join(",", internalCluster().getNodeNames());
+ settingsBuilder.put("index.routing.allocation.exclude._name", exclude);
+ }
+ Settings settings = settingsBuilder.build();
+ CreateIndexResponse response = prepareCreate("test-idx")
+ .setSettings(settings)
+ .setWaitForActiveShards(ActiveShardCount.from(0))
+ .get();
+ assertTrue(response.isAcknowledged());
+ }
+
+ public void testCreateIndexNotEnoughActiveShardsTimesOut() throws Exception {
+ final int numDataNodes = internalCluster().numDataNodes();
+ final int numReplicas = numDataNodes + randomInt(4);
+ Settings settings = Settings.builder()
+ .put(indexSettings())
+ .put(INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), randomIntBetween(1, 7))
+ .put(INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), numReplicas)
+ .build();
+ assertFalse(prepareCreate("test-idx")
+ .setSettings(settings)
+ .setWaitForActiveShards(ActiveShardCount.from(randomIntBetween(numDataNodes + 1, numReplicas + 1)))
+ .setTimeout("100ms")
+ .get()
+ .isShardsAcked());
+ }
+
+ public void testCreateIndexEnoughActiveShards() throws Exception {
+ final String indexName = "test-idx";
+ Settings settings = Settings.builder()
+ .put(indexSettings())
+ .put(INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), randomIntBetween(1, 7))
+ .put(INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), internalCluster().numDataNodes() + randomIntBetween(0, 3))
+ .build();
+ ActiveShardCount waitForActiveShards = ActiveShardCount.from(randomIntBetween(0, internalCluster().numDataNodes()));
+ assertAcked(prepareCreate(indexName).setSettings(settings).setWaitForActiveShards(waitForActiveShards).get());
+ }
+
+ public void testCreateIndexWaitsForAllActiveShards() throws Exception {
+ // not enough data nodes, index creation times out
+ final int numReplicas = internalCluster().numDataNodes() + randomInt(4);
+ Settings settings = Settings.builder()
+ .put(indexSettings())
+ .put(INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), randomIntBetween(1, 5))
+ .put(INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), numReplicas)
+ .build();
+ assertFalse(prepareCreate("test-idx1")
+ .setSettings(settings)
+ .setWaitForActiveShards(ActiveShardCount.ALL)
+ .setTimeout("100ms")
+ .get()
+ .isShardsAcked());
+
+ // enough data nodes, all shards are active
+ settings = Settings.builder()
+ .put(indexSettings())
+ .put(INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), randomIntBetween(1, 7))
+ .put(INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), internalCluster().numDataNodes() - 1)
+ .build();
+ assertAcked(prepareCreate("test-idx2").setSettings(settings).setWaitForActiveShards(ActiveShardCount.ALL).get());
+ }
+
+ public void testCreateIndexStopsWaitingWhenIndexDeleted() throws Exception {
+ final String indexName = "test-idx";
+ Settings settings = Settings.builder()
+ .put(indexSettings())
+ .put(INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), randomIntBetween(1, 5))
+ .put(INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), internalCluster().numDataNodes() - 1)
+ .build();
+
+ logger.info("--> start the index creation process");
+ ListenableActionFuture responseListener =
+ prepareCreate(indexName)
+ .setSettings(settings)
+ .setWaitForActiveShards(ActiveShardCount.ALL)
+ .execute();
+
+ logger.info("--> wait until the cluster state contains the new index");
+ assertBusy(() -> assertTrue(client().admin().cluster().prepareState().get().getState().metaData().hasIndex(indexName)));
+
+ logger.info("--> delete the index");
+ assertAcked(client().admin().indices().prepareDelete(indexName));
+
+ logger.info("--> ensure the create index request completes");
+ assertAcked(responseListener.get());
+ }
+
+}
diff --git a/core/src/test/java/org/elasticsearch/action/support/IndicesOptionsTests.java b/core/src/test/java/org/elasticsearch/action/support/IndicesOptionsTests.java
index d5ed5302b97..d656e0f62a9 100644
--- a/core/src/test/java/org/elasticsearch/action/support/IndicesOptionsTests.java
+++ b/core/src/test/java/org/elasticsearch/action/support/IndicesOptionsTests.java
@@ -38,7 +38,7 @@ public class IndicesOptionsTests extends ESTestCase {
output.setVersion(outputVersion);
indicesOptions.writeIndicesOptions(output);
- StreamInput streamInput = StreamInput.wrap(output.bytes());
+ StreamInput streamInput = output.bytes().streamInput();
streamInput.setVersion(randomVersion(random()));
IndicesOptions indicesOptions2 = IndicesOptions.readIndicesOptions(streamInput);
diff --git a/core/src/test/java/org/elasticsearch/action/support/ListenableActionFutureTests.java b/core/src/test/java/org/elasticsearch/action/support/ListenableActionFutureTests.java
index 80492f0be61..8169a674bed 100644
--- a/core/src/test/java/org/elasticsearch/action/support/ListenableActionFutureTests.java
+++ b/core/src/test/java/org/elasticsearch/action/support/ListenableActionFutureTests.java
@@ -45,15 +45,15 @@ public class ListenableActionFutureTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
error.set(e);
listenerCalled.countDown();
}
});
Thread networkThread = new Thread(new AbstractRunnable() {
@Override
- public void onFailure(Throwable t) {
- error.set(t);
+ public void onFailure(Exception e) {
+ error.set(e);
listenerCalled.countDown();
}
diff --git a/core/src/test/java/org/elasticsearch/action/support/TransportActionFilterChainTests.java b/core/src/test/java/org/elasticsearch/action/support/TransportActionFilterChainTests.java
index 00068c05efe..bbf1d2f1942 100644
--- a/core/src/test/java/org/elasticsearch/action/support/TransportActionFilterChainTests.java
+++ b/core/src/test/java/org/elasticsearch/action/support/TransportActionFilterChainTests.java
@@ -41,6 +41,8 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Function;
+import java.util.stream.IntStream;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
@@ -102,8 +104,8 @@ public class TransportActionFilterChainTests extends ESTestCase {
try {
assertThat(future.get(), notNullValue());
assertThat("shouldn't get here if an error is expected", errorExpected, equalTo(false));
- } catch(Throwable t) {
- assertThat("shouldn't get here if an error is not expected " + t.getMessage(), errorExpected, equalTo(true));
+ } catch (ExecutionException e) {
+ assertThat("shouldn't get here if an error is not expected " + e.getMessage(), errorExpected, equalTo(true));
}
List testFiltersByLastExecution = new ArrayList<>();
@@ -182,8 +184,8 @@ public class TransportActionFilterChainTests extends ESTestCase {
try {
assertThat(future.get(), notNullValue());
assertThat("shouldn't get here if an error is expected", errorExpected, equalTo(false));
- } catch(Throwable t) {
- assertThat("shouldn't get here if an error is not expected " + t.getMessage(), errorExpected, equalTo(true));
+ } catch(ExecutionException e) {
+ assertThat("shouldn't get here if an error is not expected " + e.getMessage(), errorExpected, equalTo(true));
}
List testFiltersByLastExecution = new ArrayList<>();
@@ -252,7 +254,7 @@ public class TransportActionFilterChainTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
failures.add(e);
latch.countDown();
}
@@ -309,7 +311,7 @@ public class TransportActionFilterChainTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
failures.add(e);
latch.countDown();
}
@@ -445,12 +447,12 @@ public class TransportActionFilterChainTests extends ESTestCase {
}
}
- private static interface RequestCallback {
+ private interface RequestCallback {
, Response extends ActionResponse> void execute(Task task, String action, Request request,
ActionListener listener, ActionFilterChain actionFilterChain);
}
- private static interface ResponseCallback {
+ private interface ResponseCallback {
void execute(String action, Response response, ActionListener listener,
ActionFilterChain, Response> chain);
}
diff --git a/core/src/test/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeActionTests.java b/core/src/test/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeActionTests.java
index 1d65f277e3c..603ad664ec3 100644
--- a/core/src/test/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeActionTests.java
+++ b/core/src/test/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeActionTests.java
@@ -49,7 +49,7 @@ import org.elasticsearch.cluster.routing.TestShardRouting;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.rest.RestStatus;
@@ -247,7 +247,7 @@ public class TransportBroadcastByNodeActionTests extends ESTestCase {
}
static DiscoveryNode newNode(int nodeId) {
- return new DiscoveryNode("node_" + nodeId, DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ return new DiscoveryNode("node_" + nodeId, LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT);
}
@AfterClass
@@ -491,7 +491,7 @@ public class TransportBroadcastByNodeActionTests extends ESTestCase {
}
@Override
- public void sendResponse(Throwable error) throws IOException {
+ public void sendResponse(Exception exception) throws IOException {
}
@Override
diff --git a/core/src/test/java/org/elasticsearch/action/support/master/TransportMasterNodeActionTests.java b/core/src/test/java/org/elasticsearch/action/support/master/TransportMasterNodeActionTests.java
index 32fe6b1e408..9aeafcac0e4 100644
--- a/core/src/test/java/org/elasticsearch/action/support/master/TransportMasterNodeActionTests.java
+++ b/core/src/test/java/org/elasticsearch/action/support/master/TransportMasterNodeActionTests.java
@@ -18,6 +18,7 @@
*/
package org.elasticsearch.action.support.master;
+import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.ActionListener;
@@ -37,7 +38,7 @@ import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.discovery.Discovery;
import org.elasticsearch.discovery.MasterNotDiscoveredException;
@@ -89,9 +90,9 @@ public class TransportMasterNodeActionTests extends ESTestCase {
transportService = new TransportService(clusterService.getSettings(), transport, threadPool);
transportService.start();
transportService.acceptIncomingRequests();
- localNode = new DiscoveryNode("local_node", DummyTransportAddress.INSTANCE, Collections.emptyMap(),
+ localNode = new DiscoveryNode("local_node", LocalTransportAddress.buildUnique(), Collections.emptyMap(),
Collections.singleton(DiscoveryNode.Role.MASTER), Version.CURRENT);
- remoteNode = new DiscoveryNode("remote_node", DummyTransportAddress.INSTANCE, Collections.emptyMap(),
+ remoteNode = new DiscoveryNode("remote_node", LocalTransportAddress.buildUnique(), Collections.emptyMap(),
Collections.singleton(DiscoveryNode.Role.MASTER), Version.CURRENT);
allNodes = new DiscoveryNode[]{localNode, remoteNode};
}
@@ -136,7 +137,7 @@ public class TransportMasterNodeActionTests extends ESTestCase {
@Override
protected void doExecute(Task task, final Request request, ActionListener listener) {
// remove unneeded threading by wrapping listener with SAME to prevent super.doExecute from wrapping it with LISTENER
- super.doExecute(task, request, new ThreadedActionListener<>(logger, threadPool, ThreadPool.Names.SAME, listener));
+ super.doExecute(task, request, new ThreadedActionListener<>(logger, threadPool, ThreadPool.Names.SAME, listener, false));
}
@Override
@@ -167,7 +168,7 @@ public class TransportMasterNodeActionTests extends ESTestCase {
Request request = new Request();
PlainActionFuture listener = new PlainActionFuture<>();
- final Throwable exception = new Throwable();
+ final Exception exception = new Exception();
final Response response = new Response();
setState(clusterService, ClusterStateCreationUtils.state(localNode, localNode, allNodes));
@@ -244,7 +245,7 @@ public class TransportMasterNodeActionTests extends ESTestCase {
Request request = new Request();
PlainActionFuture listener = new PlainActionFuture<>();
- setState(clusterService, ClusterStateCreationUtils.state(localNode, randomFrom(null, localNode, remoteNode), allNodes));
+ setState(clusterService, ClusterStateCreationUtils.state(localNode, randomFrom(localNode, remoteNode, null), allNodes));
new Action(Settings.EMPTY, "testAction", transportService, clusterService, threadPool) {
@Override
@@ -317,14 +318,19 @@ public class TransportMasterNodeActionTests extends ESTestCase {
assertTrue(listener.isDone());
listener.get();
} else {
- Throwable t = new Throwable();
+ ElasticsearchException t = new ElasticsearchException("test");
+ t.addHeader("header", "is here");
transport.handleRemoteError(capturedRequest.requestId, t);
assertTrue(listener.isDone());
try {
listener.get();
fail("Expected exception but returned proper result");
} catch (ExecutionException ex) {
- assertThat(ex.getCause().getCause(), equalTo(t));
+ final Throwable cause = ex.getCause().getCause();
+ assertThat(cause, instanceOf(ElasticsearchException.class));
+ final ElasticsearchException es = (ElasticsearchException) cause;
+ assertThat(es.getMessage(), equalTo(t.getMessage()));
+ assertThat(es.getHeader("header"), equalTo(t.getHeader("header")));
}
}
}
@@ -342,7 +348,7 @@ public class TransportMasterNodeActionTests extends ESTestCase {
protected void masterOperation(Request request, ClusterState state, ActionListener listener) throws Exception {
// The other node has become master, simulate failures of this node while publishing cluster state through ZenDiscovery
setState(clusterService, ClusterStateCreationUtils.state(localNode, remoteNode, allNodes));
- Throwable failure = randomBoolean()
+ Exception failure = randomBoolean()
? new Discovery.FailedToCommitClusterStateException("Fake error")
: new NotMasterException("Fake error");
listener.onFailure(failure);
diff --git a/core/src/test/java/org/elasticsearch/action/support/nodes/TransportNodesActionTests.java b/core/src/test/java/org/elasticsearch/action/support/nodes/TransportNodesActionTests.java
index a15f89bced4..ae8ea4a0b95 100644
--- a/core/src/test/java/org/elasticsearch/action/support/nodes/TransportNodesActionTests.java
+++ b/core/src/test/java/org/elasticsearch/action/support/nodes/TransportNodesActionTests.java
@@ -32,7 +32,7 @@ import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.transport.CapturingTransport;
import org.elasticsearch.threadpool.TestThreadPool;
@@ -236,7 +236,7 @@ public class TransportNodesActionTests extends ESTestCase {
private static DiscoveryNode newNode(int nodeId, Map attributes, Set roles) {
String node = "node_" + nodeId;
- return new DiscoveryNode(node, node, DummyTransportAddress.INSTANCE, attributes, roles, Version.CURRENT);
+ return new DiscoveryNode(node, node, LocalTransportAddress.buildUnique(), attributes, roles, Version.CURRENT);
}
private static class TestTransportNodesAction
diff --git a/core/src/test/java/org/elasticsearch/action/support/replication/ClusterStateCreationUtils.java b/core/src/test/java/org/elasticsearch/action/support/replication/ClusterStateCreationUtils.java
index dc40fda3f8e..7496bb85faf 100644
--- a/core/src/test/java/org/elasticsearch/action/support/replication/ClusterStateCreationUtils.java
+++ b/core/src/test/java/org/elasticsearch/action/support/replication/ClusterStateCreationUtils.java
@@ -34,7 +34,7 @@ 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.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.index.shard.ShardId;
import java.util.Arrays;
@@ -220,7 +220,6 @@ public class ClusterStateCreationUtils {
* Creates a cluster state with no index
*/
public static ClusterState stateWithNoShard() {
- int numberOfNodes = 2;
DiscoveryNodes.Builder discoBuilder = DiscoveryNodes.builder();
discoBuilder.localNodeId(newNode(0).getId());
discoBuilder.masterNodeId(newNode(1).getId());
@@ -256,11 +255,11 @@ public class ClusterStateCreationUtils {
}
private static DiscoveryNode newNode(int nodeId) {
- return new DiscoveryNode("node_" + nodeId, DummyTransportAddress.INSTANCE, Collections.emptyMap(),
+ return new DiscoveryNode("node_" + nodeId, LocalTransportAddress.buildUnique(), Collections.emptyMap(),
new HashSet<>(Arrays.asList(DiscoveryNode.Role.values())), Version.CURRENT);
}
- static private String selectAndRemove(Set strings) {
+ private static String selectAndRemove(Set strings) {
String selection = randomFrom(strings.toArray(new String[strings.size()]));
strings.remove(selection);
return selection;
diff --git a/core/src/test/java/org/elasticsearch/action/support/replication/ReplicationOperationTests.java b/core/src/test/java/org/elasticsearch/action/support/replication/ReplicationOperationTests.java
index 55e2a9d3cf2..9f41f0e37c2 100644
--- a/core/src/test/java/org/elasticsearch/action/support/replication/ReplicationOperationTests.java
+++ b/core/src/test/java/org/elasticsearch/action/support/replication/ReplicationOperationTests.java
@@ -81,11 +81,11 @@ public class ReplicationOperationTests extends ESTestCase {
final Set expectedReplicas = getExpectedReplicas(shardId, state);
- final Map expectedFailures = new HashMap<>();
+ final Map expectedFailures = new HashMap<>();
final Set expectedFailedShards = new HashSet<>();
for (ShardRouting replica : expectedReplicas) {
if (randomBoolean()) {
- Throwable t;
+ Exception t;
boolean criticalFailure = randomBoolean();
if (criticalFailure) {
t = new CorruptIndexException("simulated", (String) null);
@@ -166,7 +166,7 @@ public class ReplicationOperationTests extends ESTestCase {
final Set expectedReplicas = getExpectedReplicas(shardId, state);
- final Map expectedFailures = new HashMap<>();
+ final Map expectedFailures = new HashMap<>();
final ShardRouting failedReplica = randomFrom(new ArrayList<>(expectedReplicas));
expectedFailures.put(failedReplica, new CorruptIndexException("simulated", (String) null));
@@ -175,9 +175,9 @@ public class ReplicationOperationTests extends ESTestCase {
final ClusterState finalState = state;
final TestReplicaProxy replicasProxy = new TestReplicaProxy(expectedFailures) {
@Override
- public void failShard(ShardRouting replica, ShardRouting primary, String message, Throwable throwable,
- Runnable onSuccess, Consumer onPrimaryDemoted,
- Consumer onIgnoredFailure) {
+ public void failShard(ShardRouting replica, ShardRouting primary, String message, Exception exception,
+ Runnable onSuccess, Consumer onPrimaryDemoted,
+ Consumer onIgnoredFailure) {
assertThat(replica, equalTo(failedReplica));
onPrimaryDemoted.accept(new ElasticsearchException("the king is dead"));
}
@@ -185,7 +185,7 @@ public class ReplicationOperationTests extends ESTestCase {
AtomicBoolean primaryFailed = new AtomicBoolean();
final TestPrimary primary = new TestPrimary(primaryShard, primaryTerm) {
@Override
- public void failShard(String message, Throwable throwable) {
+ public void failShard(String message, Exception exception) {
assertTrue(primaryFailed.compareAndSet(false, true));
}
};
@@ -376,8 +376,8 @@ public class ReplicationOperationTests extends ESTestCase {
}
@Override
- public void failShard(String message, Throwable throwable) {
- throw new AssertionError("should shouldn't be failed with [" + message + "]", throwable);
+ public void failShard(String message, Exception exception) {
+ throw new AssertionError("should shouldn't be failed with [" + message + "]", exception);
}
@Override
@@ -415,7 +415,7 @@ public class ReplicationOperationTests extends ESTestCase {
static class TestReplicaProxy implements ReplicationOperation.Replicas {
- final Map opFailures;
+ final Map opFailures;
final Set failedReplicas = ConcurrentCollections.newConcurrentSet();
@@ -423,7 +423,7 @@ public class ReplicationOperationTests extends ESTestCase {
this(Collections.emptyMap());
}
- TestReplicaProxy(Map opFailures) {
+ TestReplicaProxy(Map opFailures) {
this.opFailures = opFailures;
}
@@ -438,8 +438,8 @@ public class ReplicationOperationTests extends ESTestCase {
}
@Override
- public void failShard(ShardRouting replica, ShardRouting primary, String message, Throwable throwable, Runnable onSuccess,
- Consumer onPrimaryDemoted, Consumer onIgnoredFailure) {
+ public void failShard(ShardRouting replica, ShardRouting primary, String message, Exception exception, Runnable onSuccess,
+ Consumer onPrimaryDemoted, Consumer onIgnoredFailure) {
if (failedReplicas.add(replica) == false) {
fail("replica [" + replica + "] was failed twice");
}
diff --git a/core/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java b/core/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java
index 229e3b6635e..de2ddabb0fe 100644
--- a/core/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java
+++ b/core/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java
@@ -390,7 +390,15 @@ public class TransportReplicationActionTests extends ESTestCase {
PlainActionFuture listener = new PlainActionFuture<>();
ReplicationTask task = maybeTask();
AtomicBoolean executed = new AtomicBoolean();
- Action.PrimaryOperationTransportHandler primaryPhase = action.new PrimaryOperationTransportHandler() {
+
+ ShardRouting primaryShard = state.getRoutingTable().shardRoutingTable(shardId).primaryShard();
+ boolean executeOnPrimary = true;
+ // whether shard has been marked as relocated already (i.e. relocation completed)
+ if (primaryShard.relocating() && randomBoolean()) {
+ isRelocated.set(true);
+ executeOnPrimary = false;
+ }
+ action.new AsyncPrimaryAction(request, createTransportChannel(listener), task) {
@Override
protected ReplicationOperation createReplicatedOperation(Request request,
ActionListener actionListener, Action.PrimaryShardReference primaryShardReference,
@@ -403,15 +411,7 @@ public class TransportReplicationActionTests extends ESTestCase {
}
};
}
- };
- ShardRouting primaryShard = state.getRoutingTable().shardRoutingTable(shardId).primaryShard();
- boolean executeOnPrimary = true;
- // whether shard has been marked as relocated already (i.e. relocation completed)
- if (primaryShard.relocating() && randomBoolean()) {
- isRelocated.set(true);
- executeOnPrimary = false;
- }
- primaryPhase.messageReceived(request, createTransportChannel(listener), task);
+ }.run();
if (executeOnPrimary) {
assertTrue(executed.get());
assertTrue(listener.isDone());
@@ -445,7 +445,7 @@ public class TransportReplicationActionTests extends ESTestCase {
PlainActionFuture listener = new PlainActionFuture<>();
ReplicationTask task = maybeTask();
AtomicBoolean executed = new AtomicBoolean();
- Action.PrimaryOperationTransportHandler primaryPhase = action.new PrimaryOperationTransportHandler() {
+ action.new AsyncPrimaryAction(request, createTransportChannel(listener), task) {
@Override
protected ReplicationOperation createReplicatedOperation(Request request,
ActionListener actionListener, Action.PrimaryShardReference primaryShardReference,
@@ -458,8 +458,7 @@ public class TransportReplicationActionTests extends ESTestCase {
}
};
}
- };
- primaryPhase.messageReceived(request, createTransportChannel(listener), task);
+ }.run();
assertThat(executed.get(), equalTo(true));
assertPhase(task, "finished");
}
@@ -579,16 +578,18 @@ public class TransportReplicationActionTests extends ESTestCase {
metaData.put(IndexMetaData.builder(metaData.get(index)).settings(settings));
state = ClusterState.builder(state).metaData(metaData).build();
setState(clusterService, state);
- Action.PrimaryOperationTransportHandler primaryPhase = action.new PrimaryOperationTransportHandler() {
+ AtomicBoolean executed = new AtomicBoolean();
+ action.new AsyncPrimaryAction(new Request(shardId), createTransportChannel(new PlainActionFuture<>()), null) {
@Override
protected ReplicationOperation createReplicatedOperation(Request request,
ActionListener actionListener, Action.PrimaryShardReference primaryShardReference,
boolean executeOnReplicas) {
assertFalse(executeOnReplicas);
+ assertFalse(executed.getAndSet(true));
return new NoopReplicationOperation(request, actionListener);
}
- };
- primaryPhase.messageReceived(new Request(shardId), createTransportChannel(new PlainActionFuture<>()), null);
+ }.run();
+ assertThat(executed.get(), equalTo(true));
}
public void testCounterOnPrimary() throws Exception {
@@ -604,17 +605,16 @@ public class TransportReplicationActionTests extends ESTestCase {
final boolean throwExceptionOnCreation = i == 1;
final boolean throwExceptionOnRun = i == 2;
final boolean respondWithError = i == 3;
- Action.PrimaryOperationTransportHandler primaryPhase = action.new PrimaryOperationTransportHandler() {
-
+ action.new AsyncPrimaryAction(request, createTransportChannel(listener), task) {
@Override
protected ReplicationOperation createReplicatedOperation(Request request,
- ActionListener listener, Action.PrimaryShardReference primaryShardReference,
+ ActionListener actionListener, Action.PrimaryShardReference primaryShardReference,
boolean executeOnReplicas) {
assertIndexShardCounter(1);
if (throwExceptionOnCreation) {
throw new ElasticsearchException("simulated exception, during createReplicatedOperation");
}
- return new NoopReplicationOperation(request, listener) {
+ return new NoopReplicationOperation(request, actionListener) {
@Override
public void execute() throws Exception {
assertIndexShardCounter(1);
@@ -629,18 +629,7 @@ public class TransportReplicationActionTests extends ESTestCase {
}
};
}
- };
- try {
- primaryPhase.messageReceived(request, createTransportChannel(listener), task);
- } catch (ElasticsearchException e) {
- if (throwExceptionOnCreation || throwExceptionOnRun) {
- assertThat(e.getMessage(), containsString("simulated"));
- assertIndexShardCounter(0);
- return; // early terminate
- } else {
- throw e;
- }
- }
+ }.run();
assertIndexShardCounter(0);
assertTrue(listener.isDone());
assertPhase(task, "finished");
@@ -648,7 +637,7 @@ public class TransportReplicationActionTests extends ESTestCase {
try {
listener.get();
} catch (ExecutionException e) {
- if (respondWithError) {
+ if (throwExceptionOnCreation || throwExceptionOnRun || respondWithError) {
Throwable cause = e.getCause();
assertThat(cause, instanceOf(ElasticsearchException.class));
assertThat(cause.getMessage(), containsString("simulated"));
@@ -787,16 +776,16 @@ public class TransportReplicationActionTests extends ESTestCase {
}
@Override
- protected PrimaryShardReference getPrimaryShardReference(ShardId shardId) {
+ protected void acquirePrimaryShardReference(ShardId shardId, ActionListener onReferenceAcquired) {
count.incrementAndGet();
- return new PrimaryShardReference(null, null) {
+ PrimaryShardReference primaryShardReference = new PrimaryShardReference(null, null) {
@Override
public boolean isRelocated() {
return isRelocated.get();
}
@Override
- public void failShard(String reason, @Nullable Throwable e) {
+ public void failShard(String reason, @Nullable Exception e) {
throw new UnsupportedOperationException();
}
@@ -812,13 +801,15 @@ public class TransportReplicationActionTests extends ESTestCase {
public void close() {
count.decrementAndGet();
}
-
};
+
+ onReferenceAcquired.onResponse(primaryShardReference);
}
- protected Releasable acquireReplicaOperationLock(ShardId shardId, long primaryTerm) {
+ @Override
+ protected void acquireReplicaOperationLock(ShardId shardId, long primaryTerm, ActionListener onLockAcquired) {
count.incrementAndGet();
- return count::decrementAndGet;
+ onLockAcquired.onResponse(count::decrementAndGet);
}
}
@@ -865,9 +856,9 @@ public class TransportReplicationActionTests extends ESTestCase {
}
@Override
- public void sendResponse(Throwable error) throws IOException {
- consumer.accept(error);
- listener.onFailure(error);
+ public void sendResponse(Exception exception) throws IOException {
+ consumer.accept(exception);
+ listener.onFailure(exception);
}
@Override
diff --git a/core/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java b/core/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java
index 7b312959631..80e689743fd 100644
--- a/core/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java
+++ b/core/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java
@@ -179,7 +179,7 @@ public class TransportWriteActionTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
throw new RuntimeException(e);
}
}
diff --git a/core/src/test/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationActionTests.java b/core/src/test/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationActionTests.java
index c26d376b587..37abc4d5eed 100644
--- a/core/src/test/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationActionTests.java
+++ b/core/src/test/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationActionTests.java
@@ -179,9 +179,9 @@ public class TransportInstanceSingleOperationActionTests extends ESTestCase {
action.new AsyncSingleAction(request, listener).start();
listener.get();
fail("expected ClusterBlockException");
- } catch (Throwable t) {
- if (ExceptionsHelper.unwrap(t, ClusterBlockException.class) == null) {
- logger.info("expected ClusterBlockException but got ", t);
+ } catch (Exception e) {
+ if (ExceptionsHelper.unwrap(e, ClusterBlockException.class) == null) {
+ logger.info("expected ClusterBlockException but got ", e);
fail("expected ClusterBlockException");
}
}
@@ -317,9 +317,9 @@ public class TransportInstanceSingleOperationActionTests extends ESTestCase {
assertThat(transport.capturedRequests().length, equalTo(0));
try {
listener.get();
- } catch (Throwable t) {
- if (ExceptionsHelper.unwrap(t, IllegalStateException.class) == null) {
- logger.info("expected IllegalStateException but got ", t);
+ } catch (Exception e) {
+ if (ExceptionsHelper.unwrap(e, IllegalStateException.class) == null) {
+ logger.info("expected IllegalStateException but got ", e);
fail("expected and IllegalStateException");
}
}
diff --git a/core/src/test/java/org/elasticsearch/action/termvectors/AbstractTermVectorsTestCase.java b/core/src/test/java/org/elasticsearch/action/termvectors/AbstractTermVectorsTestCase.java
index 208945a6179..1bba4cac3dd 100644
--- a/core/src/test/java/org/elasticsearch/action/termvectors/AbstractTermVectorsTestCase.java
+++ b/core/src/test/java/org/elasticsearch/action/termvectors/AbstractTermVectorsTestCase.java
@@ -68,10 +68,10 @@ import static org.hamcrest.Matchers.equalTo;
public abstract class AbstractTermVectorsTestCase extends ESIntegTestCase {
protected static class TestFieldSetting {
- final public String name;
- final public boolean storedOffset;
- final public boolean storedPayloads;
- final public boolean storedPositions;
+ public final String name;
+ public final boolean storedOffset;
+ public final boolean storedPayloads;
+ public final boolean storedPositions;
public TestFieldSetting(String name, boolean storedOffset, boolean storedPayloads, boolean storedPositions) {
this.name = name;
@@ -124,9 +124,9 @@ public abstract class AbstractTermVectorsTestCase extends ESIntegTestCase {
}
protected static class TestDoc {
- final public String id;
- final public TestFieldSetting[] fieldSettings;
- final public String[] fieldContent;
+ public final String id;
+ public final TestFieldSetting[] fieldSettings;
+ public final String[] fieldContent;
public String index = "test";
public String alias = "alias";
public String type = "type1";
@@ -163,11 +163,11 @@ public abstract class AbstractTermVectorsTestCase extends ESIntegTestCase {
}
protected static class TestConfig {
- final public TestDoc doc;
- final public String[] selectedFields;
- final public boolean requestPositions;
- final public boolean requestOffsets;
- final public boolean requestPayloads;
+ public final TestDoc doc;
+ public final String[] selectedFields;
+ public final boolean requestPositions;
+ public final boolean requestOffsets;
+ public final boolean requestPayloads;
public Class expectedException = null;
public TestConfig(TestDoc doc, String[] selectedFields, boolean requestPositions, boolean requestOffsets, boolean requestPayloads) {
@@ -213,8 +213,6 @@ public abstract class AbstractTermVectorsTestCase extends ESIntegTestCase {
.put("index.analysis.analyzer.tv_test.tokenizer", "standard")
.putArray("index.analysis.analyzer.tv_test.filter", "type_as_payload", "lowercase");
assertAcked(prepareCreate(index).addMapping("type1", mappingBuilder).setSettings(settings).addAlias(new Alias(alias)));
-
- ensureYellow();
}
/**
diff --git a/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsCheckDocFreqIT.java b/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsCheckDocFreqIT.java
index 37a1bc92e9c..1611c63d2ba 100644
--- a/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsCheckDocFreqIT.java
+++ b/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsCheckDocFreqIT.java
@@ -140,7 +140,7 @@ public class GetTermVectorsCheckDocFreqIT extends ESIntegTestCase {
xBuilder.startObject();
response.toXContent(xBuilder, null);
xBuilder.endObject();
- String utf8 = xBuilder.bytes().toUtf8().replaceFirst("\"took\":\\d+,", "");;
+ String utf8 = xBuilder.bytes().utf8ToString().replaceFirst("\"took\":\\d+,", "");;
String expectedString = "{\"_index\":\"test\",\"_type\":\"type1\",\"_id\":\""
+ i
+ "\",\"_version\":1,\"found\":true,\"term_vectors\":{\"field\":{\"terms\":{\"brown\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":2,\"start_offset\":10,\"end_offset\":15,\"payload\":\"d29yZA==\"}]},\"dog\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":8,\"start_offset\":40,\"end_offset\":43,\"payload\":\"d29yZA==\"}]},\"fox\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":3,\"start_offset\":16,\"end_offset\":19,\"payload\":\"d29yZA==\"}]},\"jumps\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":4,\"start_offset\":20,\"end_offset\":25,\"payload\":\"d29yZA==\"}]},\"lazy\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":7,\"start_offset\":35,\"end_offset\":39,\"payload\":\"d29yZA==\"}]},\"over\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":5,\"start_offset\":26,\"end_offset\":30,\"payload\":\"d29yZA==\"}]},\"quick\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":1,\"start_offset\":4,\"end_offset\":9,\"payload\":\"d29yZA==\"}]},\"the\":{\"doc_freq\":15,\"ttf\":30,\"term_freq\":2,\"tokens\":[{\"position\":0,\"start_offset\":0,\"end_offset\":3,\"payload\":\"d29yZA==\"},{\"position\":6,\"start_offset\":31,\"end_offset\":34,\"payload\":\"d29yZA==\"}]}}}}}";
@@ -196,7 +196,7 @@ public class GetTermVectorsCheckDocFreqIT extends ESIntegTestCase {
xBuilder.startObject();
response.toXContent(xBuilder, null);
xBuilder.endObject();
- String utf8 = xBuilder.bytes().toUtf8().replaceFirst("\"took\":\\d+,", "");;
+ String utf8 = xBuilder.bytes().utf8ToString().replaceFirst("\"took\":\\d+,", "");;
String expectedString = "{\"_index\":\"test\",\"_type\":\"type1\",\"_id\":\""
+ i
+ "\",\"_version\":1,\"found\":true,\"term_vectors\":{\"field\":{\"field_statistics\":{\"sum_doc_freq\":120,\"doc_count\":15,\"sum_ttf\":135},\"terms\":{\"brown\":{\"term_freq\":1,\"tokens\":[{\"position\":2,\"start_offset\":10,\"end_offset\":15,\"payload\":\"d29yZA==\"}]},\"dog\":{\"term_freq\":1,\"tokens\":[{\"position\":8,\"start_offset\":40,\"end_offset\":43,\"payload\":\"d29yZA==\"}]},\"fox\":{\"term_freq\":1,\"tokens\":[{\"position\":3,\"start_offset\":16,\"end_offset\":19,\"payload\":\"d29yZA==\"}]},\"jumps\":{\"term_freq\":1,\"tokens\":[{\"position\":4,\"start_offset\":20,\"end_offset\":25,\"payload\":\"d29yZA==\"}]},\"lazy\":{\"term_freq\":1,\"tokens\":[{\"position\":7,\"start_offset\":35,\"end_offset\":39,\"payload\":\"d29yZA==\"}]},\"over\":{\"term_freq\":1,\"tokens\":[{\"position\":5,\"start_offset\":26,\"end_offset\":30,\"payload\":\"d29yZA==\"}]},\"quick\":{\"term_freq\":1,\"tokens\":[{\"position\":1,\"start_offset\":4,\"end_offset\":9,\"payload\":\"d29yZA==\"}]},\"the\":{\"term_freq\":2,\"tokens\":[{\"position\":0,\"start_offset\":0,\"end_offset\":3,\"payload\":\"d29yZA==\"},{\"position\":6,\"start_offset\":31,\"end_offset\":34,\"payload\":\"d29yZA==\"}]}}}}}";
@@ -255,7 +255,7 @@ public class GetTermVectorsCheckDocFreqIT extends ESIntegTestCase {
xBuilder.startObject();
response.toXContent(xBuilder, ToXContent.EMPTY_PARAMS);
xBuilder.endObject();
- String utf8 = xBuilder.bytes().toUtf8().replaceFirst("\"took\":\\d+,", "");;
+ String utf8 = xBuilder.bytes().utf8ToString().replaceFirst("\"took\":\\d+,", "");;
String expectedString = "{\"_index\":\"test\",\"_type\":\"type1\",\"_id\":\""
+ i
+ "\",\"_version\":1,\"found\":true,\"term_vectors\":{\"field\":{\"field_statistics\":{\"sum_doc_freq\":120,\"doc_count\":15,\"sum_ttf\":135},\"terms\":{\"brown\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":2,\"start_offset\":10,\"end_offset\":15,\"payload\":\"d29yZA==\"}]},\"dog\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":8,\"start_offset\":40,\"end_offset\":43,\"payload\":\"d29yZA==\"}]},\"fox\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":3,\"start_offset\":16,\"end_offset\":19,\"payload\":\"d29yZA==\"}]},\"jumps\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":4,\"start_offset\":20,\"end_offset\":25,\"payload\":\"d29yZA==\"}]},\"lazy\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":7,\"start_offset\":35,\"end_offset\":39,\"payload\":\"d29yZA==\"}]},\"over\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":5,\"start_offset\":26,\"end_offset\":30,\"payload\":\"d29yZA==\"}]},\"quick\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":1,\"start_offset\":4,\"end_offset\":9,\"payload\":\"d29yZA==\"}]},\"the\":{\"doc_freq\":15,\"ttf\":30,\"term_freq\":2,\"tokens\":[{\"position\":0,\"start_offset\":0,\"end_offset\":3,\"payload\":\"d29yZA==\"},{\"position\":6,\"start_offset\":31,\"end_offset\":34,\"payload\":\"d29yZA==\"}]}}}}}";
diff --git a/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java b/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java
index 12af9f8a2c2..3835edbbe9a 100644
--- a/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java
+++ b/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java
@@ -39,7 +39,6 @@ import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.engine.VersionConflictEngineException;
import org.elasticsearch.index.mapper.FieldMapper;
-import org.hamcrest.Matcher;
import java.io.IOException;
import java.util.ArrayList;
@@ -55,7 +54,6 @@ import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@@ -71,8 +69,6 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
.endObject().endObject();
assertAcked(prepareCreate("test").addAlias(new Alias("alias")).addMapping("type1", mapping));
- ensureYellow();
-
client().prepareIndex("test", "type1", "666").setSource("field", "foo bar").execute().actionGet();
refresh();
for (int i = 0; i < 20; i++) {
@@ -97,8 +93,6 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
.endObject().endObject();
assertAcked(prepareCreate("test").addAlias(new Alias("alias")).addMapping("type1", mapping));
- ensureYellow();
-
// when indexing a field that simply has a question mark, the term vectors will be null
client().prepareIndex("test", "type1", "0").setSource("existingfield", "?").execute().actionGet();
refresh();
@@ -124,8 +118,6 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
.endObject().endObject();
assertAcked(prepareCreate("test").addAlias(new Alias("alias")).addMapping("type1", mapping));
- ensureYellow();
-
// when indexing a field that simply has a question mark, the term vectors will be null
client().prepareIndex("test", "type1", "0").setSource("anotherexistingfield", 1).execute().actionGet();
refresh();
@@ -154,8 +146,6 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
"field4", "type=keyword", // yes tvs
"field5", "type=text,index=true")); // yes tvs
- ensureYellow();
-
List indexBuilders = new ArrayList<>();
for (int i = 0; i < 6; i++) {
indexBuilders.add(client().prepareIndex()
@@ -200,7 +190,6 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
.put(indexSettings())
.put("index.analysis.analyzer.tv_test.tokenizer", "whitespace")
.putArray("index.analysis.analyzer.tv_test.filter", "type_as_payload", "lowercase")));
- ensureYellow();
for (int i = 0; i < 10; i++) {
client().prepareIndex("test", "type1", Integer.toString(i))
.setSource(jsonBuilder().startObject().field("field", "the quick brown fox jumps over the lazy dog")
@@ -286,7 +275,6 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
.setSettings(Settings.builder()
.put("index.analysis.analyzer.tv_test.tokenizer", "whitespace")
.putArray("index.analysis.analyzer.tv_test.filter", "type_as_payload", "lowercase")));
- ensureYellow();
for (int i = 0; i < 10; i++) {
client().prepareIndex("test", "type1", Integer.toString(i))
.setSource(jsonBuilder().startObject().field("field", "the quick brown fox jumps over the lazy dog")
@@ -391,19 +379,15 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
TestConfig[] testConfigs = generateTestConfigs(20, testDocs, testFieldSettings);
for (TestConfig test : testConfigs) {
- try {
- TermVectorsRequestBuilder request = getRequestForConfig(test);
- if (test.expectedException != null) {
- assertThrows(request, test.expectedException);
- continue;
- }
-
- TermVectorsResponse response = request.get();
- Fields luceneTermVectors = getTermVectorsFromLucene(directoryReader, test.doc);
- validateResponse(response, luceneTermVectors, test);
- } catch (Throwable t) {
- throw new Exception("Test exception while running " + test.toString(), t);
+ TermVectorsRequestBuilder request = getRequestForConfig(test);
+ if (test.expectedException != null) {
+ assertThrows(request, test.expectedException);
+ continue;
}
+
+ TermVectorsResponse response = request.get();
+ Fields luceneTermVectors = getTermVectorsFromLucene(directoryReader, test.doc);
+ validateResponse(response, luceneTermVectors, test);
}
}
@@ -436,7 +420,6 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
.put("index.analysis.filter.my_delimited_payload_filter.delimiter", delimiter)
.put("index.analysis.filter.my_delimited_payload_filter.encoding", encodingString)
.put("index.analysis.filter.my_delimited_payload_filter.type", "delimited_payload_filter")));
- ensureYellow();
client().prepareIndex("test", "type1", Integer.toString(1))
.setSource(jsonBuilder().startObject().field("field", queryString).endObject()).execute().actionGet();
@@ -963,21 +946,6 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
return randomBoolean() ? "test" : "alias";
}
- private Map getFieldStatistics(Map stats, String fieldName) throws IOException {
- return (Map) ((Map) stats.get(fieldName)).get("field_statistics");
- }
-
- private Map getTermStatistics(Map stats, String fieldName, String term) {
- return (Map) ((Map) ((Map) stats.get(fieldName)).get("terms")).get(term);
- }
-
- private Matcher equalOrLessThanTo(Integer value, boolean isEqual) {
- if (isEqual) {
- return equalTo(value);
- }
- return lessThan(value);
- }
-
public void testTermVectorsWithVersion() {
assertAcked(prepareCreate("test").addAlias(new Alias("alias"))
.setSettings(Settings.builder().put("index.refresh_interval", -1)));
@@ -1089,7 +1057,6 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
assertAcked(prepareCreate("test")
.setSettings(settings)
.addMapping("type1", "tags", "type=text"));
- ensureYellow();
int numTerms = scaledRandomIntBetween(10, 50);
logger.info("Indexing one document with tags of increasing length ...");
@@ -1127,7 +1094,6 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
assertAcked(prepareCreate("test")
.setSettings(settings)
.addMapping("type1", "tags", "type=text"));
- ensureYellow();
logger.info("Indexing one document with tags of increasing frequencies ...");
int numTerms = scaledRandomIntBetween(10, 50);
@@ -1168,7 +1134,6 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
assertAcked(prepareCreate("test")
.setSettings(settings)
.addMapping("type1", "tags", "type=text"));
- ensureYellow();
int numDocs = scaledRandomIntBetween(10, 50); // as many terms as there are docs
logger.info("Indexing {} documents with tags of increasing dfs ...", numDocs);
diff --git a/core/src/test/java/org/elasticsearch/action/termvectors/MultiTermVectorsIT.java b/core/src/test/java/org/elasticsearch/action/termvectors/MultiTermVectorsIT.java
index 57a89c82cc8..5ed4f3252d5 100644
--- a/core/src/test/java/org/elasticsearch/action/termvectors/MultiTermVectorsIT.java
+++ b/core/src/test/java/org/elasticsearch/action/termvectors/MultiTermVectorsIT.java
@@ -56,21 +56,16 @@ public class MultiTermVectorsIT extends AbstractTermVectorsTestCase {
for (int i = 0; i < testConfigs.length; i++) {
TestConfig test = testConfigs[i];
- try {
- MultiTermVectorsItemResponse item = responseItems[i];
- if (test.expectedException != null) {
- assertTrue(item.isFailed());
- continue;
- } else if (item.isFailed()) {
- fail(item.getFailure().getCause().getMessage());
- }
- Fields luceneTermVectors = getTermVectorsFromLucene(directoryReader, test.doc);
- validateResponse(item.getResponse(), luceneTermVectors, test);
- } catch (Throwable t) {
- throw new Exception("Test exception while running " + test.toString(), t);
+ MultiTermVectorsItemResponse item = responseItems[i];
+ if (test.expectedException != null) {
+ assertTrue(item.isFailed());
+ continue;
+ } else if (item.isFailed()) {
+ fail(item.getFailure().getCause().getMessage());
}
+ Fields luceneTermVectors = getTermVectorsFromLucene(directoryReader, test.doc);
+ validateResponse(item.getResponse(), luceneTermVectors, test);
}
-
}
public void testMissingIndexThrowsMissingIndex() throws Exception {
diff --git a/core/src/test/java/org/elasticsearch/action/update/UpdateRequestTests.java b/core/src/test/java/org/elasticsearch/action/update/UpdateRequestTests.java
index 597a2a4db39..a98433a1007 100644
--- a/core/src/test/java/org/elasticsearch/action/update/UpdateRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/update/UpdateRequestTests.java
@@ -59,6 +59,18 @@ public class UpdateRequestTests extends ESTestCase {
Map params = script.getParams();
assertThat(params, nullValue());
+ // simple verbose script
+ request.source(XContentFactory.jsonBuilder().startObject()
+ .startObject("script").field("inline", "script1").endObject()
+ .endObject());
+ script = request.script();
+ assertThat(script, notNullValue());
+ assertThat(script.getScript(), equalTo("script1"));
+ assertThat(script.getType(), equalTo(ScriptType.INLINE));
+ assertThat(script.getLang(), nullValue());
+ params = script.getParams();
+ assertThat(params, nullValue());
+
// script with params
request = new UpdateRequest("test", "type", "1");
request.source(XContentFactory.jsonBuilder().startObject().startObject("script").field("inline", "script1").startObject("params")
@@ -135,7 +147,7 @@ public class UpdateRequestTests extends ESTestCase {
TimeValue providedTTLValue = TimeValue.parseTimeValue(randomTimeValue(), null, "ttl");
Settings settings = settings(Version.CURRENT).build();
- UpdateHelper updateHelper = new UpdateHelper(settings, null, null);
+ UpdateHelper updateHelper = new UpdateHelper(settings, null);
// We just upsert one document with ttl
IndexRequest indexRequest = new IndexRequest("test", "type1", "1")
diff --git a/core/src/test/java/org/elasticsearch/aliases/IndexAliasesIT.java b/core/src/test/java/org/elasticsearch/aliases/IndexAliasesIT.java
index 5ac1bf40af6..28d068d7608 100644
--- a/core/src/test/java/org/elasticsearch/aliases/IndexAliasesIT.java
+++ b/core/src/test/java/org/elasticsearch/aliases/IndexAliasesIT.java
@@ -951,8 +951,6 @@ public class IndexAliasesIT extends ESIntegTestCase {
createIndex("index1");
createIndex("index2");
- ensureYellow();
-
assertAcked(admin().indices().prepareAliases().addAlias("index1", "alias1").addAlias("index2", "alias2"));
GetAliasesResponse response = admin().indices().prepareGetAliases().get();
diff --git a/core/src/test/java/org/elasticsearch/blocks/SimpleBlocksIT.java b/core/src/test/java/org/elasticsearch/blocks/SimpleBlocksIT.java
index ffe82f9388d..699b919cf05 100644
--- a/core/src/test/java/org/elasticsearch/blocks/SimpleBlocksIT.java
+++ b/core/src/test/java/org/elasticsearch/blocks/SimpleBlocksIT.java
@@ -141,15 +141,6 @@ public class SimpleBlocksIT extends ESIntegTestCase {
}
}
- private void canNotIndexExists(String index) {
- try {
- IndicesExistsResponse r = client().admin().indices().prepareExists(index).execute().actionGet();
- fail();
- } catch (ClusterBlockException e) {
- // all is well
- }
- }
-
private void setIndexReadOnly(String index, Object value) {
HashMap newSettings = new HashMap<>();
newSettings.put(IndexMetaData.SETTING_READ_ONLY, value);
diff --git a/core/src/test/java/org/elasticsearch/bootstrap/BootstrapCheckTests.java b/core/src/test/java/org/elasticsearch/bootstrap/BootstrapCheckTests.java
index 5336066b1e2..1c4cd5b4e87 100644
--- a/core/src/test/java/org/elasticsearch/bootstrap/BootstrapCheckTests.java
+++ b/core/src/test/java/org/elasticsearch/bootstrap/BootstrapCheckTests.java
@@ -44,6 +44,7 @@ import static org.hamcrest.Matchers.not;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class BootstrapCheckTests extends ESTestCase {
@@ -65,6 +66,23 @@ public class BootstrapCheckTests extends ESTestCase {
BootstrapCheck.check(Settings.EMPTY, boundTransportAddress);
}
+ public void testNoLogMessageInNonProductionMode() {
+ final ESLogger logger = mock(ESLogger.class);
+ BootstrapCheck.check(false, randomBoolean(), Collections.emptyList(), logger);
+ verifyNoMoreInteractions(logger);
+ }
+
+ public void testLogMessageInProductionMode() {
+ final ESLogger logger = mock(ESLogger.class);
+ final boolean ignoreSystemChecks = randomBoolean();
+ BootstrapCheck.check(true, ignoreSystemChecks, Collections.emptyList(), logger);
+ verify(logger).info("bound or publishing to a non-loopback or non-link-local address, enforcing bootstrap checks");
+ if (ignoreSystemChecks) {
+ verify(logger).warn("enforcing bootstrap checks but ignoring system bootstrap checks, consider not ignoring system checks");
+ }
+ verifyNoMoreInteractions(logger);
+ }
+
public void testEnforceLimitsWhenBoundToNonLocalAddress() {
final List transportAddresses = new ArrayList<>();
final TransportAddress nonLocalTransportAddress = mock(TransportAddress.class);
@@ -545,12 +563,16 @@ public class BootstrapCheckTests extends ESTestCase {
// nothing should happen if we ignore system checks
BootstrapCheck.check(true, true, Collections.singletonList(check), logger);
+ verify(logger).info("bound or publishing to a non-loopback or non-link-local address, enforcing bootstrap checks");
+ verify(logger).warn("enforcing bootstrap checks but ignoring system bootstrap checks, consider not ignoring system checks");
verify(logger).warn("error");
+ verifyNoMoreInteractions(logger);
reset(logger);
// nothing should happen if we ignore all checks
BootstrapCheck.check(false, randomBoolean(), Collections.singletonList(check), logger);
verify(logger).warn("error");
+ verifyNoMoreInteractions(logger);
}
public void testAlwaysEnforcedChecks() {
diff --git a/core/src/test/java/org/elasticsearch/bootstrap/ElasticsearchCliTests.java b/core/src/test/java/org/elasticsearch/bootstrap/ElasticsearchCliTests.java
index 8b8a4d947a9..f8bdf244999 100644
--- a/core/src/test/java/org/elasticsearch/bootstrap/ElasticsearchCliTests.java
+++ b/core/src/test/java/org/elasticsearch/bootstrap/ElasticsearchCliTests.java
@@ -24,10 +24,12 @@ import org.elasticsearch.Version;
import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.monitor.jvm.JvmInfo;
+import java.nio.file.Path;
import java.util.function.Consumer;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.hasEntry;
public class ElasticsearchCliTests extends ESElasticsearchCliTestCase {
@@ -50,7 +52,8 @@ public class ElasticsearchCliTests extends ESElasticsearchCliTestCase {
ExitCodes.USAGE,
output -> assertThat(
output,
- containsString("ERROR: Elasticsearch version option is mutually exclusive with any other option")),
+ allOf(containsString("ERROR:"),
+ containsString("are unavailable given other options on the command line"))),
args);
}
@@ -91,18 +94,22 @@ public class ElasticsearchCliTests extends ESElasticsearchCliTestCase {
}
public void testThatPidFileCanBeConfigured() throws Exception {
- runPidFileTest(ExitCodes.USAGE, false, output -> assertThat(output, containsString("Option p/pidfile requires an argument")), "-p");
- runPidFileTest(ExitCodes.OK, true, output -> {}, "-p", "/tmp/pid");
- runPidFileTest(ExitCodes.OK, true, output -> {}, "--pidfile", "/tmp/pid");
+ Path tmpDir = createTempDir();
+ Path pidFile = tmpDir.resolve("pid");
+ runPidFileTest(ExitCodes.USAGE, false,
+ output -> assertThat(output, containsString("Option p/pidfile requires an argument")), pidFile, "-p");
+ runPidFileTest(ExitCodes.OK, true, output -> {}, pidFile, "-p", pidFile.toString());
+ runPidFileTest(ExitCodes.OK, true, output -> {}, pidFile, "--pidfile", tmpDir.toString() + "/pid");
}
- private void runPidFileTest(final int expectedStatus, final boolean expectedInit, Consumer outputConsumer, final String... args)
+ private void runPidFileTest(final int expectedStatus, final boolean expectedInit, Consumer outputConsumer,
+ Path expectedPidFile, final String... args)
throws Exception {
runTest(
expectedStatus,
expectedInit,
outputConsumer,
- (foreground, pidFile, esSettings) -> assertThat(pidFile, equalTo("/tmp/pid")),
+ (foreground, pidFile, esSettings) -> assertThat(pidFile.toString(), equalTo(expectedPidFile.toString())),
args);
}
diff --git a/core/src/test/java/org/elasticsearch/bootstrap/ElasticsearchUncaughtExceptionHandlerTests.java b/core/src/test/java/org/elasticsearch/bootstrap/ElasticsearchUncaughtExceptionHandlerTests.java
new file mode 100644
index 00000000000..e4ff83e9b40
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/bootstrap/ElasticsearchUncaughtExceptionHandlerTests.java
@@ -0,0 +1,152 @@
+/*
+ * 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.bootstrap;
+
+import org.apache.lucene.index.MergePolicy;
+import org.elasticsearch.test.ESTestCase;
+import org.junit.Before;
+
+import java.io.IOError;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+
+public class ElasticsearchUncaughtExceptionHandlerTests extends ESTestCase {
+
+ private Map, Integer> expectedStatus;
+
+ @Before
+ public void setUp() throws Exception {
+ super.setUp();
+ Map, Integer> expectedStatus = new HashMap<>();
+ expectedStatus.put(InternalError.class, 128);
+ expectedStatus.put(OutOfMemoryError.class, 127);
+ expectedStatus.put(StackOverflowError.class, 126);
+ expectedStatus.put(UnknownError.class, 125);
+ expectedStatus.put(IOError.class, 124);
+ this.expectedStatus = Collections.unmodifiableMap(expectedStatus);
+ }
+
+ public void testUncaughtError() throws InterruptedException {
+ final Error error = randomFrom(
+ new InternalError(),
+ new OutOfMemoryError(),
+ new StackOverflowError(),
+ new UnknownError(),
+ new IOError(new IOException("fatal")),
+ new Error() {});
+ final Thread thread = new Thread(() -> { throw error; });
+ final String name = randomAsciiOfLength(10);
+ thread.setName(name);
+ final AtomicBoolean halt = new AtomicBoolean();
+ final AtomicInteger observedStatus = new AtomicInteger();
+ final AtomicReference threadNameReference = new AtomicReference<>();
+ final AtomicReference throwableReference = new AtomicReference<>();
+ thread.setUncaughtExceptionHandler(new ElasticsearchUncaughtExceptionHandler(() -> "testUncaughtError") {
+
+ @Override
+ void halt(int status) {
+ halt.set(true);
+ observedStatus.set(status);
+ }
+
+ @Override
+ void onFatalUncaught(String threadName, Throwable t) {
+ threadNameReference.set(threadName);
+ throwableReference.set(t);
+ }
+
+ @Override
+ void onNonFatalUncaught(String threadName, Throwable t) {
+ fail();
+ }
+
+ });
+ thread.start();
+ thread.join();
+ assertTrue(halt.get());
+ final int status;
+ if (expectedStatus.containsKey(error.getClass())) {
+ status = expectedStatus.get(error.getClass());
+ } else {
+ status = 1;
+ }
+ assertThat(observedStatus.get(), equalTo(status));
+ assertThat(threadNameReference.get(), equalTo(name));
+ assertThat(throwableReference.get(), equalTo(error));
+ }
+
+ public void testUncaughtException() throws InterruptedException {
+ final RuntimeException e = new RuntimeException("boom");
+ final Thread thread = new Thread(() -> { throw e; });
+ final String name = randomAsciiOfLength(10);
+ thread.setName(name);
+ final AtomicReference threadNameReference = new AtomicReference<>();
+ final AtomicReference throwableReference = new AtomicReference<>();
+ thread.setUncaughtExceptionHandler(new ElasticsearchUncaughtExceptionHandler(() -> "testUncaughtException") {
+ @Override
+ void halt(int status) {
+ fail();
+ }
+
+ @Override
+ void onFatalUncaught(String threadName, Throwable t) {
+ fail();
+ }
+
+ @Override
+ void onNonFatalUncaught(String threadName, Throwable t) {
+ threadNameReference.set(threadName);
+ throwableReference.set(t);
+ }
+ });
+ thread.start();
+ thread.join();
+ assertThat(threadNameReference.get(), equalTo(name));
+ assertThat(throwableReference.get(), equalTo(e));
+ }
+
+ public void testIsFatalCause() {
+ assertFatal(new MergePolicy.MergeException(new OutOfMemoryError(), null));
+ assertFatal(new OutOfMemoryError());
+ assertFatal(new StackOverflowError());
+ assertFatal(new InternalError());
+ assertFatal(new UnknownError());
+ assertFatal(new IOError(new IOException()));
+ assertNonFatal(new RuntimeException());
+ assertNonFatal(new UncheckedIOException(new IOException()));
+ }
+
+ private void assertFatal(Throwable cause) {
+ assertTrue(ElasticsearchUncaughtExceptionHandler.isFatalUncaught(cause));
+ }
+
+ private void assertNonFatal(Throwable cause) {
+ assertFalse(ElasticsearchUncaughtExceptionHandler.isFatalUncaught(cause));
+ }
+
+}
diff --git a/core/src/test/java/org/elasticsearch/broadcast/BroadcastActionsIT.java b/core/src/test/java/org/elasticsearch/broadcast/BroadcastActionsIT.java
index f60709d6da0..63091a97818 100644
--- a/core/src/test/java/org/elasticsearch/broadcast/BroadcastActionsIT.java
+++ b/core/src/test/java/org/elasticsearch/broadcast/BroadcastActionsIT.java
@@ -44,8 +44,6 @@ public class BroadcastActionsIT extends ESIntegTestCase {
NumShards numShards = getNumShards("test");
logger.info("Running Cluster Health");
- ensureYellow();
-
client().index(indexRequest("test").type("type1").id("1").source(source("1", "test"))).actionGet();
flush();
client().index(indexRequest("test").type("type1").id("2").source(source("2", "test"))).actionGet();
diff --git a/core/src/test/java/org/elasticsearch/bwcompat/BasicAnalysisBackwardCompatibilityIT.java b/core/src/test/java/org/elasticsearch/bwcompat/BasicAnalysisBackwardCompatibilityIT.java
index 40995ff778b..f1451255b60 100644
--- a/core/src/test/java/org/elasticsearch/bwcompat/BasicAnalysisBackwardCompatibilityIT.java
+++ b/core/src/test/java/org/elasticsearch/bwcompat/BasicAnalysisBackwardCompatibilityIT.java
@@ -41,7 +41,7 @@ import static org.hamcrest.Matchers.equalTo;
public class BasicAnalysisBackwardCompatibilityIT extends ESBackcompatTestCase {
// This pattern match characters with Line_Break = Complex_Content.
- final static Pattern complexUnicodeChars = Pattern.compile("[\u17B4\u17B5\u17D3\u17CB-\u17D1\u17DD\u1036\u17C6\u1A74\u1038\u17C7\u0E4E\u0E47-\u0E4D\u0EC8-\u0ECD\uAABF\uAAC1\u1037\u17C8-\u17CA\u1A75-\u1A7C\u1AA8-\u1AAB\uAADE\uAADF\u1AA0-\u1AA6\u1AAC\u1AAD\u109E\u109F\uAA77-\uAA79\u0E46\u0EC6\u17D7\u1AA7\uA9E6\uAA70\uAADD\u19DA\u0E01-\u0E3A\u0E40-\u0E45\u0EDE\u0E81\u0E82\u0E84\u0E87\u0E88\u0EAA\u0E8A\u0EDF\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAB\u0EDC\u0EDD\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\uAA80-\uAABE\uAAC0\uAAC2\uAADB\uAADC\u1000\u1075\u1001\u1076\u1002\u1077\uAA60\uA9E9\u1003\uA9E0\uA9EA\u1004\u105A\u1005\u1078\uAA61\u1006\uA9E1\uAA62\uAA7E\u1007\uAA63\uA9EB\u1079\uAA72\u1008\u105B\uA9E2\uAA64\uA9EC\u1061\uAA7F\u1009\u107A\uAA65\uA9E7\u100A\u100B\uAA66\u100C\uAA67\u100D\uAA68\uA9ED\u100E\uAA69\uA9EE\u100F\u106E\uA9E3\uA9EF\u1010-\u1012\u107B\uA9FB\u1013\uAA6A\uA9FC\u1014\u107C\uAA6B\u105E\u1015\u1016\u107D\u107E\uAA6F\u108E\uA9E8\u1017\u107F\uA9FD\u1018\uA9E4\uA9FE\u1019\u105F\u101A\u103B\u101B\uAA73\uAA7A\u103C\u101C\u1060\u101D\u103D\u1082\u1080\u1050\u1051\u1065\u101E\u103F\uAA6C\u101F\u1081\uAA6D\u103E\uAA6E\uAA71\u1020\uA9FA\u105C\u105D\u106F\u1070\u1066\u1021-\u1026\u1052-\u1055\u1027-\u102A\u102C\u102B\u1083\u1072\u109C\u102D\u1071\u102E\u1033\u102F\u1073\u1074\u1030\u1056-\u1059\u1031\u1084\u1035\u1085\u1032\u109D\u1034\u1062\u1067\u1068\uA9E5\u1086\u1039\u103A\u1063\u1064\u1069-\u106D\u1087\u108B\u1088\u108C\u108D\u1089\u108A\u108F\u109A\u109B\uAA7B-\uAA7D\uAA74-\uAA76\u1780-\u17A2\u17DC\u17A3-\u17B3\u17B6-\u17C5\u17D2\u1950-\u196D\u1970-\u1974\u1980-\u199C\u19DE\u19DF\u199D-\u19AB\u19B0-\u19C9\u1A20-\u1A26\u1A58\u1A59\u1A27-\u1A3B\u1A5A\u1A5B\u1A3C-\u1A46\u1A54\u1A47-\u1A4C\u1A53\u1A6B\u1A55-\u1A57\u1A5C-\u1A5E\u1A4D-\u1A52\u1A61\u1A6C\u1A62-\u1A6A\u1A6E\u1A6F\u1A73\u1A70-\u1A72\u1A6D\u1A60]");
+ static final Pattern complexUnicodeChars = Pattern.compile("[\u17B4\u17B5\u17D3\u17CB-\u17D1\u17DD\u1036\u17C6\u1A74\u1038\u17C7\u0E4E\u0E47-\u0E4D\u0EC8-\u0ECD\uAABF\uAAC1\u1037\u17C8-\u17CA\u1A75-\u1A7C\u1AA8-\u1AAB\uAADE\uAADF\u1AA0-\u1AA6\u1AAC\u1AAD\u109E\u109F\uAA77-\uAA79\u0E46\u0EC6\u17D7\u1AA7\uA9E6\uAA70\uAADD\u19DA\u0E01-\u0E3A\u0E40-\u0E45\u0EDE\u0E81\u0E82\u0E84\u0E87\u0E88\u0EAA\u0E8A\u0EDF\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAB\u0EDC\u0EDD\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\uAA80-\uAABE\uAAC0\uAAC2\uAADB\uAADC\u1000\u1075\u1001\u1076\u1002\u1077\uAA60\uA9E9\u1003\uA9E0\uA9EA\u1004\u105A\u1005\u1078\uAA61\u1006\uA9E1\uAA62\uAA7E\u1007\uAA63\uA9EB\u1079\uAA72\u1008\u105B\uA9E2\uAA64\uA9EC\u1061\uAA7F\u1009\u107A\uAA65\uA9E7\u100A\u100B\uAA66\u100C\uAA67\u100D\uAA68\uA9ED\u100E\uAA69\uA9EE\u100F\u106E\uA9E3\uA9EF\u1010-\u1012\u107B\uA9FB\u1013\uAA6A\uA9FC\u1014\u107C\uAA6B\u105E\u1015\u1016\u107D\u107E\uAA6F\u108E\uA9E8\u1017\u107F\uA9FD\u1018\uA9E4\uA9FE\u1019\u105F\u101A\u103B\u101B\uAA73\uAA7A\u103C\u101C\u1060\u101D\u103D\u1082\u1080\u1050\u1051\u1065\u101E\u103F\uAA6C\u101F\u1081\uAA6D\u103E\uAA6E\uAA71\u1020\uA9FA\u105C\u105D\u106F\u1070\u1066\u1021-\u1026\u1052-\u1055\u1027-\u102A\u102C\u102B\u1083\u1072\u109C\u102D\u1071\u102E\u1033\u102F\u1073\u1074\u1030\u1056-\u1059\u1031\u1084\u1035\u1085\u1032\u109D\u1034\u1062\u1067\u1068\uA9E5\u1086\u1039\u103A\u1063\u1064\u1069-\u106D\u1087\u108B\u1088\u108C\u108D\u1089\u108A\u108F\u109A\u109B\uAA7B-\uAA7D\uAA74-\uAA76\u1780-\u17A2\u17DC\u17A3-\u17B3\u17B6-\u17C5\u17D2\u1950-\u196D\u1970-\u1974\u1980-\u199C\u19DE\u19DF\u199D-\u19AB\u19B0-\u19C9\u1A20-\u1A26\u1A58\u1A59\u1A27-\u1A3B\u1A5A\u1A5B\u1A3C-\u1A46\u1A54\u1A47-\u1A4C\u1A53\u1A6B\u1A55-\u1A57\u1A5C-\u1A5E\u1A4D-\u1A52\u1A61\u1A6C\u1A62-\u1A6A\u1A6E\u1A6F\u1A73\u1A70-\u1A72\u1A6D\u1A60]");
/**
* Simple upgrade test for analyzers to make sure they analyze to the same tokens after upgrade
@@ -59,7 +59,6 @@ public class BasicAnalysisBackwardCompatibilityIT extends ESBackcompatTestCase {
assertAcked(prepareCreate("test")
.addMapping("type", (Object[])fields)
.setSettings(indexSettings()));
- ensureYellow();
InputOutput[] inout = new InputOutput[numFields];
for (int i = 0; i < numFields; i++) {
String input;
diff --git a/core/src/test/java/org/elasticsearch/bwcompat/BasicBackwardsCompatibilityIT.java b/core/src/test/java/org/elasticsearch/bwcompat/BasicBackwardsCompatibilityIT.java
index 8db5b1536e8..e6d47a63bb6 100644
--- a/core/src/test/java/org/elasticsearch/bwcompat/BasicBackwardsCompatibilityIT.java
+++ b/core/src/test/java/org/elasticsearch/bwcompat/BasicBackwardsCompatibilityIT.java
@@ -155,7 +155,6 @@ public class BasicBackwardsCompatibilityIT extends ESBackcompatTestCase {
backwardsCluster().startNewNode();
}
assertAcked(prepareCreate("test").setSettings(Settings.builder().put("index.routing.allocation.exclude._name", backwardsCluster().newNodePattern()).put(indexSettings())));
- ensureYellow();
assertAllShardsOnNodes("test", backwardsCluster().backwardsNodePattern());
int numDocs = randomIntBetween(100, 150);
ArrayList ids = new ArrayList<>();
@@ -271,7 +270,6 @@ public class BasicBackwardsCompatibilityIT extends ESBackcompatTestCase {
*/
public void testIndexUpgradeSingleNode() throws Exception {
assertAcked(prepareCreate("test").setSettings(Settings.builder().put("index.routing.allocation.exclude._name", backwardsCluster().newNodePattern()).put(indexSettings())));
- ensureYellow();
int numDocs = randomIntBetween(100, 150);
IndexRequestBuilder[] docs = new IndexRequestBuilder[numDocs];
for (int i = 0; i < numDocs; i++) {
@@ -403,7 +401,6 @@ public class BasicBackwardsCompatibilityIT extends ESBackcompatTestCase {
for (; ; ) {
indexName = "test_"+indexId++;
createIndex(indexName);
- ensureYellow();
indexRandom(true,
client().prepareIndex(indexName, "type1", "1").setSource(jsonBuilder().startObject().startObject("obj1").field("obj1_val", "1").endObject().field("x1", "x_1").field("field1", "value1_1").field("field2", "value2_1").endObject()),
client().prepareIndex(indexName, "type1", "2").setSource(jsonBuilder().startObject().startObject("obj1").field("obj1_val", "1").endObject().field("x2", "x_2").field("field1", "value1_2").endObject()),
@@ -490,7 +487,6 @@ public class BasicBackwardsCompatibilityIT extends ESBackcompatTestCase {
public void testIndexGetAndDelete() throws ExecutionException, InterruptedException {
createIndexWithAlias();
- ensureYellow("test");
int numDocs = iterations(10, 50);
for (int i = 0; i < numDocs; i++) {
@@ -526,7 +522,6 @@ public class BasicBackwardsCompatibilityIT extends ESBackcompatTestCase {
public void testUpdate() {
createIndexWithAlias();
- ensureYellow("test");
UpdateRequestBuilder updateRequestBuilder = client().prepareUpdate(indexOrAlias(), "type1", "1")
.setUpsert("field1", "value1").setDoc("field2", "value2");
@@ -557,7 +552,6 @@ public class BasicBackwardsCompatibilityIT extends ESBackcompatTestCase {
public void testAnalyze() {
createIndexWithAlias();
assertAcked(client().admin().indices().preparePutMapping("test").setType("test").setSource("field", "type=text,analyzer=keyword"));
- ensureYellow("test");
AnalyzeResponse analyzeResponse = client().admin().indices().prepareAnalyze("this is a test").setIndex(indexOrAlias()).setField("field").get();
assertThat(analyzeResponse.getTokens().size(), equalTo(1));
assertThat(analyzeResponse.getTokens().get(0).getTerm(), equalTo("this is a test"));
@@ -565,7 +559,6 @@ public class BasicBackwardsCompatibilityIT extends ESBackcompatTestCase {
public void testExplain() {
createIndexWithAlias();
- ensureYellow("test");
client().prepareIndex(indexOrAlias(), "test", "1").setSource("field", "value1").get();
refresh();
@@ -582,7 +575,6 @@ public class BasicBackwardsCompatibilityIT extends ESBackcompatTestCase {
public void testGetTermVector() throws IOException {
createIndexWithAlias();
assertAcked(client().admin().indices().preparePutMapping("test").setType("type1").setSource("field", "type=text,term_vector=with_positions_offsets_payloads").get());
- ensureYellow("test");
client().prepareIndex(indexOrAlias(), "type1", "1")
.setSource("field", "the quick brown fox jumps over the lazy dog").get();
@@ -598,7 +590,6 @@ public class BasicBackwardsCompatibilityIT extends ESBackcompatTestCase {
public void testIndicesStats() {
createIndex("test");
- ensureYellow("test");
IndicesStatsResponse indicesStatsResponse = client().admin().indices().prepareStats().all().get();
assertThat(indicesStatsResponse.getIndices().size(), equalTo(1));
@@ -607,7 +598,6 @@ public class BasicBackwardsCompatibilityIT extends ESBackcompatTestCase {
public void testMultiGet() throws ExecutionException, InterruptedException {
createIndexWithAlias();
- ensureYellow("test");
int numDocs = iterations(10, 50);
IndexRequestBuilder[] indexRequestBuilders = new IndexRequestBuilder[numDocs];
@@ -639,7 +629,6 @@ public class BasicBackwardsCompatibilityIT extends ESBackcompatTestCase {
public void testScroll() throws ExecutionException, InterruptedException {
createIndex("test");
- ensureYellow("test");
int numDocs = iterations(10, 100);
IndexRequestBuilder[] indexRequestBuilders = new IndexRequestBuilder[numDocs];
diff --git a/core/src/test/java/org/elasticsearch/bwcompat/ClusterStateBackwardsCompatIT.java b/core/src/test/java/org/elasticsearch/bwcompat/ClusterStateBackwardsCompatIT.java
index a4427befea2..eb6648cad02 100644
--- a/core/src/test/java/org/elasticsearch/bwcompat/ClusterStateBackwardsCompatIT.java
+++ b/core/src/test/java/org/elasticsearch/bwcompat/ClusterStateBackwardsCompatIT.java
@@ -30,6 +30,7 @@ import org.elasticsearch.cluster.block.ClusterBlocks;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESBackcompatTestCase;
+import org.elasticsearch.transport.MockTransportClient;
import java.util.HashMap;
import java.util.Map;
@@ -101,6 +102,6 @@ public class ClusterStateBackwardsCompatIT extends ESBackcompatTestCase {
private TransportClient newTransportClient() {
Settings settings = Settings.builder().put("client.transport.ignore_cluster_name", true)
.put("node.name", "transport_client_" + getTestName()).build();
- return TransportClient.builder().settings(settings).build();
+ return new MockTransportClient(settings);
}
}
diff --git a/core/src/test/java/org/elasticsearch/bwcompat/NodesStatsBasicBackwardsCompatIT.java b/core/src/test/java/org/elasticsearch/bwcompat/NodesStatsBasicBackwardsCompatIT.java
index c9d5f0b622e..03f7f21ec55 100644
--- a/core/src/test/java/org/elasticsearch/bwcompat/NodesStatsBasicBackwardsCompatIT.java
+++ b/core/src/test/java/org/elasticsearch/bwcompat/NodesStatsBasicBackwardsCompatIT.java
@@ -22,11 +22,11 @@ package org.elasticsearch.bwcompat;
import org.elasticsearch.action.admin.cluster.node.info.NodeInfo;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsRequestBuilder;
-import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESBackcompatTestCase;
import org.elasticsearch.test.ESIntegTestCase;
+import org.elasticsearch.transport.MockTransportClient;
import java.lang.reflect.Method;
@@ -44,9 +44,9 @@ public class NodesStatsBasicBackwardsCompatIT extends ESBackcompatTestCase {
// We explicitly connect to each node with a custom TransportClient
for (NodeInfo n : nodesInfo.getNodes()) {
- TransportClient tc = TransportClient.builder().settings(settings).build().addTransportAddress(n.getNode().getAddress());
+ TransportClient tc = new MockTransportClient(settings).addTransportAddress(n.getNode().getAddress());
// Just verify that the NS can be sent and serialized/deserialized between nodes with basic indices
- NodesStatsResponse ns = tc.admin().cluster().prepareNodesStats().setIndices(true).execute().actionGet();
+ tc.admin().cluster().prepareNodesStats().setIndices(true).execute().actionGet();
tc.close();
}
}
@@ -62,7 +62,7 @@ public class NodesStatsBasicBackwardsCompatIT extends ESBackcompatTestCase {
// We explicitly connect to each node with a custom TransportClient
for (NodeInfo n : nodesInfo.getNodes()) {
- TransportClient tc = TransportClient.builder().settings(settings).build().addTransportAddress(n.getNode().getAddress());
+ TransportClient tc = new MockTransportClient(settings).addTransportAddress(n.getNode().getAddress());
// randomize the combination of flags set
// Uses reflection to find methods in an attempt to future-proof this test against newly added flags
@@ -78,7 +78,7 @@ public class NodesStatsBasicBackwardsCompatIT extends ESBackcompatTestCase {
method.invoke(nsBuilder);
}
}
- NodesStatsResponse ns = nsBuilder.execute().actionGet();
+ nsBuilder.execute().actionGet();
tc.close();
}
diff --git a/core/src/test/java/org/elasticsearch/bwcompat/RecoveryWithUnsupportedIndicesIT.java b/core/src/test/java/org/elasticsearch/bwcompat/RecoveryWithUnsupportedIndicesIT.java
index 9fe83f65c45..429266c4589 100644
--- a/core/src/test/java/org/elasticsearch/bwcompat/RecoveryWithUnsupportedIndicesIT.java
+++ b/core/src/test/java/org/elasticsearch/bwcompat/RecoveryWithUnsupportedIndicesIT.java
@@ -18,9 +18,7 @@
*/
package org.elasticsearch.bwcompat;
-import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.node.Node;
import static org.hamcrest.Matchers.containsString;
@@ -29,7 +27,7 @@ public class RecoveryWithUnsupportedIndicesIT extends StaticIndexBackwardCompati
String indexName = "unsupported-0.20.6";
logger.info("Checking static index {}", indexName);
- Settings nodeSettings = prepareBackwardsDataDir(getBwcIndicesPath().resolve(indexName + ".zip"), NetworkModule.HTTP_ENABLED.getKey(), true);
+ Settings nodeSettings = prepareBackwardsDataDir(getBwcIndicesPath().resolve(indexName + ".zip"));
try {
internalCluster().startNode(nodeSettings);
fail();
diff --git a/core/src/test/java/org/elasticsearch/bwcompat/RepositoryUpgradabilityIT.java b/core/src/test/java/org/elasticsearch/bwcompat/RepositoryUpgradabilityIT.java
index e1873850703..c29d83b4454 100644
--- a/core/src/test/java/org/elasticsearch/bwcompat/RepositoryUpgradabilityIT.java
+++ b/core/src/test/java/org/elasticsearch/bwcompat/RepositoryUpgradabilityIT.java
@@ -26,6 +26,7 @@ import org.elasticsearch.snapshots.AbstractSnapshotIntegTestCase;
import org.elasticsearch.snapshots.SnapshotId;
import org.elasticsearch.snapshots.SnapshotInfo;
import org.elasticsearch.test.ESIntegTestCase;
+import org.elasticsearch.test.junit.annotations.TestLogging;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
@@ -45,6 +46,8 @@ import static org.hamcrest.Matchers.greaterThanOrEqualTo;
* as blob names and repository blob formats have changed between the snapshot versions.
*/
@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.TEST)
+// this test sometimes fails in recovery when the recovery is reset, increasing the logging level to help debug
+@TestLogging("indices.recovery:DEBUG")
public class RepositoryUpgradabilityIT extends AbstractSnapshotIntegTestCase {
/**
diff --git a/core/src/test/java/org/elasticsearch/bwcompat/TransportClientBackwardsCompatibilityIT.java b/core/src/test/java/org/elasticsearch/bwcompat/TransportClientBackwardsCompatibilityIT.java
index b1fc1d45dca..3f0daaa3157 100644
--- a/core/src/test/java/org/elasticsearch/bwcompat/TransportClientBackwardsCompatibilityIT.java
+++ b/core/src/test/java/org/elasticsearch/bwcompat/TransportClientBackwardsCompatibilityIT.java
@@ -29,6 +29,7 @@ import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.test.CompositeTestCluster;
import org.elasticsearch.test.ESBackcompatTestCase;
+import org.elasticsearch.transport.MockTransportClient;
import java.util.concurrent.ExecutionException;
@@ -45,11 +46,10 @@ public class TransportClientBackwardsCompatibilityIT extends ESBackcompatTestCas
CompositeTestCluster compositeTestCluster = backwardsCluster();
TransportAddress transportAddress = compositeTestCluster.externalTransportAddress();
- try(TransportClient client = TransportClient.builder().settings(settings).build()) {
+ try(TransportClient client = new MockTransportClient(settings)) {
client.addTransportAddress(transportAddress);
assertAcked(client.admin().indices().prepareCreate("test"));
- ensureYellow("test");
int numDocs = iterations(10, 100);
IndexRequestBuilder[] indexRequestBuilders = new IndexRequestBuilder[numDocs];
diff --git a/core/src/test/java/org/elasticsearch/cli/CommandTests.java b/core/src/test/java/org/elasticsearch/cli/CommandTests.java
index 1f50ad4c13b..0da487e7b9d 100644
--- a/core/src/test/java/org/elasticsearch/cli/CommandTests.java
+++ b/core/src/test/java/org/elasticsearch/cli/CommandTests.java
@@ -19,6 +19,7 @@
package org.elasticsearch.cli;
+import joptsimple.OptionException;
import joptsimple.OptionSet;
import org.elasticsearch.test.ESTestCase;
@@ -30,7 +31,7 @@ public class CommandTests extends ESTestCase {
}
@Override
protected void execute(Terminal terminal, OptionSet options) throws Exception {
- throw new UserError(ExitCodes.DATA_ERROR, "Bad input");
+ throw new UserException(ExitCodes.DATA_ERROR, "Bad input");
}
}
@@ -40,7 +41,7 @@ public class CommandTests extends ESTestCase {
}
@Override
protected void execute(Terminal terminal, OptionSet options) throws Exception {
- throw new UserError(ExitCodes.USAGE, "something was no good");
+ throw new UserException(ExitCodes.USAGE, "something was no good");
}
}
@@ -87,10 +88,11 @@ public class CommandTests extends ESTestCase {
MockTerminal terminal = new MockTerminal();
NoopCommand command = new NoopCommand();
String[] args = {"-v", "-s"};
- UserError e = expectThrows(UserError.class, () -> {
+ OptionException e = expectThrows(OptionException.class, () -> {
command.mainWithoutErrorHandling(args, terminal);
});
- assertTrue(e.getMessage(), e.getMessage().contains("Cannot specify -s and -v together"));
+ assertTrue(e.getMessage(),
+ e.getMessage().contains("Option(s) [v/verbose] are unavailable given other options on the command line"));
}
public void testSilentVerbosity() throws Exception {
diff --git a/core/src/test/java/org/elasticsearch/cli/MultiCommandTests.java b/core/src/test/java/org/elasticsearch/cli/MultiCommandTests.java
index 4f91d378440..f4680492028 100644
--- a/core/src/test/java/org/elasticsearch/cli/MultiCommandTests.java
+++ b/core/src/test/java/org/elasticsearch/cli/MultiCommandTests.java
@@ -61,7 +61,7 @@ public class MultiCommandTests extends CommandTestCase {
public void testUnknownCommand() throws Exception {
multiCommand.subcommands.put("something", new DummySubCommand());
- UserError e = expectThrows(UserError.class, () -> {
+ UserException e = expectThrows(UserException.class, () -> {
execute("somethingelse");
});
assertEquals(ExitCodes.USAGE, e.exitCode);
@@ -70,7 +70,7 @@ public class MultiCommandTests extends CommandTestCase {
public void testMissingCommand() throws Exception {
multiCommand.subcommands.put("command1", new DummySubCommand());
- UserError e = expectThrows(UserError.class, () -> {
+ UserException e = expectThrows(UserException.class, () -> {
execute();
});
assertEquals(ExitCodes.USAGE, e.exitCode);
diff --git a/core/src/test/java/org/elasticsearch/client/AbstractClientHeadersTestCase.java b/core/src/test/java/org/elasticsearch/client/AbstractClientHeadersTestCase.java
index 196b053ff82..276a43581a6 100644
--- a/core/src/test/java/org/elasticsearch/client/AbstractClientHeadersTestCase.java
+++ b/core/src/test/java/org/elasticsearch/client/AbstractClientHeadersTestCase.java
@@ -179,7 +179,7 @@ public abstract class AbstractClientHeadersTestCase extends ESTestCase {
}
@Override
- public void onFailure(Throwable t) {
+ public void onFailure(Exception t) {
Throwable e = unwrap(t, InternalException.class);
assertThat("expected action [" + action + "] to throw an internal exception", e, notNullValue());
assertThat(action, equalTo(((InternalException) e).action));
diff --git a/core/src/test/java/org/elasticsearch/client/transport/FailAndRetryMockTransport.java b/core/src/test/java/org/elasticsearch/client/transport/FailAndRetryMockTransport.java
index c085c3164a0..9d2c176dffb 100644
--- a/core/src/test/java/org/elasticsearch/client/transport/FailAndRetryMockTransport.java
+++ b/core/src/test/java/org/elasticsearch/client/transport/FailAndRetryMockTransport.java
@@ -187,19 +187,13 @@ abstract class FailAndRetryMockTransport imp
}
@Override
- public Transport start() {
- return null;
- }
+ public void start() {}
@Override
- public Transport stop() {
- return null;
- }
+ public void stop() {}
@Override
- public void close() {
-
- }
+ public void close() {}
@Override
public Map profileBoundAddresses() {
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 eee74b66148..282f929ff24 100644
--- a/core/src/test/java/org/elasticsearch/client/transport/TransportClientHeadersTests.java
+++ b/core/src/test/java/org/elasticsearch/client/transport/TransportClientHeadersTests.java
@@ -40,6 +40,7 @@ import org.elasticsearch.env.Environment;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.ConnectTransportException;
+import org.elasticsearch.transport.MockTransportClient;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.TransportException;
import org.elasticsearch.transport.TransportRequest;
@@ -64,30 +65,27 @@ public class TransportClientHeadersTests extends AbstractClientHeadersTestCase {
@Override
protected Client buildClient(Settings headersSettings, GenericAction[] testedActions) {
- TransportClient client = TransportClient.builder()
- .settings(Settings.builder()
+ TransportClient client = new MockTransportClient(Settings.builder()
.put("client.transport.sniff", false)
.put("cluster.name", "cluster1")
.put("node.name", "transport_client_" + this.getTestName())
.put(headersSettings)
- .build())
- .addPlugin(InternalTransportService.TestPlugin.class).build();
+ .build(), InternalTransportService.TestPlugin.class);
client.addTransportAddress(address);
return client;
}
public void testWithSniffing() throws Exception {
- try (TransportClient client = TransportClient.builder()
- .settings(Settings.builder()
+ try (TransportClient client = new MockTransportClient(
+ Settings.builder()
.put("client.transport.sniff", true)
.put("cluster.name", "cluster1")
.put("node.name", "transport_client_" + this.getTestName() + "_1")
.put("client.transport.nodes_sampler_interval", "1s")
.put(HEADER_SETTINGS)
- .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()).build())
- .addPlugin(InternalTransportService.TestPlugin.class)
- .build()) {
+ .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()).build(),
+ InternalTransportService.TestPlugin.class)) {
client.addTransportAddress(address);
InternalTransportService service = (InternalTransportService) client.injector.getInstance(TransportService.class);
diff --git a/core/src/test/java/org/elasticsearch/client/transport/TransportClientIT.java b/core/src/test/java/org/elasticsearch/client/transport/TransportClientIT.java
index 9cdeef2a7ff..761cc8cf0ae 100644
--- a/core/src/test/java/org/elasticsearch/client/transport/TransportClientIT.java
+++ b/core/src/test/java/org/elasticsearch/client/transport/TransportClientIT.java
@@ -22,14 +22,15 @@ package org.elasticsearch.client.transport;
import org.elasticsearch.Version;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.env.Environment;
import org.elasticsearch.node.Node;
-import org.elasticsearch.node.internal.InternalSettingsPreparer;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope;
+import org.elasticsearch.transport.MockTransportClient;
import org.elasticsearch.transport.TransportService;
import java.io.IOException;
@@ -51,37 +52,33 @@ public class TransportClientIT extends ESIntegTestCase {
public void testNodeVersionIsUpdated() throws IOException {
TransportClient client = (TransportClient) internalCluster().client();
- TransportClientNodesService nodeService = client.nodeService();
- Node node = new Node(Settings.builder()
+ try (Node node = new Node(Settings.builder()
.put(internalCluster().getDefaultSettings())
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
.put("node.name", "testNodeVersionIsUpdated")
- .put("http.enabled", false)
+ .put("transport.type", "local")
+ .put(NetworkModule.HTTP_ENABLED.getKey(), false)
.put(Node.NODE_DATA_SETTING.getKey(), false)
.put("cluster.name", "foobar")
- .build());
- node.start();
- try {
+ .build()).start()) {
TransportAddress transportAddress = node.injector().getInstance(TransportService.class).boundAddress().publishAddress();
client.addTransportAddress(transportAddress);
// since we force transport clients there has to be one node started that we connect to.
- assertThat(nodeService.connectedNodes().size(), greaterThanOrEqualTo(1));
+ assertThat(client.connectedNodes().size(), greaterThanOrEqualTo(1));
// connected nodes have updated version
- for (DiscoveryNode discoveryNode : nodeService.connectedNodes()) {
+ for (DiscoveryNode discoveryNode : client.connectedNodes()) {
assertThat(discoveryNode.getVersion(), equalTo(Version.CURRENT));
}
- for (DiscoveryNode discoveryNode : nodeService.listedNodes()) {
+ for (DiscoveryNode discoveryNode : client.listedNodes()) {
assertThat(discoveryNode.getId(), startsWith("#transport#-"));
assertThat(discoveryNode.getVersion(), equalTo(Version.CURRENT.minimumCompatibilityVersion()));
}
- assertThat(nodeService.filteredNodes().size(), equalTo(1));
- for (DiscoveryNode discoveryNode : nodeService.filteredNodes()) {
+ assertThat(client.filteredNodes().size(), equalTo(1));
+ for (DiscoveryNode discoveryNode : client.filteredNodes()) {
assertThat(discoveryNode.getVersion(), equalTo(Version.CURRENT.minimumCompatibilityVersion()));
}
- } finally {
- node.close();
}
}
@@ -94,8 +91,8 @@ public class TransportClientIT extends ESIntegTestCase {
public void testThatTransportClientSettingCannotBeChanged() {
Settings baseSettings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
- .build();
- try (TransportClient client = TransportClient.builder().settings(baseSettings).build()) {
+ .build();
+ try (TransportClient client = new MockTransportClient(baseSettings)) {
Settings settings = client.injector.getInstance(Settings.class);
assertThat(Client.CLIENT_TYPE_SETTING_S.get(settings), is("transport"));
}
diff --git a/core/src/test/java/org/elasticsearch/client/transport/TransportClientNodesServiceTests.java b/core/src/test/java/org/elasticsearch/client/transport/TransportClientNodesServiceTests.java
index 5c07f5e6f25..41891c5831f 100644
--- a/core/src/test/java/org/elasticsearch/client/transport/TransportClientNodesServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/client/transport/TransportClientNodesServiceTests.java
@@ -19,7 +19,6 @@
package org.elasticsearch.client.transport;
-import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.node.liveness.LivenessResponse;
import org.elasticsearch.action.admin.cluster.node.liveness.TransportLivenessAction;
@@ -30,7 +29,7 @@ import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
-import org.elasticsearch.transport.BaseTransportResponseHandler;
+import org.elasticsearch.transport.TransportResponseHandler;
import org.elasticsearch.transport.TransportException;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportRequestOptions;
@@ -123,7 +122,7 @@ public class TransportClientNodesServiceTests extends ESTestCase {
@SuppressWarnings("unchecked")
public void handleResponse(T response) {
LivenessResponse livenessResponse = new LivenessResponse(clusterName,
- new DiscoveryNode(node.getName(), node.getId(), "liveness-hostname" + node.getId(),
+ new DiscoveryNode(node.getName(), node.getId(), node.getEphemeralId(), "liveness-hostname" + node.getId(),
"liveness-hostaddress" + node.getId(),
new LocalTransportAddress("liveness-address-" + node.getId()), node.getAttributes(), node.getRoles(),
node.getVersion()));
@@ -171,7 +170,7 @@ public class TransportClientNodesServiceTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
finalFailures.incrementAndGet();
finalFailure.set(e);
latch.countDown();
@@ -188,7 +187,7 @@ public class TransportClientNodesServiceTests extends ESTestCase {
}
iteration.transportService.sendRequest(node, "action", new TestRequest(),
- TransportRequestOptions.EMPTY, new BaseTransportResponseHandler() {
+ TransportRequestOptions.EMPTY, new TransportResponseHandler() {
@Override
public TestResponse newInstance() {
return new TestResponse();
diff --git a/core/src/test/java/org/elasticsearch/client/transport/TransportClientRetryIT.java b/core/src/test/java/org/elasticsearch/client/transport/TransportClientRetryIT.java
index ed9136851b4..ab34b38f598 100644
--- a/core/src/test/java/org/elasticsearch/client/transport/TransportClientRetryIT.java
+++ b/core/src/test/java/org/elasticsearch/client/transport/TransportClientRetryIT.java
@@ -28,16 +28,15 @@ import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.env.Environment;
-import org.elasticsearch.node.Node;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope;
+import org.elasticsearch.transport.MockTransportClient;
import org.elasticsearch.transport.TransportService;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
-import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
@ClusterScope(scope = Scope.TEST, numClientNodes = 0, supportsDedicatedMasters = false)
@@ -52,13 +51,12 @@ public class TransportClientRetryIT extends ESIntegTestCase {
Settings.Builder builder = Settings.builder().put("client.transport.nodes_sampler_interval", "1s")
.put("node.name", "transport_client_retry_test")
- .put(Node.NODE_MODE_SETTING.getKey(), internalCluster().getNodeMode())
.put(ClusterName.CLUSTER_NAME_SETTING.getKey(), internalCluster().getClusterName())
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir());
- try (TransportClient client = TransportClient.builder().settings(builder.build()).build()) {
+ try (TransportClient client = new MockTransportClient(builder.build())) {
client.addTransportAddresses(addresses);
- assertThat(client.connectedNodes().size(), equalTo(internalCluster().size()));
+ assertEquals(client.connectedNodes().size(), internalCluster().size());
int size = cluster().size();
//kill all nodes one by one, leaving a single master/data node at the end of the loop
diff --git a/core/src/test/java/org/elasticsearch/client/transport/TransportClientTests.java b/core/src/test/java/org/elasticsearch/client/transport/TransportClientTests.java
index ec2065b67e2..2145f66b5e0 100644
--- a/core/src/test/java/org/elasticsearch/client/transport/TransportClientTests.java
+++ b/core/src/test/java/org/elasticsearch/client/transport/TransportClientTests.java
@@ -22,6 +22,7 @@ package org.elasticsearch.client.transport;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESTestCase;
+import org.elasticsearch.transport.MockTransportClient;
import java.util.concurrent.ExecutionException;
@@ -31,11 +32,10 @@ import static org.hamcrest.object.HasToString.hasToString;
public class TransportClientTests extends ESTestCase {
public void testThatUsingAClosedClientThrowsAnException() throws ExecutionException, InterruptedException {
- final TransportClient client = TransportClient.builder().settings(Settings.EMPTY).build();
+ final TransportClient client = new MockTransportClient(Settings.EMPTY);
client.close();
final IllegalStateException e =
expectThrows(IllegalStateException.class, () -> client.admin().cluster().health(new ClusterHealthRequest()).get());
assertThat(e, hasToString(containsString("transport client is closed")));
}
-
}
diff --git a/core/src/test/java/org/elasticsearch/cluster/ClusterChangedEventTests.java b/core/src/test/java/org/elasticsearch/cluster/ClusterChangedEventTests.java
index 72748a59986..555f23813cb 100644
--- a/core/src/test/java/org/elasticsearch/cluster/ClusterChangedEventTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/ClusterChangedEventTests.java
@@ -30,7 +30,7 @@ import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.gateway.GatewayService;
import org.elasticsearch.index.Index;
import org.elasticsearch.test.ESTestCase;
@@ -320,7 +320,8 @@ public class ClusterChangedEventTests extends ESTestCase {
// Create a new DiscoveryNode
private static DiscoveryNode newNode(final String nodeId, Set roles) {
- return new DiscoveryNode(nodeId, nodeId, DummyTransportAddress.INSTANCE, Collections.emptyMap(), roles, Version.CURRENT);
+ return new DiscoveryNode(nodeId, nodeId, nodeId, "host", "host_address", new LocalTransportAddress("_test_" + nodeId),
+ Collections.emptyMap(), roles, Version.CURRENT);
}
// Create the metadata for a cluster state.
diff --git a/core/src/test/java/org/elasticsearch/cluster/ClusterHealthIT.java b/core/src/test/java/org/elasticsearch/cluster/ClusterHealthIT.java
index c4a3ecba839..d6cf029c00d 100644
--- a/core/src/test/java/org/elasticsearch/cluster/ClusterHealthIT.java
+++ b/core/src/test/java/org/elasticsearch/cluster/ClusterHealthIT.java
@@ -23,10 +23,13 @@ import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.common.Priority;
import org.elasticsearch.test.ESIntegTestCase;
+import java.util.concurrent.atomic.AtomicBoolean;
import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.not;
public class ClusterHealthIT extends ESIntegTestCase {
+
public void testSimpleLocalHealth() {
createIndex("test");
ensureGreen(); // master should thing it's green now.
@@ -68,4 +71,24 @@ public class ClusterHealthIT extends ESIntegTestCase {
assertThat(healthResponse.getIndices().get("test1").getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(healthResponse.getIndices().size(), equalTo(1));
}
-}
\ No newline at end of file
+
+ public void testHealthOnIndexCreation() throws Exception {
+ final AtomicBoolean finished = new AtomicBoolean(false);
+ Thread clusterHealthThread = new Thread() {
+ @Override
+ public void run() {
+ while (finished.get() == false) {
+ ClusterHealthResponse health = client().admin().cluster().prepareHealth().get();
+ assertThat(health.getStatus(), not(equalTo(ClusterHealthStatus.RED)));
+ }
+ }
+ };
+ clusterHealthThread.start();
+ for (int i = 0; i < 10; i++) {
+ createIndex("test" + i);
+ }
+ finished.set(true);
+ clusterHealthThread.join();
+ }
+
+}
diff --git a/core/src/test/java/org/elasticsearch/cluster/ClusterInfoTests.java b/core/src/test/java/org/elasticsearch/cluster/ClusterInfoTests.java
new file mode 100644
index 00000000000..99afee8b2c2
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/cluster/ClusterInfoTests.java
@@ -0,0 +1,88 @@
+/*
+ * 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.cluster;
+
+import org.elasticsearch.Version;
+import org.elasticsearch.cluster.routing.RestoreSource;
+import org.elasticsearch.cluster.routing.ShardRouting;
+import org.elasticsearch.cluster.routing.UnassignedInfo;
+import org.elasticsearch.common.collect.ImmutableOpenMap;
+import org.elasticsearch.common.io.stream.BytesStreamOutput;
+import org.elasticsearch.index.shard.ShardId;
+import org.elasticsearch.snapshots.Snapshot;
+import org.elasticsearch.snapshots.SnapshotId;
+import org.elasticsearch.test.ESTestCase;
+
+public class ClusterInfoTests extends ESTestCase {
+
+ public void testSerialization() throws Exception {
+ ClusterInfo clusterInfo = new ClusterInfo(
+ randomDiskUsage(), randomDiskUsage(), randomShardSizes(), randomRoutingToDataPath()
+ );
+ BytesStreamOutput output = new BytesStreamOutput();
+ clusterInfo.writeTo(output);
+
+ ClusterInfo result = new ClusterInfo(output.bytes().streamInput());
+ assertEquals(clusterInfo.getNodeLeastAvailableDiskUsages(), result.getNodeLeastAvailableDiskUsages());
+ assertEquals(clusterInfo.getNodeMostAvailableDiskUsages(), result.getNodeMostAvailableDiskUsages());
+ assertEquals(clusterInfo.shardSizes, result.shardSizes);
+ assertEquals(clusterInfo.routingToDataPath, result.routingToDataPath);
+ }
+
+ private static ImmutableOpenMap randomDiskUsage() {
+ int numEntries = randomIntBetween(0, 128);
+ ImmutableOpenMap.Builder builder = ImmutableOpenMap.builder(numEntries);
+ for (int i = 0; i < numEntries; i++) {
+ String key = randomAsciiOfLength(32);
+ DiskUsage diskUsage = new DiskUsage(
+ randomAsciiOfLength(4), randomAsciiOfLength(4), randomAsciiOfLength(4),
+ randomIntBetween(0, Integer.MAX_VALUE), randomIntBetween(0, Integer.MAX_VALUE)
+ );
+ builder.put(key, diskUsage);
+ }
+ return builder.build();
+ }
+
+ private static ImmutableOpenMap randomShardSizes() {
+ int numEntries = randomIntBetween(0, 128);
+ ImmutableOpenMap.Builder builder = ImmutableOpenMap.builder(numEntries);
+ for (int i = 0; i < numEntries; i++) {
+ String key = randomAsciiOfLength(32);
+ long shardSize = randomIntBetween(0, Integer.MAX_VALUE);
+ builder.put(key, shardSize);
+ }
+ return builder.build();
+ }
+
+ private static ImmutableOpenMap randomRoutingToDataPath() {
+ int numEntries = randomIntBetween(0, 128);
+ ImmutableOpenMap.Builder builder = ImmutableOpenMap.builder(numEntries);
+ for (int i = 0; i < numEntries; i++) {
+ RestoreSource restoreSource = new RestoreSource(new Snapshot(randomAsciiOfLength(4),
+ new SnapshotId(randomAsciiOfLength(4), randomAsciiOfLength(4))), Version.CURRENT, randomAsciiOfLength(4));
+ UnassignedInfo.Reason reason = randomFrom(UnassignedInfo.Reason.values());
+ UnassignedInfo unassignedInfo = new UnassignedInfo(reason, randomAsciiOfLength(4));
+ ShardId shardId = new ShardId(randomAsciiOfLength(32), randomAsciiOfLength(32), randomIntBetween(0, Integer.MAX_VALUE));
+ ShardRouting shardRouting = ShardRouting.newUnassigned(shardId, restoreSource, randomBoolean(), unassignedInfo);
+ builder.put(shardRouting, randomAsciiOfLength(32));
+ }
+ return builder.build();
+ }
+
+}
diff --git a/core/src/test/java/org/elasticsearch/cluster/ClusterStateDiffIT.java b/core/src/test/java/org/elasticsearch/cluster/ClusterStateDiffIT.java
index b82b5e0ba60..68a0f73eb34 100644
--- a/core/src/test/java/org/elasticsearch/cluster/ClusterStateDiffIT.java
+++ b/core/src/test/java/org/elasticsearch/cluster/ClusterStateDiffIT.java
@@ -30,6 +30,7 @@ import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.IndexTemplateMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.metadata.RepositoriesMetaData;
+import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.snapshots.SnapshotId;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
@@ -52,6 +53,7 @@ import org.elasticsearch.index.Index;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.snapshots.Snapshot;
+import org.elasticsearch.snapshots.SnapshotId;
import org.elasticsearch.test.ESIntegTestCase;
import java.util.Collections;
@@ -121,7 +123,7 @@ public class ClusterStateDiffIT extends ESIntegTestCase {
Diff diffBeforeSerialization = clusterState.diff(previousClusterState);
BytesStreamOutput os = new BytesStreamOutput();
diffBeforeSerialization.writeTo(os);
- byte[] diffBytes = os.bytes().toBytes();
+ byte[] diffBytes = BytesReference.toBytes(os.bytes());
Diff diff;
try (StreamInput input = StreamInput.wrap(diffBytes)) {
diff = previousClusterStateFromDiffs.readDiffFrom(input);
@@ -190,9 +192,8 @@ public class ClusterStateDiffIT extends ESIntegTestCase {
List nodeIds = randomSubsetOf(randomInt(clusterState.nodes().getNodes().size() - 1), clusterState.nodes().getNodes().keys().toArray(String.class));
for (String nodeId : nodeIds) {
if (nodeId.startsWith("node-")) {
+ nodes.remove(nodeId);
if (randomBoolean()) {
- nodes.remove(nodeId);
- } else {
nodes.put(new DiscoveryNode(nodeId, new LocalTransportAddress(randomAsciiOfLength(10)), emptyMap(),
emptySet(), randomVersion(random())));
}
diff --git a/core/src/test/java/org/elasticsearch/cluster/ClusterStateTests.java b/core/src/test/java/org/elasticsearch/cluster/ClusterStateTests.java
index 5e272a27459..6b99e525cb2 100644
--- a/core/src/test/java/org/elasticsearch/cluster/ClusterStateTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/ClusterStateTests.java
@@ -22,7 +22,7 @@ import org.elasticsearch.Version;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.test.ESTestCase;
import static java.util.Collections.emptyMap;
@@ -32,8 +32,9 @@ import static org.hamcrest.Matchers.equalTo;
public class ClusterStateTests extends ESTestCase {
public void testSupersedes() {
- final DiscoveryNode node1 = new DiscoveryNode("node1", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
- final DiscoveryNode node2 = new DiscoveryNode("node2", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ final Version version = Version.CURRENT;
+ final DiscoveryNode node1 = new DiscoveryNode("node1", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), version);
+ final DiscoveryNode node2 = new DiscoveryNode("node2", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), version);
final DiscoveryNodes nodes = DiscoveryNodes.builder().put(node1).put(node2).build();
ClusterName name = ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY);
ClusterState noMaster1 = ClusterState.builder(name).version(randomInt(5)).nodes(nodes).build();
diff --git a/core/src/test/java/org/elasticsearch/cluster/DiskUsageTests.java b/core/src/test/java/org/elasticsearch/cluster/DiskUsageTests.java
index 9210e2a56bd..2073235af98 100644
--- a/core/src/test/java/org/elasticsearch/cluster/DiskUsageTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/DiskUsageTests.java
@@ -23,8 +23,6 @@ import org.elasticsearch.Version;
import org.elasticsearch.action.admin.cluster.node.stats.NodeStats;
import org.elasticsearch.action.admin.indices.stats.CommonStats;
import org.elasticsearch.action.admin.indices.stats.ShardStats;
-import org.elasticsearch.cluster.ClusterName;
-import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
@@ -33,7 +31,7 @@ import org.elasticsearch.cluster.routing.ShardRoutingHelper;
import org.elasticsearch.cluster.routing.UnassignedInfo;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.ShardPath;
@@ -200,11 +198,11 @@ public class DiskUsageTests extends ESTestCase {
new FsInfo.Path("/most", "/dev/sda", 100, 90, 80),
};
List nodeStats = Arrays.asList(
- new NodeStats(new DiscoveryNode("node_1", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT), 0,
+ new NodeStats(new DiscoveryNode("node_1", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT), 0,
null,null,null,null,null,new FsInfo(0, null, node1FSInfo), null,null,null,null,null, null),
- new NodeStats(new DiscoveryNode("node_2", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT), 0,
+ new NodeStats(new DiscoveryNode("node_2", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT), 0,
null,null,null,null,null, new FsInfo(0, null, node2FSInfo), null,null,null,null,null, null),
- new NodeStats(new DiscoveryNode("node_3", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT), 0,
+ new NodeStats(new DiscoveryNode("node_3", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT), 0,
null,null,null,null,null, new FsInfo(0, null, node3FSInfo), null,null,null,null,null, null)
);
InternalClusterInfoService.fillDiskUsagePerNode(logger, nodeStats, newLeastAvaiableUsages, newMostAvaiableUsages);
@@ -241,11 +239,11 @@ public class DiskUsageTests extends ESTestCase {
new FsInfo.Path("/least", "/dev/sda", 10, -8, 0),
};
List nodeStats = Arrays.asList(
- new NodeStats(new DiscoveryNode("node_1", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT), 0,
+ new NodeStats(new DiscoveryNode("node_1", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT), 0,
null,null,null,null,null,new FsInfo(0, null, node1FSInfo), null,null,null,null,null, null),
- new NodeStats(new DiscoveryNode("node_2", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT), 0,
+ new NodeStats(new DiscoveryNode("node_2", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT), 0,
null,null,null,null,null, new FsInfo(0, null, node2FSInfo), null,null,null,null,null, null),
- new NodeStats(new DiscoveryNode("node_3", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT), 0,
+ new NodeStats(new DiscoveryNode("node_3", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT), 0,
null,null,null,null,null, new FsInfo(0, null, node3FSInfo), null,null,null,null,null, null)
);
InternalClusterInfoService.fillDiskUsagePerNode(logger, nodeStats, newLeastAvailableUsages, newMostAvailableUsages);
diff --git a/core/src/test/java/org/elasticsearch/cluster/MinimumMasterNodesIT.java b/core/src/test/java/org/elasticsearch/cluster/MinimumMasterNodesIT.java
index 61bb898acc2..aad2aa212a1 100644
--- a/core/src/test/java/org/elasticsearch/cluster/MinimumMasterNodesIT.java
+++ b/core/src/test/java/org/elasticsearch/cluster/MinimumMasterNodesIT.java
@@ -395,8 +395,8 @@ public class MinimumMasterNodesIT extends ESIntegTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
- failure.set(t);
+ public void onFailure(String source, Exception e) {
+ failure.set(e);
latch.countDown();
}
});
diff --git a/core/src/test/java/org/elasticsearch/cluster/NodeConnectionsServiceTests.java b/core/src/test/java/org/elasticsearch/cluster/NodeConnectionsServiceTests.java
index 5eb5a34c44f..b0bc3ee2e4e 100644
--- a/core/src/test/java/org/elasticsearch/cluster/NodeConnectionsServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/NodeConnectionsServiceTests.java
@@ -26,7 +26,7 @@ import org.elasticsearch.common.component.Lifecycle;
import org.elasticsearch.common.component.LifecycleListener;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.BoundTransportAddress;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
import org.elasticsearch.test.ESTestCase;
@@ -64,7 +64,7 @@ public class NodeConnectionsServiceTests extends ESTestCase {
List nodes = new ArrayList<>();
for (int i = randomIntBetween(20, 50); i > 0; i--) {
Set roles = new HashSet<>(randomSubsetOf(Arrays.asList(DiscoveryNode.Role.values())));
- nodes.add(new DiscoveryNode("node_" + i, "" + i, DummyTransportAddress.INSTANCE, Collections.emptyMap(),
+ nodes.add(new DiscoveryNode("node_" + i, "" + i, LocalTransportAddress.buildUnique(), Collections.emptyMap(),
roles, Version.CURRENT));
}
return nodes;
@@ -253,18 +253,12 @@ public class NodeConnectionsServiceTests extends ESTestCase {
}
@Override
- public Transport start() {
- return null;
- }
+ public void start() {}
@Override
- public Transport stop() {
- return null;
- }
+ public void stop() {}
@Override
- public void close() {
-
- }
+ public void close() {}
}
}
diff --git a/core/src/test/java/org/elasticsearch/cluster/SimpleDataNodesIT.java b/core/src/test/java/org/elasticsearch/cluster/SimpleDataNodesIT.java
index 43aa088a3b9..f411e00468e 100644
--- a/core/src/test/java/org/elasticsearch/cluster/SimpleDataNodesIT.java
+++ b/core/src/test/java/org/elasticsearch/cluster/SimpleDataNodesIT.java
@@ -21,6 +21,7 @@ package org.elasticsearch.cluster;
import org.elasticsearch.action.UnavailableShardsException;
import org.elasticsearch.action.index.IndexResponse;
+import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.settings.Settings;
@@ -40,7 +41,7 @@ import static org.hamcrest.Matchers.equalTo;
public class SimpleDataNodesIT extends ESIntegTestCase {
public void testDataNodes() throws Exception {
internalCluster().startNode(Settings.builder().put(Node.NODE_DATA_SETTING.getKey(), false).build());
- client().admin().indices().create(createIndexRequest("test")).actionGet();
+ client().admin().indices().create(createIndexRequest("test").waitForActiveShards(ActiveShardCount.NONE)).actionGet();
try {
client().index(Requests.indexRequest("test").type("type1").id("1").source(source("1", "test")).timeout(timeValueSeconds(1))).actionGet();
fail("no allocation should happen");
diff --git a/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardFailedClusterStateTaskExecutorTests.java b/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardFailedClusterStateTaskExecutorTests.java
index 1faac874114..d12b6b563b3 100644
--- a/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardFailedClusterStateTaskExecutorTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardFailedClusterStateTaskExecutorTests.java
@@ -27,7 +27,6 @@ import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateTaskExecutor;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
-import org.elasticsearch.cluster.node.DiscoveryNodeService;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.GroupShardsIterator;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
@@ -41,6 +40,7 @@ import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.FailedRerouteAllocation;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.routing.allocation.decider.ClusterRebalanceAllocationDecider;
+import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
@@ -305,7 +305,8 @@ public class ShardFailedClusterStateTaskExecutorTests extends ESAllocationTestCa
return randomSubsetOf(1, shards.toArray(new ShardRouting[0])).get(0);
} else {
return
- TestShardRouting.newShardRouting(shardRouting.shardId(), DiscoveryNodeService.generateNodeId(Settings.EMPTY), randomBoolean(), randomFrom(ShardRoutingState.values()));
+ TestShardRouting.newShardRouting(shardRouting.shardId(), UUIDs.randomBase64UUID(random()), randomBoolean(),
+ randomFrom(ShardRoutingState.values()));
}
}
diff --git a/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java b/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java
index 7f0ac1a6e45..d387d6f7d43 100644
--- a/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java
@@ -148,7 +148,7 @@ public class ShardStateActionTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable t) {
+ public void onFailure(Exception e) {
success.set(false);
latch.countDown();
assert false;
@@ -196,7 +196,7 @@ public class ShardStateActionTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
success.set(false);
latch.countDown();
assert false;
@@ -245,9 +245,9 @@ public class ShardStateActionTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable t) {
+ public void onFailure(Exception e) {
success.set(false);
- throwable.set(t);
+ throwable.set(e);
latch.countDown();
assert false;
}
@@ -281,7 +281,7 @@ public class ShardStateActionTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable t) {
+ public void onFailure(Exception e) {
failure.set(true);
}
});
@@ -313,7 +313,7 @@ public class ShardStateActionTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable t) {
+ public void onFailure(Exception e) {
success.set(false);
latch.countDown();
assert false;
@@ -348,8 +348,8 @@ public class ShardStateActionTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable t) {
- failure.set(t);
+ public void onFailure(Exception e) {
+ failure.set(e);
latch.countDown();
}
});
@@ -401,7 +401,7 @@ public class ShardStateActionTests extends ESTestCase {
}
}
- private Throwable getSimulatedFailure() {
+ private Exception getSimulatedFailure() {
return new CorruptIndexException("simulated", (String) null);
}
}
diff --git a/core/src/test/java/org/elasticsearch/cluster/allocation/ClusterRerouteIT.java b/core/src/test/java/org/elasticsearch/cluster/allocation/ClusterRerouteIT.java
index c86535e40c5..70af5808241 100644
--- a/core/src/test/java/org/elasticsearch/cluster/allocation/ClusterRerouteIT.java
+++ b/core/src/test/java/org/elasticsearch/cluster/allocation/ClusterRerouteIT.java
@@ -22,6 +22,7 @@ package org.elasticsearch.cluster.allocation;
import org.apache.lucene.util.IOUtils;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteResponse;
+import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.action.support.WriteRequest.RefreshPolicy;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
@@ -91,7 +92,7 @@ public class ClusterRerouteIT extends ESIntegTestCase {
final String node_2 = nodesIds.get(1);
logger.info("--> create an index with 1 shard, 1 replica, nothing should allocate");
- client().admin().indices().prepareCreate("test")
+ client().admin().indices().prepareCreate("test").setWaitForActiveShards(ActiveShardCount.NONE)
.setSettings(Settings.builder().put("index.number_of_shards", 1))
.execute().actionGet();
@@ -203,7 +204,7 @@ public class ClusterRerouteIT extends ESIntegTestCase {
assertThat(healthResponse.isTimedOut(), equalTo(false));
logger.info("--> create an index with 1 shard, 1 replica, nothing should allocate");
- client().admin().indices().prepareCreate("test")
+ client().admin().indices().prepareCreate("test").setWaitForActiveShards(ActiveShardCount.NONE)
.setSettings(Settings.builder().put("index.number_of_shards", 1))
.execute().actionGet();
@@ -253,14 +254,13 @@ public class ClusterRerouteIT extends ESIntegTestCase {
assertThat(state.getRoutingNodes().unassigned().size(), equalTo(1));
assertThat(state.getRoutingNodes().node(state.nodes().resolveNode(node_1).getId()).iterator().next().state(), equalTo(ShardRoutingState.INITIALIZING));
- healthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet();
- assertThat(healthResponse.isTimedOut(), equalTo(false));
-
logger.info("--> get the state, verify shard 1 primary allocated");
- state = client().admin().cluster().prepareState().execute().actionGet().getState();
- assertThat(state.getRoutingNodes().unassigned().size(), equalTo(1));
- assertThat(state.getRoutingNodes().node(state.nodes().resolveNode(node_1).getId()).iterator().next().state(), equalTo(ShardRoutingState.STARTED));
-
+ final String nodeToCheck = node_1;
+ assertBusy(() -> {
+ ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
+ String nodeId = clusterState.nodes().resolveNode(nodeToCheck).getId();
+ assertThat(clusterState.getRoutingNodes().node(nodeId).iterator().next().state(), equalTo(ShardRoutingState.STARTED));
+ });
}
public void testRerouteExplain() {
diff --git a/core/src/test/java/org/elasticsearch/cluster/block/ClusterBlockTests.java b/core/src/test/java/org/elasticsearch/cluster/block/ClusterBlockTests.java
index 7f2d0828128..a7fe1b918c0 100644
--- a/core/src/test/java/org/elasticsearch/cluster/block/ClusterBlockTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/block/ClusterBlockTests.java
@@ -55,7 +55,7 @@ public class ClusterBlockTests extends ESTestCase {
out.setVersion(version);
clusterBlock.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
in.setVersion(version);
ClusterBlock result = ClusterBlock.readClusterBlock(in);
diff --git a/core/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java b/core/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java
index fd1e3e62466..0b0ea6b3f91 100644
--- a/core/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java
@@ -18,6 +18,8 @@
*/
package org.elasticsearch.cluster.health;
+import com.carrotsearch.hppc.cursors.IntObjectCursor;
+import com.carrotsearch.hppc.cursors.ObjectCursor;
import org.elasticsearch.Version;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
@@ -32,12 +34,18 @@ import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
+import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.RoutingTableGenerator;
+import org.elasticsearch.cluster.routing.ShardRouting;
+import org.elasticsearch.cluster.routing.UnassignedInfo;
import org.elasticsearch.cluster.service.ClusterService;
+import org.elasticsearch.common.UUIDs;
+import org.elasticsearch.common.collect.ImmutableOpenIntMap;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.settings.Settings;
+import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.gateway.NoopGatewayAllocator;
import org.elasticsearch.test.transport.CapturingTransport;
@@ -50,7 +58,10 @@ import org.junit.Before;
import org.junit.BeforeClass;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@@ -65,14 +76,13 @@ import static org.hamcrest.Matchers.lessThanOrEqualTo;
public class ClusterStateHealthTests extends ESTestCase {
private final IndexNameExpressionResolver indexNameExpressionResolver = new IndexNameExpressionResolver(Settings.EMPTY);
-
private static ThreadPool threadPool;
private ClusterService clusterService;
private TransportService transportService;
@BeforeClass
- public static void beforeClass() {
+ public static void setupThreadPool() {
threadPool = new TestThreadPool("ClusterStateHealthTests");
}
@@ -94,7 +104,7 @@ public class ClusterStateHealthTests extends ESTestCase {
}
@AfterClass
- public static void afterClass() {
+ public static void terminateThreadPool() {
ThreadPool.terminate(threadPool, 30, TimeUnit.SECONDS);
threadPool = null;
}
@@ -118,8 +128,8 @@ public class ClusterStateHealthTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
- logger.warn("unexpected failure", t);
+ public void onFailure(String source, Exception e) {
+ logger.warn("unexpected failure", e);
}
});
@@ -129,7 +139,6 @@ public class ClusterStateHealthTests extends ESTestCase {
TransportClusterHealthAction action = new TransportClusterHealthAction(Settings.EMPTY, transportService,
clusterService, threadPool, new ActionFilters(new HashSet<>()), indexNameExpressionResolver, NoopGatewayAllocator.INSTANCE);
PlainActionFuture listener = new PlainActionFuture<>();
-
action.execute(new ClusterHealthRequest(), listener);
assertFalse(listener.isDone());
@@ -138,7 +147,6 @@ public class ClusterStateHealthTests extends ESTestCase {
listener.get();
}
-
public void testClusterHealth() throws IOException {
RoutingTableGenerator routingTableGenerator = new RoutingTableGenerator();
RoutingTableGenerator.ShardCounter counter = new RoutingTableGenerator.ShardCounter();
@@ -157,24 +165,376 @@ public class ClusterStateHealthTests extends ESTestCase {
metaData.put(indexMetaData, true);
routingTable.add(indexRoutingTable);
}
- ClusterState clusterState = ClusterState.builder(ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY)).metaData(metaData).routingTable(routingTable.build()).build();
- String[] concreteIndices = indexNameExpressionResolver.concreteIndexNames(clusterState, IndicesOptions.strictExpand(), (String[]) null);
+ ClusterState clusterState = ClusterState.builder(ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY))
+ .metaData(metaData)
+ .routingTable(routingTable.build())
+ .build();
+ String[] concreteIndices = indexNameExpressionResolver.concreteIndexNames(
+ clusterState, IndicesOptions.strictExpand(), (String[]) null
+ );
ClusterStateHealth clusterStateHealth = new ClusterStateHealth(clusterState, concreteIndices);
logger.info("cluster status: {}, expected {}", clusterStateHealth.getStatus(), counter.status());
clusterStateHealth = maybeSerialize(clusterStateHealth);
assertClusterHealth(clusterStateHealth, counter);
}
+ public void testClusterHealthOnIndexCreation() {
+ final String indexName = "test-idx";
+ final String[] indices = new String[] { indexName };
+ final List clusterStates = simulateIndexCreationStates(indexName, false);
+ for (int i = 0; i < clusterStates.size(); i++) {
+ // make sure cluster health is always YELLOW, up until the last state where it should be GREEN
+ final ClusterState clusterState = clusterStates.get(i);
+ final ClusterStateHealth health = new ClusterStateHealth(clusterState, indices);
+ if (i < clusterStates.size() - 1) {
+ assertThat(health.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
+ } else {
+ assertThat(health.getStatus(), equalTo(ClusterHealthStatus.GREEN));
+ }
+ }
+ }
+
+ public void testClusterHealthOnIndexCreationWithFailedAllocations() {
+ final String indexName = "test-idx";
+ final String[] indices = new String[] { indexName };
+ final List clusterStates = simulateIndexCreationStates(indexName, true);
+ for (int i = 0; i < clusterStates.size(); i++) {
+ // make sure cluster health is YELLOW up until the final cluster state, which contains primary shard
+ // failed allocations that should make the cluster health RED
+ final ClusterState clusterState = clusterStates.get(i);
+ final ClusterStateHealth health = new ClusterStateHealth(clusterState, indices);
+ if (i < clusterStates.size() - 1) {
+ assertThat(health.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
+ } else {
+ assertThat(health.getStatus(), equalTo(ClusterHealthStatus.RED));
+ }
+ }
+ }
+
+ public void testClusterHealthOnClusterRecovery() {
+ final String indexName = "test-idx";
+ final String[] indices = new String[] { indexName };
+ final List clusterStates = simulateClusterRecoveryStates(indexName, false, false);
+ for (int i = 0; i < clusterStates.size(); i++) {
+ // make sure cluster health is YELLOW up until the final cluster state, when it turns GREEN
+ final ClusterState clusterState = clusterStates.get(i);
+ final ClusterStateHealth health = new ClusterStateHealth(clusterState, indices);
+ if (i < clusterStates.size() - 1) {
+ assertThat(health.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
+ } else {
+ assertThat(health.getStatus(), equalTo(ClusterHealthStatus.GREEN));
+ }
+ }
+ }
+
+ public void testClusterHealthOnClusterRecoveryWithFailures() {
+ final String indexName = "test-idx";
+ final String[] indices = new String[] { indexName };
+ final List clusterStates = simulateClusterRecoveryStates(indexName, false, true);
+ for (int i = 0; i < clusterStates.size(); i++) {
+ // make sure cluster health is YELLOW up until the final cluster state, which contains primary shard
+ // failed allocations that should make the cluster health RED
+ final ClusterState clusterState = clusterStates.get(i);
+ final ClusterStateHealth health = new ClusterStateHealth(clusterState, indices);
+ if (i < clusterStates.size() - 1) {
+ assertThat(health.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
+ } else {
+ assertThat(health.getStatus(), equalTo(ClusterHealthStatus.RED));
+ }
+ }
+ }
+
+ public void testClusterHealthOnClusterRecoveryWithPreviousAllocationIds() {
+ final String indexName = "test-idx";
+ final String[] indices = new String[] { indexName };
+ final List clusterStates = simulateClusterRecoveryStates(indexName, true, false);
+ for (int i = 0; i < clusterStates.size(); i++) {
+ // because there were previous allocation ids, we should be RED until the primaries are started,
+ // then move to YELLOW, and the last state should be GREEN when all shards have been started
+ final ClusterState clusterState = clusterStates.get(i);
+ final ClusterStateHealth health = new ClusterStateHealth(clusterState, indices);
+ if (i < clusterStates.size() - 1) {
+ // if the inactive primaries are due solely to recovery (not failed allocation or previously being allocated),
+ // then cluster health is YELLOW, otherwise RED
+ if (primaryInactiveDueToRecovery(indexName, clusterState)) {
+ assertThat(health.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
+ } else {
+ assertThat(health.getStatus(), equalTo(ClusterHealthStatus.RED));
+ }
+ } else {
+ assertThat(health.getStatus(), equalTo(ClusterHealthStatus.GREEN));
+ }
+ }
+ }
+
+ public void testClusterHealthOnClusterRecoveryWithPreviousAllocationIdsAndAllocationFailures() {
+ final String indexName = "test-idx";
+ final String[] indices = new String[] { indexName };
+ for (final ClusterState clusterState : simulateClusterRecoveryStates(indexName, true, true)) {
+ final ClusterStateHealth health = new ClusterStateHealth(clusterState, indices);
+ // if the inactive primaries are due solely to recovery (not failed allocation or previously being allocated)
+ // then cluster health is YELLOW, otherwise RED
+ if (primaryInactiveDueToRecovery(indexName, clusterState)) {
+ assertThat(health.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
+ } else {
+ assertThat(health.getStatus(), equalTo(ClusterHealthStatus.RED));
+ }
+ }
+ }
+
ClusterStateHealth maybeSerialize(ClusterStateHealth clusterStateHealth) throws IOException {
if (randomBoolean()) {
BytesStreamOutput out = new BytesStreamOutput();
clusterStateHealth.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
clusterStateHealth = new ClusterStateHealth(in);
}
return clusterStateHealth;
}
+ private List simulateIndexCreationStates(final String indexName, final boolean withPrimaryAllocationFailures) {
+ final int numberOfShards = randomIntBetween(1, 5);
+ final int numberOfReplicas = randomIntBetween(1, numberOfShards);
+ // initial index creation and new routing table info
+ final IndexMetaData indexMetaData = IndexMetaData.builder(indexName)
+ .settings(settings(Version.CURRENT)
+ .put(IndexMetaData.SETTING_INDEX_UUID, UUIDs.randomBase64UUID()))
+ .numberOfShards(numberOfShards)
+ .numberOfReplicas(numberOfReplicas)
+ .build();
+ final MetaData metaData = MetaData.builder().put(indexMetaData, true).build();
+ final RoutingTable routingTable = RoutingTable.builder().addAsNew(indexMetaData).build();
+
+ ClusterState clusterState = ClusterState.builder(new ClusterName("test_cluster"))
+ .metaData(metaData)
+ .routingTable(routingTable)
+ .build();
+ return generateClusterStates(clusterState, indexName, numberOfReplicas, withPrimaryAllocationFailures);
+ }
+
+ private List simulateClusterRecoveryStates(final String indexName,
+ final boolean withPreviousAllocationIds,
+ final boolean withPrimaryAllocationFailures) {
+ final int numberOfShards = randomIntBetween(1, 5);
+ final int numberOfReplicas = randomIntBetween(1, numberOfShards);
+ // initial index creation and new routing table info
+ IndexMetaData indexMetaData = IndexMetaData.builder(indexName)
+ .settings(settings(Version.CURRENT)
+ .put(IndexMetaData.SETTING_INDEX_UUID, UUIDs.randomBase64UUID()))
+ .numberOfShards(numberOfShards)
+ .numberOfReplicas(numberOfReplicas)
+ .state(IndexMetaData.State.OPEN)
+ .build();
+ if (withPreviousAllocationIds) {
+ final IndexMetaData.Builder idxMetaWithAllocationIds = IndexMetaData.builder(indexMetaData);
+ boolean atLeastOne = false;
+ for (int i = 0; i < numberOfShards; i++) {
+ if (atLeastOne == false || randomBoolean()) {
+ idxMetaWithAllocationIds.putActiveAllocationIds(i, Sets.newHashSet(UUIDs.randomBase64UUID()));
+ atLeastOne = true;
+ }
+ }
+ indexMetaData = idxMetaWithAllocationIds.build();
+ }
+ final MetaData metaData = MetaData.builder().put(indexMetaData, true).build();
+ final RoutingTable routingTable = RoutingTable.builder().addAsRecovery(indexMetaData).build();
+
+ ClusterState clusterState = ClusterState.builder(new ClusterName("test_cluster"))
+ .metaData(metaData)
+ .routingTable(routingTable)
+ .build();
+ return generateClusterStates(clusterState, indexName, numberOfReplicas, withPrimaryAllocationFailures);
+ }
+
+ private List generateClusterStates(final ClusterState originalClusterState,
+ final String indexName,
+ final int numberOfReplicas,
+ final boolean withPrimaryAllocationFailures) {
+ // generate random node ids
+ final List nodeIds = new ArrayList<>();
+ final int numNodes = randomIntBetween(numberOfReplicas + 1, 10);
+ for (int i = 0; i < numNodes; i++) {
+ nodeIds.add(randomAsciiOfLength(8));
+ }
+
+ final List clusterStates = new ArrayList<>();
+ clusterStates.add(originalClusterState);
+ ClusterState clusterState = originalClusterState;
+
+ // initialize primaries
+ RoutingTable routingTable = originalClusterState.routingTable();
+ IndexRoutingTable indexRoutingTable = routingTable.index(indexName);
+ IndexRoutingTable.Builder newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
+ for (final ObjectCursor shardEntry : indexRoutingTable.getShards().values()) {
+ final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
+ for (final ShardRouting shardRouting : shardRoutingTable.getShards()) {
+ if (shardRouting.primary()) {
+ newIndexRoutingTable.addShard(
+ shardRouting.initialize(nodeIds.get(randomIntBetween(0, numNodes - 1)), null, shardRouting.getExpectedShardSize())
+ );
+ } else {
+ newIndexRoutingTable.addShard(shardRouting);
+ }
+ }
+ }
+ routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
+ clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
+ clusterStates.add(clusterState);
+
+ // some primaries started
+ indexRoutingTable = routingTable.index(indexName);
+ newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
+ ImmutableOpenIntMap.Builder> allocationIds = ImmutableOpenIntMap.>builder();
+ for (final ObjectCursor shardEntry : indexRoutingTable.getShards().values()) {
+ final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
+ for (final ShardRouting shardRouting : shardRoutingTable.getShards()) {
+ if (shardRouting.primary() && randomBoolean()) {
+ final ShardRouting newShardRouting = shardRouting.moveToStarted();
+ allocationIds.fPut(newShardRouting.getId(), Sets.newHashSet(newShardRouting.allocationId().getId()));
+ newIndexRoutingTable.addShard(newShardRouting);
+ } else {
+ newIndexRoutingTable.addShard(shardRouting);
+ }
+ }
+ }
+ routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
+ IndexMetaData.Builder idxMetaBuilder = IndexMetaData.builder(clusterState.metaData().index(indexName));
+ for (final IntObjectCursor> entry : allocationIds.build()) {
+ idxMetaBuilder.putActiveAllocationIds(entry.key, entry.value);
+ }
+ MetaData.Builder metaDataBuilder = MetaData.builder(clusterState.metaData()).put(idxMetaBuilder);
+ clusterState = ClusterState.builder(clusterState).routingTable(routingTable).metaData(metaDataBuilder).build();
+ clusterStates.add(clusterState);
+
+ if (withPrimaryAllocationFailures) {
+ boolean alreadyFailedPrimary = false;
+ // some primaries failed to allocate
+ indexRoutingTable = routingTable.index(indexName);
+ newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
+ for (final ObjectCursor shardEntry : indexRoutingTable.getShards().values()) {
+ final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
+ for (final ShardRouting shardRouting : shardRoutingTable.getShards()) {
+ if (shardRouting.primary() && (shardRouting.started() == false || alreadyFailedPrimary == false)) {
+ newIndexRoutingTable.addShard(shardRouting.moveToUnassigned(
+ new UnassignedInfo(UnassignedInfo.Reason.ALLOCATION_FAILED, "unlucky shard")));
+ alreadyFailedPrimary = true;
+ } else {
+ newIndexRoutingTable.addShard(shardRouting);
+ }
+ }
+ }
+ routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
+ clusterStates.add(ClusterState.builder(clusterState).routingTable(routingTable).build());
+ return clusterStates;
+ }
+
+ // all primaries started
+ indexRoutingTable = routingTable.index(indexName);
+ newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
+ allocationIds = ImmutableOpenIntMap.>builder();
+ for (final ObjectCursor shardEntry : indexRoutingTable.getShards().values()) {
+ final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
+ for (final ShardRouting shardRouting : shardRoutingTable.getShards()) {
+ if (shardRouting.primary() && shardRouting.started() == false) {
+ final ShardRouting newShardRouting = shardRouting.moveToStarted();
+ allocationIds.fPut(newShardRouting.getId(), Sets.newHashSet(newShardRouting.allocationId().getId()));
+ newIndexRoutingTable.addShard(newShardRouting);
+ } else {
+ newIndexRoutingTable.addShard(shardRouting);
+ }
+ }
+ }
+ routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
+ idxMetaBuilder = IndexMetaData.builder(clusterState.metaData().index(indexName));
+ for (final IntObjectCursor> entry : allocationIds.build()) {
+ idxMetaBuilder.putActiveAllocationIds(entry.key, entry.value);
+ }
+ metaDataBuilder = MetaData.builder(clusterState.metaData()).put(idxMetaBuilder);
+ clusterState = ClusterState.builder(clusterState).routingTable(routingTable).metaData(metaDataBuilder).build();
+ clusterStates.add(clusterState);
+
+ // initialize replicas
+ indexRoutingTable = routingTable.index(indexName);
+ newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
+ for (final ObjectCursor shardEntry : indexRoutingTable.getShards().values()) {
+ final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
+ for (final ShardRouting shardRouting : shardRoutingTable.getShards()) {
+ if (shardRouting.primary() == false) {
+ // give the replica a different node id than the primary
+ final String primaryNodeId = shardRoutingTable.primaryShard().currentNodeId();
+ String replicaNodeId;
+ do {
+ replicaNodeId = nodeIds.get(randomIntBetween(0, numNodes - 1));
+ } while (primaryNodeId.equals(replicaNodeId));
+ newIndexRoutingTable.addShard(
+ shardRouting.initialize(replicaNodeId, null, shardRouting.getExpectedShardSize())
+ );
+ } else {
+ newIndexRoutingTable.addShard(shardRouting);
+ }
+ }
+ }
+ routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
+ clusterStates.add(ClusterState.builder(clusterState).routingTable(routingTable).build());
+
+ // some replicas started
+ indexRoutingTable = routingTable.index(indexName);
+ newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
+ for (final ObjectCursor shardEntry : indexRoutingTable.getShards().values()) {
+ final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
+ for (final ShardRouting shardRouting : shardRoutingTable.getShards()) {
+ if (shardRouting.primary() == false && randomBoolean()) {
+ newIndexRoutingTable.addShard(shardRouting.moveToStarted());
+ } else {
+ newIndexRoutingTable.addShard(shardRouting);
+ }
+ }
+ }
+ routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
+ clusterStates.add(ClusterState.builder(clusterState).routingTable(routingTable).build());
+
+ // all replicas started
+ boolean replicaStateChanged = false;
+ indexRoutingTable = routingTable.index(indexName);
+ newIndexRoutingTable = IndexRoutingTable.builder(indexRoutingTable.getIndex());
+ for (final ObjectCursor shardEntry : indexRoutingTable.getShards().values()) {
+ final IndexShardRoutingTable shardRoutingTable = shardEntry.value;
+ for (final ShardRouting shardRouting : shardRoutingTable.getShards()) {
+ if (shardRouting.primary() == false && shardRouting.started() == false) {
+ newIndexRoutingTable.addShard(shardRouting.moveToStarted());
+ replicaStateChanged = true;
+ } else {
+ newIndexRoutingTable.addShard(shardRouting);
+ }
+ }
+ }
+ // all of the replicas may have moved to started in the previous phase already
+ if (replicaStateChanged) {
+ routingTable = RoutingTable.builder(routingTable).add(newIndexRoutingTable).build();
+ clusterStates.add(ClusterState.builder(clusterState).routingTable(routingTable).build());
+ }
+
+ return clusterStates;
+ }
+
+ // returns true if the inactive primaries in the index are only due to cluster recovery
+ // (not because of allocation failure or previously having allocation ids assigned)
+ private boolean primaryInactiveDueToRecovery(final String indexName, final ClusterState clusterState) {
+ for (final IntObjectCursor shardRouting : clusterState.routingTable().index(indexName).shards()) {
+ final ShardRouting primaryShard = shardRouting.value.primaryShard();
+ if (primaryShard.active() == false) {
+ if (clusterState.metaData().index(indexName).activeAllocationIds(shardRouting.key).isEmpty() == false) {
+ return false;
+ }
+ if (primaryShard.unassignedInfo() != null &&
+ primaryShard.unassignedInfo().getReason() == UnassignedInfo.Reason.ALLOCATION_FAILED) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
private void assertClusterHealth(ClusterStateHealth clusterStateHealth, RoutingTableGenerator.ShardCounter counter) {
assertThat(clusterStateHealth.getStatus(), equalTo(counter.status()));
assertThat(clusterStateHealth.getActiveShards(), equalTo(counter.active));
diff --git a/core/src/test/java/org/elasticsearch/cluster/metadata/IndexGraveyardTests.java b/core/src/test/java/org/elasticsearch/cluster/metadata/IndexGraveyardTests.java
index aec701052fb..8dd950ba8e6 100644
--- a/core/src/test/java/org/elasticsearch/cluster/metadata/IndexGraveyardTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/metadata/IndexGraveyardTests.java
@@ -60,8 +60,7 @@ public class IndexGraveyardTests extends ESTestCase {
final IndexGraveyard graveyard = createRandom();
final BytesStreamOutput out = new BytesStreamOutput();
graveyard.writeTo(out);
- final ByteBufferStreamInput in = new ByteBufferStreamInput(ByteBuffer.wrap(out.bytes().toBytes()));
- assertThat(IndexGraveyard.fromStream(in), equalTo(graveyard));
+ assertThat(IndexGraveyard.fromStream(out.bytes().streamInput()), equalTo(graveyard));
}
public void testXContent() throws IOException {
diff --git a/core/src/test/java/org/elasticsearch/cluster/metadata/IndexMetaDataTests.java b/core/src/test/java/org/elasticsearch/cluster/metadata/IndexMetaDataTests.java
index 0c9827587ea..5fef33be388 100644
--- a/core/src/test/java/org/elasticsearch/cluster/metadata/IndexMetaDataTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/metadata/IndexMetaDataTests.java
@@ -69,7 +69,7 @@ public class IndexMetaDataTests extends ESTestCase {
final BytesStreamOutput out = new BytesStreamOutput();
metaData.writeTo(out);
- IndexMetaData deserialized = IndexMetaData.PROTO.readFrom(StreamInput.wrap(out.bytes()));
+ IndexMetaData deserialized = IndexMetaData.PROTO.readFrom(out.bytes().streamInput());
assertEquals(metaData, deserialized);
assertEquals(metaData.hashCode(), deserialized.hashCode());
diff --git a/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexServiceTests.java b/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexServiceTests.java
index 04d27020273..f6f7aaf3228 100644
--- a/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataCreateIndexServiceTests.java
@@ -34,7 +34,7 @@ import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders;
import org.elasticsearch.cluster.routing.allocation.decider.MaxRetryAllocationDecider;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.indices.IndexAlreadyExistsException;
import org.elasticsearch.indices.InvalidIndexNameException;
@@ -181,7 +181,7 @@ public class MetaDataCreateIndexServiceTests extends ESTestCase {
}
private DiscoveryNode newNode(String nodeId) {
- return new DiscoveryNode(nodeId, DummyTransportAddress.INSTANCE, emptyMap(),
+ return new DiscoveryNode(nodeId, LocalTransportAddress.buildUnique(), emptyMap(),
Collections.unmodifiableSet(new HashSet<>(Arrays.asList(DiscoveryNode.Role.MASTER, DiscoveryNode.Role.DATA))), Version.CURRENT);
}
@@ -216,6 +216,7 @@ public class MetaDataCreateIndexServiceTests extends ESTestCase {
new HashSet<>(),
null,
null,
+ null,
null);
}
}
diff --git a/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataTests.java b/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataTests.java
index e1e3a39122c..cf040fb3c7f 100644
--- a/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataTests.java
@@ -22,7 +22,6 @@ package org.elasticsearch.cluster.metadata;
import org.elasticsearch.Version;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.bytes.BytesReference;
-import org.elasticsearch.common.io.stream.ByteBufferStreamInput;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent;
@@ -34,7 +33,6 @@ import org.elasticsearch.index.Index;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
-import java.nio.ByteBuffer;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
@@ -185,8 +183,7 @@ public class MetaDataTests extends ESTestCase {
final MetaData originalMeta = MetaData.builder().indexGraveyard(graveyard).build();
final BytesStreamOutput out = new BytesStreamOutput();
originalMeta.writeTo(out);
- final ByteBufferStreamInput in = new ByteBufferStreamInput(ByteBuffer.wrap(out.bytes().toBytes()));
- final MetaData fromStreamMeta = MetaData.PROTO.readFrom(in);
+ final MetaData fromStreamMeta = MetaData.PROTO.readFrom(out.bytes().streamInput());
assertThat(fromStreamMeta.indexGraveyard(), equalTo(fromStreamMeta.indexGraveyard()));
}
}
diff --git a/core/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodeFiltersTests.java b/core/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodeFiltersTests.java
index 38aa73a9935..59f058a95fb 100644
--- a/core/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodeFiltersTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodeFiltersTests.java
@@ -21,8 +21,8 @@ package org.elasticsearch.cluster.node;
import org.elasticsearch.Version;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.test.ESTestCase;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@@ -64,10 +64,11 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
.build();
DiscoveryNodeFilters filters = DiscoveryNodeFilters.buildFromSettings(OR, "xxx.", settings);
- DiscoveryNode node = new DiscoveryNode("name1", "id1", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ DiscoveryNode node = new DiscoveryNode("name1", "id1", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(),
+ Version.CURRENT);
assertThat(filters.match(node), equalTo(true));
- node = new DiscoveryNode("name2", "id2", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ node = new DiscoveryNode("name2", "id2", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT);
assertThat(filters.match(node), equalTo(false));
}
@@ -77,10 +78,11 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
.build();
DiscoveryNodeFilters filters = DiscoveryNodeFilters.buildFromSettings(OR, "xxx.", settings);
- DiscoveryNode node = new DiscoveryNode("name1", "id1", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ DiscoveryNode node = new DiscoveryNode("name1", "id1", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(),
+ Version.CURRENT);
assertThat(filters.match(node), equalTo(true));
- node = new DiscoveryNode("name2", "id2", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ node = new DiscoveryNode("name2", "id2", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT);
assertThat(filters.match(node), equalTo(false));
}
@@ -91,13 +93,14 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
.build());
DiscoveryNodeFilters filters = DiscoveryNodeFilters.buildFromSettings(OR, "xxx.", settings);
- DiscoveryNode node = new DiscoveryNode("name1", "id1", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ final Version version = Version.CURRENT;
+ DiscoveryNode node = new DiscoveryNode("name1", "id1", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), version);
assertThat(filters.match(node), equalTo(true));
- node = new DiscoveryNode("name2", "id2", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ node = new DiscoveryNode("name2", "id2", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), version);
assertThat(filters.match(node), equalTo(true));
- node = new DiscoveryNode("name3", "id3", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ node = new DiscoveryNode("name3", "id3", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), version);
assertThat(filters.match(node), equalTo(false));
}
@@ -111,7 +114,7 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
Map attributes = new HashMap<>();
attributes.put("tag", "A");
attributes.put("group", "B");
- DiscoveryNode node = new DiscoveryNode("name1", "id1", DummyTransportAddress.INSTANCE,
+ DiscoveryNode node = new DiscoveryNode("name1", "id1", LocalTransportAddress.buildUnique(),
attributes, emptySet(), Version.CURRENT);
assertThat(filters.match(node), equalTo(true));
@@ -119,7 +122,7 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
attributes.put("tag", "A");
attributes.put("group", "B");
attributes.put("name", "X");
- node = new DiscoveryNode("name2", "id2", DummyTransportAddress.INSTANCE,
+ node = new DiscoveryNode("name2", "id2", LocalTransportAddress.buildUnique(),
attributes, emptySet(), Version.CURRENT);
assertThat(filters.match(node), equalTo(true));
@@ -127,11 +130,11 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
attributes.put("tag", "A");
attributes.put("group", "F");
attributes.put("name", "X");
- node = new DiscoveryNode("name3", "id3", DummyTransportAddress.INSTANCE,
+ node = new DiscoveryNode("name3", "id3", LocalTransportAddress.buildUnique(),
attributes, emptySet(), Version.CURRENT);
assertThat(filters.match(node), equalTo(false));
- node = new DiscoveryNode("name4", "id4", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ node = new DiscoveryNode("name4", "id4", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT);
assertThat(filters.match(node), equalTo(false));
}
@@ -141,7 +144,8 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
.build();
DiscoveryNodeFilters filters = DiscoveryNodeFilters.buildFromSettings(OR, "xxx.", settings);
- DiscoveryNode node = new DiscoveryNode("name1", "id1", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ DiscoveryNode node = new DiscoveryNode("name1", "id1", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(),
+ Version.CURRENT);
assertThat(filters.match(node), equalTo(true));
}
@@ -152,7 +156,7 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
.build());
DiscoveryNodeFilters filters = DiscoveryNodeFilters.buildFromSettings(AND, "xxx.", settings);
- DiscoveryNode node = new DiscoveryNode("", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
+ DiscoveryNode node = new DiscoveryNode("", "", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
assertThat(filters.match(node), equalTo(true));
}
@@ -163,7 +167,7 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
.build());
DiscoveryNodeFilters filters = DiscoveryNodeFilters.buildFromSettings(AND, "xxx.", settings);
- DiscoveryNode node = new DiscoveryNode("", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
+ DiscoveryNode node = new DiscoveryNode("", "", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
assertThat(filters.match(node), equalTo(false));
}
@@ -174,7 +178,7 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
.build());
DiscoveryNodeFilters filters = DiscoveryNodeFilters.buildFromSettings(AND, "xxx.", settings);
- DiscoveryNode node = new DiscoveryNode("", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
+ DiscoveryNode node = new DiscoveryNode("", "", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
assertThat(filters.match(node), equalTo(false));
}
@@ -185,7 +189,7 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
.build());
DiscoveryNodeFilters filters = DiscoveryNodeFilters.buildFromSettings(OR, "xxx.", settings);
- DiscoveryNode node = new DiscoveryNode("", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
+ DiscoveryNode node = new DiscoveryNode("", "", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
assertThat(filters.match(node), equalTo(true));
}
@@ -196,7 +200,7 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
.build());
DiscoveryNodeFilters filters = DiscoveryNodeFilters.buildFromSettings(OR, "xxx.", settings);
- DiscoveryNode node = new DiscoveryNode("", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
+ DiscoveryNode node = new DiscoveryNode("", "", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
assertThat(filters.match(node), equalTo(true));
}
@@ -207,7 +211,7 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
.build());
DiscoveryNodeFilters filters = DiscoveryNodeFilters.buildFromSettings(AND, "xxx.", settings);
- DiscoveryNode node = new DiscoveryNode("", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
+ DiscoveryNode node = new DiscoveryNode("", "", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
assertThat(filters.match(node), equalTo(true));
}
@@ -218,7 +222,7 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
.build());
DiscoveryNodeFilters filters = DiscoveryNodeFilters.buildFromSettings(AND, "xxx.", settings);
- DiscoveryNode node = new DiscoveryNode("", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
+ DiscoveryNode node = new DiscoveryNode("", "", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
assertThat(filters.match(node), equalTo(false));
}
@@ -229,7 +233,7 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
.build());
DiscoveryNodeFilters filters = DiscoveryNodeFilters.buildFromSettings(OR, "xxx.", settings);
- DiscoveryNode node = new DiscoveryNode("", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
+ DiscoveryNode node = new DiscoveryNode("", "", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
assertThat(filters.match(node), equalTo(true));
}
@@ -240,7 +244,7 @@ public class DiscoveryNodeFiltersTests extends ESTestCase {
.build());
DiscoveryNodeFilters filters = DiscoveryNodeFilters.buildFromSettings(OR, "xxx.", settings);
- DiscoveryNode node = new DiscoveryNode("", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
+ DiscoveryNode node = new DiscoveryNode("", "", "", "", "192.1.1.54", localAddress, singletonMap("tag", "A"), emptySet(), null);
assertThat(filters.match(node), equalTo(true));
}
diff --git a/core/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodeServiceTests.java b/core/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodeServiceTests.java
deleted file mode 100644
index fb38a428a76..00000000000
--- a/core/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodeServiceTests.java
+++ /dev/null
@@ -1,83 +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.cluster.node;
-
-import org.elasticsearch.Version;
-import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
-import org.elasticsearch.test.ESTestCase;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-
-public class DiscoveryNodeServiceTests extends ESTestCase {
-
- public void testBuildLocalNode() {
- Map expectedAttributes = new HashMap<>();
- int numCustomSettings = randomIntBetween(0, 5);
- Settings.Builder builder = Settings.builder();
- for (int i = 0; i < numCustomSettings; i++) {
- builder.put("node.attr.attr" + i, "value" + i);
- expectedAttributes.put("attr" + i, "value" + i);
- }
- Set selectedRoles = new HashSet<>();
- for (DiscoveryNode.Role role : DiscoveryNode.Role.values()) {
- if (randomBoolean()) {
- //test default true for every role
- selectedRoles.add(role);
- } else {
- boolean isRoleEnabled = randomBoolean();
- builder.put("node." + role.getRoleName(), isRoleEnabled);
- if (isRoleEnabled) {
- selectedRoles.add(role);
- }
- }
- }
- DiscoveryNodeService discoveryNodeService = new DiscoveryNodeService(builder.build());
- DiscoveryNode discoveryNode = discoveryNodeService.buildLocalNode(DummyTransportAddress.INSTANCE);
- assertThat(discoveryNode.getRoles(), equalTo(selectedRoles));
- assertThat(discoveryNode.getAttributes(), equalTo(expectedAttributes));
- }
-
- public void testBuildAttributesWithCustomAttributeServiceProvider() {
- Map expectedAttributes = new HashMap<>();
- int numCustomSettings = randomIntBetween(0, 5);
- Settings.Builder builder = Settings.builder();
- for (int i = 0; i < numCustomSettings; i++) {
- builder.put("node.attr.attr" + i, "value" + i);
- expectedAttributes.put("attr" + i, "value" + i);
- }
- DiscoveryNodeService discoveryNodeService = new DiscoveryNodeService(builder.build());
- int numCustomAttributes = randomIntBetween(0, 5);
- Map customAttributes = new HashMap<>();
- for (int i = 0; i < numCustomAttributes; i++) {
- customAttributes.put("custom-" + randomAsciiOfLengthBetween(5, 10), randomAsciiOfLengthBetween(1, 10));
- }
- expectedAttributes.putAll(customAttributes);
- discoveryNodeService.addCustomAttributeProvider(() -> customAttributes);
-
- DiscoveryNode discoveryNode = discoveryNodeService.buildLocalNode(DummyTransportAddress.INSTANCE);
- assertThat(discoveryNode.getAttributes(), equalTo(expectedAttributes));
- }
-}
diff --git a/core/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodesTests.java b/core/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodesTests.java
index 984cd31b7a0..ec741a908c5 100644
--- a/core/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodesTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodesTests.java
@@ -19,8 +19,9 @@
package org.elasticsearch.cluster.node;
+import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import org.elasticsearch.Version;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.test.ESTestCase;
import java.util.ArrayList;
@@ -30,10 +31,15 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.nullValue;
public class DiscoveryNodesTests extends ESTestCase {
@@ -53,7 +59,7 @@ public class DiscoveryNodesTests extends ESTestCase {
DiscoveryNode resolvedNode = discoveryNodes.resolveNode(nodeSelector.selector);
assertThat(matchingNodeIds.size(), equalTo(1));
assertThat(resolvedNode.getId(), equalTo(matchingNodeIds.iterator().next()));
- } catch(IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
if (matchingNodeIds.size() == 0) {
assertThat(e.getMessage(), equalTo("failed to resolve [" + nodeSelector.selector + "], no matching nodes"));
} else if (matchingNodeIds.size() > 1) {
@@ -98,26 +104,98 @@ public class DiscoveryNodesTests extends ESTestCase {
assertThat(resolvedNodesIds, equalTo(expectedNodesIds));
}
- private static DiscoveryNodes buildDiscoveryNodes() {
- int numNodes = randomIntBetween(1, 10);
- DiscoveryNodes.Builder discoBuilder = DiscoveryNodes.builder();
+ public void testDeltas() {
+ Set nodesA = new HashSet<>();
+ nodesA.addAll(randomNodes(1 + randomInt(10)));
+ Set nodesB = new HashSet<>();
+ nodesB.addAll(randomNodes(1 + randomInt(5)));
+ for (DiscoveryNode node : randomSubsetOf(nodesA)) {
+ if (randomBoolean()) {
+ // change an attribute
+ Map attrs = new HashMap<>(node.getAttributes());
+ attrs.put("new", "new");
+ node = new DiscoveryNode(node.getName(), node.getId(), node.getAddress(), attrs, node.getRoles(), node.getVersion());
+ }
+ nodesB.add(node);
+ }
+
+ DiscoveryNode masterA = randomBoolean() ? null : RandomPicks.randomFrom(random(), nodesA);
+ DiscoveryNode masterB = randomBoolean() ? null : RandomPicks.randomFrom(random(), nodesB);
+
+ DiscoveryNodes.Builder builderA = DiscoveryNodes.builder();
+ nodesA.stream().forEach(builderA::put);
+ final String masterAId = masterA == null ? null : masterA.getId();
+ builderA.masterNodeId(masterAId);
+ builderA.localNodeId(RandomPicks.randomFrom(random(), nodesA).getId());
+
+ DiscoveryNodes.Builder builderB = DiscoveryNodes.builder();
+ nodesB.stream().forEach(builderB::put);
+ final String masterBId = masterB == null ? null : masterB.getId();
+ builderB.masterNodeId(masterBId);
+ builderB.localNodeId(RandomPicks.randomFrom(random(), nodesB).getId());
+
+ final DiscoveryNodes discoNodesA = builderA.build();
+ final DiscoveryNodes discoNodesB = builderB.build();
+ logger.info("nodes A: {}", discoNodesA.prettyPrint());
+ logger.info("nodes B: {}", discoNodesB.prettyPrint());
+
+ DiscoveryNodes.Delta delta = discoNodesB.delta(discoNodesA);
+
+ if (masterB == null || Objects.equals(masterAId, masterBId)) {
+ assertFalse(delta.masterNodeChanged());
+ assertThat(delta.previousMasterNode(), nullValue());
+ assertThat(delta.newMasterNode(), nullValue());
+ } else {
+ assertTrue(delta.masterNodeChanged());
+ assertThat(delta.newMasterNode().getId(), equalTo(masterBId));
+ assertThat(delta.previousMasterNode() != null ? delta.previousMasterNode().getId() : null,
+ equalTo(masterAId));
+ }
+
+ Set newNodes = new HashSet<>(nodesB);
+ newNodes.removeAll(nodesA);
+ assertThat(delta.added(), equalTo(newNodes.isEmpty() == false));
+ assertThat(delta.addedNodes(), containsInAnyOrder(newNodes.stream().collect(Collectors.toList()).toArray()));
+ assertThat(delta.addedNodes().size(), equalTo(newNodes.size()));
+
+ Set removedNodes = new HashSet<>(nodesA);
+ removedNodes.removeAll(nodesB);
+ assertThat(delta.removed(), equalTo(removedNodes.isEmpty() == false));
+ assertThat(delta.removedNodes(), containsInAnyOrder(removedNodes.stream().collect(Collectors.toList()).toArray()));
+ assertThat(delta.removedNodes().size(), equalTo(removedNodes.size()));
+ }
+
+ private static AtomicInteger idGenerator = new AtomicInteger();
+
+ private static List randomNodes(final int numNodes) {
List nodesList = new ArrayList<>();
for (int i = 0; i < numNodes; i++) {
Map attributes = new HashMap<>();
if (frequently()) {
attributes.put("custom", randomBoolean() ? "match" : randomAsciiOfLengthBetween(3, 5));
}
- final DiscoveryNode node = newNode(i, attributes, new HashSet<>(randomSubsetOf(Arrays.asList(DiscoveryNode.Role.values()))));
- discoBuilder = discoBuilder.put(node);
+ final DiscoveryNode node = newNode(idGenerator.getAndIncrement(), attributes,
+ new HashSet<>(randomSubsetOf(Arrays.asList(DiscoveryNode.Role.values()))));
nodesList.add(node);
}
+ return nodesList;
+ }
+
+ private static DiscoveryNodes buildDiscoveryNodes() {
+ int numNodes = randomIntBetween(1, 10);
+ DiscoveryNodes.Builder discoBuilder = DiscoveryNodes.builder();
+ List nodesList = randomNodes(numNodes);
+ for (DiscoveryNode node : nodesList) {
+ discoBuilder = discoBuilder.put(node);
+ }
discoBuilder.localNodeId(randomFrom(nodesList).getId());
discoBuilder.masterNodeId(randomFrom(nodesList).getId());
return discoBuilder.build();
}
private static DiscoveryNode newNode(int nodeId, Map attributes, Set roles) {
- return new DiscoveryNode("name_" + nodeId, "node_" + nodeId, DummyTransportAddress.INSTANCE, attributes, roles, Version.CURRENT);
+ return new DiscoveryNode("name_" + nodeId, "node_" + nodeId, LocalTransportAddress.buildUnique(), attributes, roles,
+ Version.CURRENT);
}
private enum NodeSelector {
@@ -152,7 +230,7 @@ public class DiscoveryNodesTests extends ESTestCase {
nodes.getIngestNodes().keysIt().forEachRemaining(ids::add);
return ids;
}
- },CUSTOM_ATTRIBUTE("attr:value") {
+ }, CUSTOM_ATTRIBUTE("attr:value") {
@Override
Set matchingNodeIds(DiscoveryNodes nodes) {
Set ids = new HashSet<>();
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/PrimaryAllocationIT.java b/core/src/test/java/org/elasticsearch/cluster/routing/PrimaryAllocationIT.java
index f990f382c8c..f267af66dc6 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/PrimaryAllocationIT.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/PrimaryAllocationIT.java
@@ -22,6 +22,7 @@ package org.elasticsearch.cluster.routing;
import com.carrotsearch.hppc.cursors.IntObjectCursor;
import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteRequestBuilder;
import org.elasticsearch.action.admin.indices.shards.IndicesShardStoresResponse;
+import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.routing.allocation.command.AllocateEmptyPrimaryAllocationCommand;
import org.elasticsearch.cluster.routing.allocation.command.AllocateStalePrimaryAllocationCommand;
@@ -108,7 +109,7 @@ public class PrimaryAllocationIT extends ESIntegTestCase {
logger.info("--> check that old primary shard does not get promoted to primary again");
// kick reroute and wait for all shard states to be fetched
client(master).admin().cluster().prepareReroute().get();
- assertBusy(new Runnable() {
+ assertBusy(new Runnable() {
@Override
public void run() {
assertThat(internalCluster().getInstance(GatewayAllocator.class, master).getNumberOfInFlightFetch(), equalTo(0));
@@ -157,7 +158,8 @@ public class PrimaryAllocationIT extends ESIntegTestCase {
createStaleReplicaScenario();
logger.info("--> explicitly promote old primary shard");
- ImmutableOpenIntMap> storeStatuses = client().admin().indices().prepareShardStores("test").get().getStoreStatuses().get("test");
+ final String idxName = "test";
+ ImmutableOpenIntMap> storeStatuses = client().admin().indices().prepareShardStores(idxName).get().getStoreStatuses().get(idxName);
ClusterRerouteRequestBuilder rerouteBuilder = client().admin().cluster().prepareReroute();
for (IntObjectCursor> shardStoreStatuses : storeStatuses) {
int shardId = shardStoreStatuses.key;
@@ -165,22 +167,30 @@ public class PrimaryAllocationIT extends ESIntegTestCase {
logger.info("--> adding allocation command for shard {}", shardId);
// force allocation based on node id
if (useStaleReplica) {
- rerouteBuilder.add(new AllocateStalePrimaryAllocationCommand("test", shardId, storeStatus.getNode().getId(), true));
+ rerouteBuilder.add(new AllocateStalePrimaryAllocationCommand(idxName, shardId, storeStatus.getNode().getId(), true));
} else {
- rerouteBuilder.add(new AllocateEmptyPrimaryAllocationCommand("test", shardId, storeStatus.getNode().getId(), true));
+ rerouteBuilder.add(new AllocateEmptyPrimaryAllocationCommand(idxName, shardId, storeStatus.getNode().getId(), true));
}
}
rerouteBuilder.get();
logger.info("--> check that the stale primary shard gets allocated and that documents are available");
- ensureYellow("test");
+ ensureYellow(idxName);
- assertHitCount(client().prepareSearch("test").setSize(0).setQuery(matchAllQuery()).get(), useStaleReplica ? 1L : 0L);
+ if (useStaleReplica == false) {
+ // When invoking AllocateEmptyPrimaryAllocationCommand, due to the UnassignedInfo.Reason being changed to INDEX_CREATION,
+ // its possible that the shard has not completed initialization, even though the cluster health is yellow, so the
+ // search can throw an "all shards failed" exception. We will wait until the shard initialization has completed before
+ // verifying the search hit count.
+ assertBusy(() -> assertTrue(clusterService().state().routingTable().index(idxName).allPrimaryShardsActive()));
+
+ }
+ assertHitCount(client().prepareSearch(idxName).setSize(0).setQuery(matchAllQuery()).get(), useStaleReplica ? 1L : 0L);
}
public void testForcePrimaryShardIfAllocationDecidersSayNoAfterIndexCreation() throws ExecutionException, InterruptedException {
String node = internalCluster().startNode();
- client().admin().indices().prepareCreate("test").setSettings(Settings.builder()
+ client().admin().indices().prepareCreate("test").setWaitForActiveShards(ActiveShardCount.NONE).setSettings(Settings.builder()
.put("index.routing.allocation.exclude._name", node)
.put("index.number_of_shards", 1).put("index.number_of_replicas", 0)).get();
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/PrimaryTermsTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/PrimaryTermsTests.java
index 2d3e44db68a..32072282d6f 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/PrimaryTermsTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/PrimaryTermsTests.java
@@ -50,7 +50,7 @@ public class PrimaryTermsTests extends ESAllocationTestCase {
private RoutingTable testRoutingTable;
private int numberOfShards;
private int numberOfReplicas;
- private final static Settings DEFAULT_SETTINGS = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build();
+ private static final Settings DEFAULT_SETTINGS = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build();
private AllocationService allocationService;
private ClusterState clusterState;
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/RoutingTableGenerator.java b/core/src/test/java/org/elasticsearch/cluster/routing/RoutingTableGenerator.java
index cea89b09542..62002ad1f99 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/RoutingTableGenerator.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/RoutingTableGenerator.java
@@ -24,6 +24,8 @@ import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.index.shard.ShardId;
+import static org.elasticsearch.cluster.health.ClusterShardHealth.getInactivePrimaryHealth;
+
public class RoutingTableGenerator {
private static int node_id = 1;
@@ -56,14 +58,15 @@ public class RoutingTableGenerator {
}
- public IndexShardRoutingTable genShardRoutingTable(String index, int shardId, int replicas, ShardCounter counter) {
+ public IndexShardRoutingTable genShardRoutingTable(IndexMetaData indexMetaData, int shardId, ShardCounter counter) {
+ final String index = indexMetaData.getIndex().getName();
IndexShardRoutingTable.Builder builder = new IndexShardRoutingTable.Builder(new ShardId(index, "_na_", shardId));
ShardRouting shardRouting = genShardRouting(index, shardId, true);
- counter.update(shardRouting);
+ counter.update(shardRouting, indexMetaData);
builder.addShard(shardRouting);
- for (; replicas > 0; replicas--) {
+ for (int replicas = indexMetaData.getNumberOfReplicas(); replicas > 0; replicas--) {
shardRouting = genShardRouting(index, shardId, false);
- counter.update(shardRouting);
+ counter.update(shardRouting, indexMetaData);
builder.addShard(shardRouting);
}
@@ -73,8 +76,7 @@ public class RoutingTableGenerator {
public IndexRoutingTable genIndexRoutingTable(IndexMetaData indexMetaData, ShardCounter counter) {
IndexRoutingTable.Builder builder = IndexRoutingTable.builder(indexMetaData.getIndex());
for (int shard = 0; shard < indexMetaData.getNumberOfShards(); shard++) {
- builder.addIndexShard(genShardRoutingTable(indexMetaData.getIndex().getName(), shard,
- indexMetaData.getNumberOfReplicas(), counter));
+ builder.addIndexShard(genShardRoutingTable(indexMetaData, shard, counter));
}
return builder.build();
}
@@ -86,10 +88,15 @@ public class RoutingTableGenerator {
public int unassigned;
public int primaryActive;
public int primaryInactive;
+ private boolean inactivePrimaryCausesRed = false;
public ClusterHealthStatus status() {
if (primaryInactive > 0) {
- return ClusterHealthStatus.RED;
+ if (inactivePrimaryCausesRed) {
+ return ClusterHealthStatus.RED;
+ } else {
+ return ClusterHealthStatus.YELLOW;
+ }
}
if (unassigned > 0 || initializing > 0) {
return ClusterHealthStatus.YELLOW;
@@ -97,7 +104,7 @@ public class RoutingTableGenerator {
return ClusterHealthStatus.GREEN;
}
- public void update(ShardRouting shardRouting) {
+ public void update(ShardRouting shardRouting, IndexMetaData indexMetaData) {
if (shardRouting.active()) {
active++;
if (shardRouting.primary()) {
@@ -111,6 +118,9 @@ public class RoutingTableGenerator {
if (shardRouting.primary()) {
primaryInactive++;
+ if (inactivePrimaryCausesRed == false) {
+ inactivePrimaryCausesRed = getInactivePrimaryHealth(shardRouting, indexMetaData) == ClusterHealthStatus.RED;
+ }
}
if (shardRouting.initializing()) {
initializing++;
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/RoutingTableTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/RoutingTableTests.java
index 2d1a467a001..9da5e76ed1f 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/RoutingTableTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/RoutingTableTests.java
@@ -47,7 +47,7 @@ public class RoutingTableTests extends ESAllocationTestCase {
private int numberOfReplicas;
private int shardsPerIndex;
private int totalNumberOfShards;
- private final static Settings DEFAULT_SETTINGS = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build();
+ private static final Settings DEFAULT_SETTINGS = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build();
private final AllocationService ALLOCATION_SERVICE = createAllocationService(Settings.builder()
.put("cluster.routing.allocation.node_concurrent_recoveries", Integer.MAX_VALUE) // don't limit recoveries
.put("cluster.routing.allocation.node_initial_primaries_recoveries", Integer.MAX_VALUE)
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/ShardRoutingTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/ShardRoutingTests.java
index 7267252b19f..fa9133f6d36 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/ShardRoutingTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/ShardRoutingTests.java
@@ -206,7 +206,7 @@ public class ShardRoutingTests extends ESTestCase {
if (randomBoolean()) {
BytesStreamOutput out = new BytesStreamOutput();
routing.writeTo(out);
- routing = new ShardRouting(StreamInput.wrap(out.bytes()));
+ routing = new ShardRouting(out.bytes().streamInput());
}
if (routing.initializing() || routing.relocating()) {
assertEquals(routing.toString(), byteSize, routing.getExpectedShardSize());
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/UnassignedInfoTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/UnassignedInfoTests.java
index 75300a4beb8..0854d27e208 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/UnassignedInfoTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/UnassignedInfoTests.java
@@ -26,19 +26,22 @@ import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
+import org.elasticsearch.cluster.routing.UnassignedInfo.AllocationStatus;
import org.elasticsearch.common.UUIDs;
+import org.elasticsearch.common.io.stream.ByteBufferStreamInput;
import org.elasticsearch.snapshots.SnapshotId;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.FailedRerouteAllocation;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
-import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.Index;
import org.elasticsearch.snapshots.Snapshot;
import org.elasticsearch.test.ESAllocationTestCase;
+import java.io.IOException;
+import java.nio.ByteBuffer;
import java.util.Collections;
import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING;
@@ -76,13 +79,14 @@ public class UnassignedInfoTests extends ESAllocationTestCase {
public void testSerialization() throws Exception {
UnassignedInfo.Reason reason = RandomPicks.randomFrom(random(), UnassignedInfo.Reason.values());
UnassignedInfo meta = reason == UnassignedInfo.Reason.ALLOCATION_FAILED ?
- new UnassignedInfo(reason, randomBoolean() ? randomAsciiOfLength(4) : null, null, randomIntBetween(1, 100), System.nanoTime(), System.currentTimeMillis(), false):
+ new UnassignedInfo(reason, randomBoolean() ? randomAsciiOfLength(4) : null, null, randomIntBetween(1, 100), System.nanoTime(),
+ System.currentTimeMillis(), false, AllocationStatus.NO_ATTEMPT):
new UnassignedInfo(reason, randomBoolean() ? randomAsciiOfLength(4) : null);
BytesStreamOutput out = new BytesStreamOutput();
meta.writeTo(out);
out.close();
- UnassignedInfo read = new UnassignedInfo(StreamInput.wrap(out.bytes()));
+ UnassignedInfo read = new UnassignedInfo(out.bytes().streamInput());
assertThat(read.getReason(), equalTo(meta.getReason()));
assertThat(read.getUnassignedTimeInMillis(), equalTo(meta.getUnassignedTimeInMillis()));
assertThat(read.getMessage(), equalTo(meta.getMessage()));
@@ -265,7 +269,8 @@ public class UnassignedInfoTests extends ESAllocationTestCase {
*/
public void testRemainingDelayCalculation() throws Exception {
final long baseTime = System.nanoTime();
- UnassignedInfo unassignedInfo = new UnassignedInfo(UnassignedInfo.Reason.NODE_LEFT, "test", null, 0, baseTime, System.currentTimeMillis(), randomBoolean());
+ UnassignedInfo unassignedInfo = new UnassignedInfo(UnassignedInfo.Reason.NODE_LEFT, "test", null, 0, baseTime,
+ System.currentTimeMillis(), randomBoolean(), AllocationStatus.NO_ATTEMPT);
final long totalDelayNanos = TimeValue.timeValueMillis(10).nanos();
final Settings indexSettings = Settings.builder().put(UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING.getKey(), TimeValue.timeValueNanos(totalDelayNanos)).build();
long delay = unassignedInfo.getRemainingDelay(baseTime, indexSettings);
@@ -340,4 +345,14 @@ public class UnassignedInfoTests extends ESAllocationTestCase {
assertThat(UnassignedInfo.findNextDelayedAllocation(baseTime + delta, clusterState), equalTo(expectMinDelaySettingsNanos - delta));
}
+
+ public void testAllocationStatusSerialization() throws IOException {
+ for (AllocationStatus allocationStatus : AllocationStatus.values()) {
+ BytesStreamOutput out = new BytesStreamOutput();
+ allocationStatus.writeTo(out);
+ ByteBufferStreamInput in = new ByteBufferStreamInput(ByteBuffer.wrap(out.bytes().toBytesRef().bytes));
+ AllocationStatus readStatus = AllocationStatus.readFrom(in);
+ assertThat(readStatus, equalTo(allocationStatus));
+ }
+ }
}
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/AllocationCommandsTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/AllocationCommandsTests.java
index 28f27b8988c..f95fb687c76 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/AllocationCommandsTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/AllocationCommandsTests.java
@@ -430,7 +430,7 @@ public class AllocationCommandsTests extends ESAllocationTestCase {
);
BytesStreamOutput bytes = new BytesStreamOutput();
AllocationCommands.writeTo(commands, bytes);
- StreamInput in = StreamInput.wrap(bytes.bytes());
+ StreamInput in = bytes.bytes().streamInput();
// Since the commands are named writeable we need to register them and wrap the input stream
NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry();
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/ClusterRebalanceRoutingTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/ClusterRebalanceRoutingTests.java
index 95ce9d668ea..458432ff78e 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/ClusterRebalanceRoutingTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/ClusterRebalanceRoutingTests.java
@@ -27,6 +27,7 @@ import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.ShardRouting;
+import org.elasticsearch.cluster.routing.UnassignedInfo;
import org.elasticsearch.cluster.routing.allocation.decider.ClusterRebalanceAllocationDecider;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
@@ -642,7 +643,7 @@ public class ClusterRebalanceRoutingTests extends ESAllocationTestCase {
while (iterator.hasNext()) {
ShardRouting next = iterator.next();
if ("test1".equals(next.index().getName())) {
- iterator.removeAndIgnore();
+ iterator.removeAndIgnore(UnassignedInfo.AllocationStatus.NO_ATTEMPT);
}
}
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/DecisionsImpactOnClusterHealthTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/DecisionsImpactOnClusterHealthTests.java
new file mode 100644
index 00000000000..e9f487b1e10
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/DecisionsImpactOnClusterHealthTests.java
@@ -0,0 +1,169 @@
+/*
+ * 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.cluster.routing.allocation;
+
+import org.elasticsearch.Version;
+import org.elasticsearch.cluster.ClusterName;
+import org.elasticsearch.cluster.ClusterState;
+import org.elasticsearch.cluster.EmptyClusterInfoService;
+import org.elasticsearch.cluster.health.ClusterHealthStatus;
+import org.elasticsearch.cluster.health.ClusterStateHealth;
+import org.elasticsearch.cluster.metadata.IndexMetaData;
+import org.elasticsearch.cluster.metadata.MetaData;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
+import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
+import org.elasticsearch.cluster.routing.RoutingNode;
+import org.elasticsearch.cluster.routing.RoutingTable;
+import org.elasticsearch.cluster.routing.ShardRouting;
+import org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator;
+import org.elasticsearch.cluster.routing.allocation.decider.AllocationDecider;
+import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders;
+import org.elasticsearch.cluster.routing.allocation.decider.Decision;
+import org.elasticsearch.common.settings.Settings;
+import org.elasticsearch.env.Environment;
+import org.elasticsearch.test.ESAllocationTestCase;
+import org.elasticsearch.test.gateway.NoopGatewayAllocator;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.Set;
+
+import static org.hamcrest.Matchers.equalTo;
+
+/**
+ * This class of tests exercise various scenarios of
+ * primary shard allocation and assert the cluster health
+ * has the correct status based on those allocation decisions.
+ */
+public class DecisionsImpactOnClusterHealthTests extends ESAllocationTestCase {
+
+ public void testPrimaryShardNoDecisionOnIndexCreation() throws IOException {
+ final String indexName = "test-idx";
+ Settings settings = Settings.builder()
+ .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString())
+ .build();
+ AllocationDecider decider = new TestAllocateDecision(Decision.NO);
+ // if deciders say NO to allocating a primary shard, then the cluster health should be RED
+ runAllocationTest(
+ settings, indexName, Collections.singleton(decider), ClusterHealthStatus.RED
+ );
+ }
+
+ public void testPrimaryShardThrottleDecisionOnIndexCreation() throws IOException {
+ final String indexName = "test-idx";
+ Settings settings = Settings.builder()
+ .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString())
+ .build();
+ AllocationDecider decider = new TestAllocateDecision(Decision.THROTTLE) {
+ // the only allocation decider that implements this is ShardsLimitAllocationDecider and it always
+ // returns only YES or NO, never THROTTLE
+ @Override
+ public Decision canAllocate(RoutingNode node, RoutingAllocation allocation) {
+ return randomBoolean() ? Decision.YES : Decision.NO;
+ }
+ };
+ // if deciders THROTTLE allocating a primary shard, stay in YELLOW state
+ runAllocationTest(
+ settings, indexName, Collections.singleton(decider), ClusterHealthStatus.YELLOW
+ );
+ }
+
+ public void testPrimaryShardYesDecisionOnIndexCreation() throws IOException {
+ final String indexName = "test-idx";
+ Settings settings = Settings.builder()
+ .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString())
+ .build();
+ AllocationDecider decider = new TestAllocateDecision(Decision.YES) {
+ @Override
+ public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) {
+ if (node.getByShardId(shardRouting.shardId()) == null) {
+ return Decision.YES;
+ } else {
+ return Decision.NO;
+ }
+ }
+ };
+ // if deciders say YES to allocating primary shards, stay in YELLOW state
+ ClusterState clusterState = runAllocationTest(
+ settings, indexName, Collections.singleton(decider), ClusterHealthStatus.YELLOW
+ );
+ // make sure primaries are initialized
+ RoutingTable routingTable = clusterState.routingTable();
+ for (IndexShardRoutingTable indexShardRoutingTable : routingTable.index(indexName)) {
+ assertTrue(indexShardRoutingTable.primaryShard().initializing());
+ }
+ }
+
+ private ClusterState runAllocationTest(final Settings settings,
+ final String indexName,
+ final Set allocationDeciders,
+ final ClusterHealthStatus expectedStatus) throws IOException {
+
+ final String clusterName = "test-cluster";
+ final AllocationService allocationService = newAllocationService(settings, allocationDeciders);
+
+ logger.info("Building initial routing table");
+ final int numShards = randomIntBetween(1, 5);
+ MetaData metaData = MetaData.builder()
+ .put(IndexMetaData.builder(indexName)
+ .settings(settings(Version.CURRENT))
+ .numberOfShards(numShards)
+ .numberOfReplicas(1))
+ .build();
+
+ RoutingTable routingTable = RoutingTable.builder()
+ .addAsNew(metaData.index(indexName))
+ .build();
+
+ ClusterState clusterState = ClusterState.builder(new ClusterName(clusterName))
+ .metaData(metaData)
+ .routingTable(routingTable)
+ .build();
+
+ logger.info("--> adding nodes");
+ // we need at least as many nodes as shards for the THROTTLE case, because
+ // once a shard has been throttled on a node, that node no longer accepts
+ // any allocations on it
+ final DiscoveryNodes.Builder discoveryNodes = DiscoveryNodes.builder();
+ for (int i = 0; i < numShards; i++) {
+ discoveryNodes.put(newNode("node" + i));
+ }
+ clusterState = ClusterState.builder(clusterState).nodes(discoveryNodes).build();
+
+ logger.info("--> do the reroute");
+ routingTable = allocationService.reroute(clusterState, "reroute").routingTable();
+ clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
+
+ logger.info("--> assert cluster health");
+ ClusterStateHealth health = new ClusterStateHealth(clusterState);
+ assertThat(health.getStatus(), equalTo(expectedStatus));
+
+ return clusterState;
+ }
+
+ private static AllocationService newAllocationService(Settings settings, Set deciders) {
+ return new AllocationService(settings,
+ new AllocationDeciders(settings, deciders),
+ NoopGatewayAllocator.INSTANCE,
+ new BalancedShardsAllocator(settings),
+ EmptyClusterInfoService.INSTANCE);
+ }
+
+}
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/NodeVersionAllocationDeciderTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/NodeVersionAllocationDeciderTests.java
index 6dd4df59060..9859cd4d570 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/NodeVersionAllocationDeciderTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/NodeVersionAllocationDeciderTests.java
@@ -25,8 +25,6 @@ import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.EmptyClusterInfoService;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
-import org.elasticsearch.common.UUIDs;
-import org.elasticsearch.snapshots.SnapshotId;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
@@ -44,12 +42,14 @@ import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders;
import org.elasticsearch.cluster.routing.allocation.decider.ClusterRebalanceAllocationDecider;
import org.elasticsearch.cluster.routing.allocation.decider.NodeVersionAllocationDecider;
import org.elasticsearch.cluster.routing.allocation.decider.ReplicaAfterPrimaryActiveAllocationDecider;
+import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.snapshots.Snapshot;
+import org.elasticsearch.snapshots.SnapshotId;
import org.elasticsearch.test.ESAllocationTestCase;
import org.elasticsearch.test.VersionUtils;
import org.elasticsearch.test.gateway.NoopGatewayAllocator;
@@ -307,11 +307,11 @@ public class NodeVersionAllocationDeciderTests extends ESAllocationTestCase {
public void testRebalanceDoesNotAllocatePrimaryAndReplicasOnDifferentVersionNodes() {
ShardId shard1 = new ShardId("test1", "_na_", 0);
ShardId shard2 = new ShardId("test2", "_na_", 0);
- final DiscoveryNode newNode = new DiscoveryNode("newNode", DummyTransportAddress.INSTANCE, emptyMap(),
+ final DiscoveryNode newNode = new DiscoveryNode("newNode", LocalTransportAddress.buildUnique(), emptyMap(),
MASTER_DATA_ROLES, Version.CURRENT);
- final DiscoveryNode oldNode1 = new DiscoveryNode("oldNode1", DummyTransportAddress.INSTANCE, emptyMap(),
+ final DiscoveryNode oldNode1 = new DiscoveryNode("oldNode1", LocalTransportAddress.buildUnique(), emptyMap(),
MASTER_DATA_ROLES, VersionUtils.getPreviousVersion());
- final DiscoveryNode oldNode2 = new DiscoveryNode("oldNode2", DummyTransportAddress.INSTANCE, emptyMap(),
+ final DiscoveryNode oldNode2 = new DiscoveryNode("oldNode2", LocalTransportAddress.buildUnique(), emptyMap(),
MASTER_DATA_ROLES, VersionUtils.getPreviousVersion());
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder(shard1.getIndexName()).settings(settings(Version.CURRENT).put(Settings.EMPTY)).numberOfShards(1).numberOfReplicas(1))
@@ -347,11 +347,11 @@ public class NodeVersionAllocationDeciderTests extends ESAllocationTestCase {
}
public void testRestoreDoesNotAllocateSnapshotOnOlderNodes() {
- final DiscoveryNode newNode = new DiscoveryNode("newNode", DummyTransportAddress.INSTANCE, emptyMap(),
+ final DiscoveryNode newNode = new DiscoveryNode("newNode", LocalTransportAddress.buildUnique(), emptyMap(),
MASTER_DATA_ROLES, Version.CURRENT);
- final DiscoveryNode oldNode1 = new DiscoveryNode("oldNode1", DummyTransportAddress.INSTANCE, emptyMap(),
+ final DiscoveryNode oldNode1 = new DiscoveryNode("oldNode1", LocalTransportAddress.buildUnique(), emptyMap(),
MASTER_DATA_ROLES, VersionUtils.getPreviousVersion());
- final DiscoveryNode oldNode2 = new DiscoveryNode("oldNode2", DummyTransportAddress.INSTANCE, emptyMap(),
+ final DiscoveryNode oldNode2 = new DiscoveryNode("oldNode2", LocalTransportAddress.buildUnique(), emptyMap(),
MASTER_DATA_ROLES, VersionUtils.getPreviousVersion());
int numberOfShards = randomIntBetween(1, 3);
@@ -407,7 +407,7 @@ public class NodeVersionAllocationDeciderTests extends ESAllocationTestCase {
return clusterState;
}
- private final void assertRecoveryNodeVersions(RoutingNodes routingNodes) {
+ private void assertRecoveryNodeVersions(RoutingNodes routingNodes) {
logger.trace("RoutingNodes: {}", routingNodes.prettyPrint());
List mutableShardRoutings = routingNodes.shardsWithState(ShardRoutingState.RELOCATING);
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/SameShardRoutingTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/SameShardRoutingTests.java
index 3d0475ed137..e09d9790651 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/SameShardRoutingTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/SameShardRoutingTests.java
@@ -33,7 +33,7 @@ import org.elasticsearch.cluster.routing.allocation.decider.SameShardAllocationD
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.test.ESAllocationTestCase;
import static java.util.Collections.emptyMap;
@@ -63,9 +63,9 @@ public class SameShardRoutingTests extends ESAllocationTestCase {
logger.info("--> adding two nodes with the same host");
clusterState = ClusterState.builder(clusterState).nodes(
DiscoveryNodes.builder()
- .put(new DiscoveryNode("node1", "node1", "test1", "test1", DummyTransportAddress.INSTANCE, emptyMap(),
+ .put(new DiscoveryNode("node1", "node1", "node1", "test1", "test1", LocalTransportAddress.buildUnique(), emptyMap(),
MASTER_DATA_ROLES, Version.CURRENT))
- .put(new DiscoveryNode("node2", "node2", "test1", "test1", DummyTransportAddress.INSTANCE, emptyMap(),
+ .put(new DiscoveryNode("node2", "node2", "node2", "test1", "test1", LocalTransportAddress.buildUnique(), emptyMap(),
MASTER_DATA_ROLES, Version.CURRENT))).build();
routingTable = strategy.reroute(clusterState, "reroute").routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
@@ -82,7 +82,7 @@ public class SameShardRoutingTests extends ESAllocationTestCase {
logger.info("--> add another node, with a different host, replicas will be allocating");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())
- .put(new DiscoveryNode("node3", "node3", "test2", "test2", DummyTransportAddress.INSTANCE, emptyMap(),
+ .put(new DiscoveryNode("node3", "node3", "node3", "test2", "test2", LocalTransportAddress.buildUnique(), emptyMap(),
MASTER_DATA_ROLES, Version.CURRENT))).build();
routingTable = strategy.reroute(clusterState, "reroute").routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderUnitTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderUnitTests.java
index be50c5f5331..56ca6381af9 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderUnitTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderUnitTests.java
@@ -41,7 +41,6 @@ import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.index.Index;
@@ -110,9 +109,9 @@ public class DiskThresholdDeciderUnitTests extends ESAllocationTestCase {
final Index index = metaData.index("test").getIndex();
ShardRouting test_0 = ShardRouting.newUnassigned(new ShardId(index, 0), null, true, new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, "foo"));
- DiscoveryNode node_0 = new DiscoveryNode("node_0", DummyTransportAddress.INSTANCE, Collections.emptyMap(),
+ DiscoveryNode node_0 = new DiscoveryNode("node_0", LocalTransportAddress.buildUnique(), Collections.emptyMap(),
new HashSet<>(Arrays.asList(DiscoveryNode.Role.values())), Version.CURRENT);
- DiscoveryNode node_1 = new DiscoveryNode("node_1", DummyTransportAddress.INSTANCE, Collections.emptyMap(),
+ DiscoveryNode node_1 = new DiscoveryNode("node_1", LocalTransportAddress.buildUnique(), Collections.emptyMap(),
new HashSet<>(Arrays.asList(DiscoveryNode.Role.values())), Version.CURRENT);
RoutingTable routingTable = RoutingTable.builder()
@@ -149,9 +148,9 @@ public class DiskThresholdDeciderUnitTests extends ESAllocationTestCase {
DiskThresholdDecider decider = new DiskThresholdDecider(Settings.EMPTY, nss, cis, null);
ImmutableOpenMap.Builder shardRoutingMap = ImmutableOpenMap.builder();
- DiscoveryNode node_0 = new DiscoveryNode("node_0", DummyTransportAddress.INSTANCE, Collections.emptyMap(),
+ DiscoveryNode node_0 = new DiscoveryNode("node_0", LocalTransportAddress.buildUnique(), Collections.emptyMap(),
new HashSet<>(Arrays.asList(DiscoveryNode.Role.values())), Version.CURRENT);
- DiscoveryNode node_1 = new DiscoveryNode("node_1", DummyTransportAddress.INSTANCE, Collections.emptyMap(),
+ DiscoveryNode node_1 = new DiscoveryNode("node_1", LocalTransportAddress.buildUnique(), Collections.emptyMap(),
new HashSet<>(Arrays.asList(DiscoveryNode.Role.values())), Version.CURRENT);
MetaData metaData = MetaData.builder()
diff --git a/core/src/test/java/org/elasticsearch/cluster/serialization/ClusterSerializationTests.java b/core/src/test/java/org/elasticsearch/cluster/serialization/ClusterSerializationTests.java
index 7b81d3ece27..4fa6615ac45 100644
--- a/core/src/test/java/org/elasticsearch/cluster/serialization/ClusterSerializationTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/serialization/ClusterSerializationTests.java
@@ -80,7 +80,7 @@ public class ClusterSerializationTests extends ESAllocationTestCase {
BytesStreamOutput outStream = new BytesStreamOutput();
source.writeTo(outStream);
- StreamInput inStream = StreamInput.wrap(outStream.bytes().toBytes());
+ StreamInput inStream = outStream.bytes().streamInput();
RoutingTable target = RoutingTable.Builder.readFrom(inStream);
assertThat(target.prettyPrint(), equalTo(source.prettyPrint()));
diff --git a/core/src/test/java/org/elasticsearch/cluster/serialization/ClusterStateToStringTests.java b/core/src/test/java/org/elasticsearch/cluster/serialization/ClusterStateToStringTests.java
index 99cde60f086..9957a6d3603 100644
--- a/core/src/test/java/org/elasticsearch/cluster/serialization/ClusterStateToStringTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/serialization/ClusterStateToStringTests.java
@@ -29,7 +29,7 @@ import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.test.ESAllocationTestCase;
import static java.util.Collections.emptyMap;
@@ -50,7 +50,7 @@ public class ClusterStateToStringTests extends ESAllocationTestCase {
.addAsNew(metaData.index("test_idx"))
.build();
- DiscoveryNodes nodes = DiscoveryNodes.builder().put(new DiscoveryNode("node_foo", DummyTransportAddress.INSTANCE,
+ DiscoveryNodes nodes = DiscoveryNodes.builder().put(new DiscoveryNode("node_foo", LocalTransportAddress.buildUnique(),
emptyMap(), emptySet(), Version.CURRENT)).localNodeId("node_foo").masterNodeId("node_foo").build();
ClusterState clusterState = ClusterState.builder(ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY)).nodes(nodes)
diff --git a/core/src/test/java/org/elasticsearch/cluster/serialization/DiffableTests.java b/core/src/test/java/org/elasticsearch/cluster/serialization/DiffableTests.java
index 452c6054576..611c261e334 100644
--- a/core/src/test/java/org/elasticsearch/cluster/serialization/DiffableTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/serialization/DiffableTests.java
@@ -310,7 +310,7 @@ public class DiffableTests extends ESTestCase {
logger.debug("--> serializing diff");
BytesStreamOutput out = new BytesStreamOutput();
diffMap.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
logger.debug("--> reading diff back");
diffMap = readDiff(in);
}
diff --git a/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceIT.java b/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceIT.java
index 991f11a4493..68537038eb2 100644
--- a/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceIT.java
+++ b/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceIT.java
@@ -57,9 +57,6 @@ import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
-/**
- *
- */
@ClusterScope(scope = Scope.TEST, numDataNodes = 0)
@ESIntegTestCase.SuppressLocalMode
public class ClusterServiceIT extends ESIntegTestCase {
@@ -94,7 +91,7 @@ public class ClusterServiceIT extends ESIntegTestCase {
}
@Override
- public void onAllNodesAcked(@Nullable Throwable t) {
+ public void onAllNodesAcked(@Nullable Exception e) {
allNodesAcked.set(true);
latch.countDown();
}
@@ -127,8 +124,8 @@ public class ClusterServiceIT extends ESIntegTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
- logger.error("failed to execute callback in test {}", t, source);
+ public void onFailure(String source, Exception e) {
+ logger.error("failed to execute callback in test {}", e, source);
onFailure.set(true);
latch.countDown();
}
@@ -165,7 +162,7 @@ public class ClusterServiceIT extends ESIntegTestCase {
}
@Override
- public void onAllNodesAcked(@Nullable Throwable t) {
+ public void onAllNodesAcked(@Nullable Exception e) {
allNodesAcked.set(true);
latch.countDown();
}
@@ -198,8 +195,8 @@ public class ClusterServiceIT extends ESIntegTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
- logger.error("failed to execute callback in test {}", t, source);
+ public void onFailure(String source, Exception e) {
+ logger.error("failed to execute callback in test {}", e, source);
onFailure.set(true);
latch.countDown();
}
@@ -240,7 +237,7 @@ public class ClusterServiceIT extends ESIntegTestCase {
}
@Override
- public void onAllNodesAcked(@Nullable Throwable t) {
+ public void onAllNodesAcked(@Nullable Exception e) {
allNodesAcked.set(true);
latch.countDown();
}
@@ -272,8 +269,8 @@ public class ClusterServiceIT extends ESIntegTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
- logger.error("failed to execute callback in test {}", t, source);
+ public void onFailure(String source, Exception e) {
+ logger.error("failed to execute callback in test {}", e, source);
onFailure.set(true);
latch.countDown();
}
@@ -313,7 +310,7 @@ public class ClusterServiceIT extends ESIntegTestCase {
}
@Override
- public void onAllNodesAcked(@Nullable Throwable t) {
+ public void onAllNodesAcked(@Nullable Exception e) {
allNodesAcked.set(true);
latch.countDown();
}
@@ -346,8 +343,8 @@ public class ClusterServiceIT extends ESIntegTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
- logger.error("failed to execute callback in test {}", t, source);
+ public void onFailure(String source, Exception e) {
+ logger.error("failed to execute callback in test {}", e, source);
onFailure.set(true);
latch.countDown();
}
@@ -388,7 +385,7 @@ public class ClusterServiceIT extends ESIntegTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
invoked1.countDown();
fail();
}
@@ -403,7 +400,7 @@ public class ClusterServiceIT extends ESIntegTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
fail();
}
@@ -458,7 +455,7 @@ public class ClusterServiceIT extends ESIntegTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
invoked3.countDown();
fail();
}
@@ -473,7 +470,7 @@ public class ClusterServiceIT extends ESIntegTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
fail();
}
});
@@ -520,7 +517,6 @@ public class ClusterServiceIT extends ESIntegTestCase {
assertThat(clusterService.state().nodes().getMasterNode(), notNullValue());
assertThat(clusterService.state().nodes().isLocalNodeElectedMaster(), is(true));
assertThat(testService.master(), is(true));
-
String node_1 = internalCluster().startNode(settings);
final ClusterService clusterService1 = internalCluster().getInstance(ClusterService.class, node_1);
MasterAwareService testService1 = internalCluster().getInstance(MasterAwareService.class, node_1);
@@ -583,7 +579,7 @@ public class ClusterServiceIT extends ESIntegTestCase {
public static class TestPlugin extends Plugin {
@Override
- public Collection> nodeServices() {
+ public Collection> getGuiceServiceClasses() {
List> services = new ArrayList<>(1);
services.add(MasterAwareService.class);
return services;
@@ -591,7 +587,7 @@ public class ClusterServiceIT extends ESIntegTestCase {
}
@Singleton
- public static class MasterAwareService extends AbstractLifecycleComponent implements LocalNodeMasterListener {
+ public static class MasterAwareService extends AbstractLifecycleComponent implements LocalNodeMasterListener {
private final ClusterService clusterService;
private volatile boolean master;
diff --git a/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceTests.java b/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceTests.java
index 66f96f8cd3a..1002774d2ca 100644
--- a/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/service/ClusterServiceTests.java
@@ -37,7 +37,7 @@ import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.lease.Releasable;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.MockLogAppender;
@@ -69,10 +69,14 @@ import java.util.stream.Collectors;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static org.elasticsearch.test.ClusterServiceUtils.setState;
+import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.anyOf;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
+import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.is;
public class ClusterServiceTests extends ESTestCase {
@@ -109,7 +113,7 @@ public class ClusterServiceTests extends ESTestCase {
TimedClusterService timedClusterService = new TimedClusterService(Settings.builder().put("cluster.name",
"ClusterServiceTests").build(), new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS),
threadPool);
- timedClusterService.setLocalNode(new DiscoveryNode("node1", DummyTransportAddress.INSTANCE, emptyMap(),
+ timedClusterService.setLocalNode(new DiscoveryNode("node1", LocalTransportAddress.buildUnique(), emptyMap(),
emptySet(), Version.CURRENT));
timedClusterService.setNodeConnectionsService(new NodeConnectionsService(Settings.EMPTY, null, null) {
@Override
@@ -149,8 +153,8 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
- throw new RuntimeException(t);
+ public void onFailure(String source, Exception e) {
+ throw new RuntimeException(e);
}
});
@@ -163,7 +167,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
timedOut.countDown();
}
@@ -183,8 +187,8 @@ public class ClusterServiceTests extends ESTestCase {
final CountDownLatch allProcessed = new CountDownLatch(1);
clusterService.submitStateUpdateTask("test3", new ClusterStateUpdateTask() {
@Override
- public void onFailure(String source, Throwable t) {
- throw new RuntimeException(t);
+ public void onFailure(String source, Exception e) {
+ throw new RuntimeException(e);
}
@Override
@@ -212,7 +216,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
taskFailed[0] = true;
latch1.countDown();
}
@@ -237,7 +241,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
taskFailed[0] = true;
latch2.countDown();
}
@@ -286,7 +290,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
}
}
);
@@ -326,9 +330,9 @@ public class ClusterServiceTests extends ESTestCase {
ClusterStateTaskListener listener = new ClusterStateTaskListener() {
@Override
- public void onFailure(String source, Throwable t) {
- logger.error("unexpected failure: [{}]", t, source);
- failures.add(new Tuple<>(source, t));
+ public void onFailure(String source, Exception e) {
+ logger.error("unexpected failure: [{}]", e, source);
+ failures.add(new Tuple<>(source, e));
updateLatch.countDown();
}
@@ -387,8 +391,8 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
- fail(ExceptionsHelper.detailedMessage(t));
+ public void onFailure(String source, Exception e) {
+ fail(ExceptionsHelper.detailedMessage(e));
}
})) ;
}
@@ -523,8 +527,8 @@ public class ClusterServiceTests extends ESTestCase {
final CountDownLatch updateLatch = new CountDownLatch(totalTaskCount);
final ClusterStateTaskListener listener = new ClusterStateTaskListener() {
@Override
- public void onFailure(String source, Throwable t) {
- fail(ExceptionsHelper.detailedMessage(t));
+ public void onFailure(String source, Exception e) {
+ fail(ExceptionsHelper.detailedMessage(e));
}
@Override
@@ -608,13 +612,12 @@ public class ClusterServiceTests extends ESTestCase {
BlockingTask block = new BlockingTask(Priority.IMMEDIATE);
clusterService.submitStateUpdateTask("test", block);
int taskCount = randomIntBetween(5, 20);
- Priority[] priorities = Priority.values();
// will hold all the tasks in the order in which they were executed
List tasks = new ArrayList<>(taskCount);
CountDownLatch latch = new CountDownLatch(taskCount);
for (int i = 0; i < taskCount; i++) {
- Priority priority = priorities[randomIntBetween(0, priorities.length - 1)];
+ Priority priority = randomFrom(Priority.values());
clusterService.submitStateUpdateTask("test", new PrioritizedTask(priority, latch, tasks));
}
@@ -647,15 +650,22 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
- fail(ExceptionsHelper.detailedMessage(t));
+ public void onFailure(String source, Exception e) {
+ fail(ExceptionsHelper.detailedMessage(e));
}
};
clusterService.submitStateUpdateTask("first time", task, ClusterStateTaskConfig.build(Priority.NORMAL), executor, listener);
- expectThrows(IllegalArgumentException.class, () -> clusterService.submitStateUpdateTask("second time", task,
- ClusterStateTaskConfig.build(Priority.NORMAL), executor, listener));
+ final IllegalStateException e =
+ expectThrows(
+ IllegalStateException.class,
+ () -> clusterService.submitStateUpdateTask(
+ "second time",
+ task,
+ ClusterStateTaskConfig.build(Priority.NORMAL),
+ executor, listener));
+ assertThat(e, hasToString(containsString("task [1] with source [second time] is already queued")));
clusterService.submitStateUpdateTask("third time a charm", new SimpleTask(1),
ClusterStateTaskConfig.build(Priority.NORMAL), executor, listener);
@@ -693,7 +703,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
fail();
}
});
@@ -710,7 +720,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
latch.countDown();
}
});
@@ -727,7 +737,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
fail();
}
});
@@ -745,7 +755,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
fail();
}
});
@@ -788,7 +798,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
fail();
}
});
@@ -807,7 +817,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
latch.countDown();
}
});
@@ -824,7 +834,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
fail();
}
});
@@ -841,7 +851,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
fail();
}
});
@@ -859,7 +869,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
fail();
}
});
@@ -886,6 +896,11 @@ public class ClusterServiceTests extends ESTestCase {
public boolean equals(Object obj) {
return super.equals(obj);
}
+
+ @Override
+ public String toString() {
+ return Integer.toString(id);
+ }
}
private static class BlockingTask extends ClusterStateUpdateTask implements Releasable {
@@ -902,7 +917,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
}
public void close() {
@@ -930,7 +945,7 @@ public class ClusterServiceTests extends ESTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
+ public void onFailure(String source, Exception e) {
latch.countDown();
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/BooleansTests.java b/core/src/test/java/org/elasticsearch/common/BooleansTests.java
index 6e5446cebf9..176c4c75dc7 100644
--- a/core/src/test/java/org/elasticsearch/common/BooleansTests.java
+++ b/core/src/test/java/org/elasticsearch/common/BooleansTests.java
@@ -51,9 +51,9 @@ public class BooleansTests extends ESTestCase {
assertThat(Booleans.parseBoolean(null, false), is(false));
assertThat(Booleans.parseBoolean(null, true), is(true));
- assertThat(Booleans.parseBoolean(randomFrom("true", "on", "yes", "1"), randomFrom(null, Boolean.TRUE, Boolean.FALSE)), is(true));
- assertThat(Booleans.parseBoolean(randomFrom("false", "off", "no", "0"), randomFrom(null, Boolean.TRUE, Boolean.FALSE)), is(false));
- assertThat(Booleans.parseBoolean(randomFrom("true", "on", "yes").toUpperCase(Locale.ROOT),randomFrom(null, Boolean.TRUE, Boolean.FALSE)), is(true));
+ assertThat(Booleans.parseBoolean(randomFrom("true", "on", "yes", "1"), randomFrom(Boolean.TRUE, Boolean.FALSE, null)), is(true));
+ assertThat(Booleans.parseBoolean(randomFrom("false", "off", "no", "0"), randomFrom(Boolean.TRUE, Boolean.FALSE, null)), is(false));
+ assertThat(Booleans.parseBoolean(randomFrom("true", "on", "yes").toUpperCase(Locale.ROOT),randomFrom(Boolean.TRUE, Boolean.FALSE, null)), is(true));
assertThat(Booleans.parseBoolean(null, Boolean.FALSE), is(false));
assertThat(Booleans.parseBoolean(null, Boolean.TRUE), is(true));
assertThat(Booleans.parseBoolean(null, null), nullValue());
@@ -70,7 +70,7 @@ public class BooleansTests extends ESTestCase {
assertThat(Booleans.parseBooleanExact(randomFrom("true", "on", "yes", "1")), is(true));
assertThat(Booleans.parseBooleanExact(randomFrom("false", "off", "no", "0")), is(false));
try {
- Booleans.parseBooleanExact(randomFrom(null, "fred", "foo", "barney"));
+ Booleans.parseBooleanExact(randomFrom("fred", "foo", "barney", null));
fail("Expected exception while parsing invalid boolean value ");
} catch (Exception ex) {
assertTrue(ex instanceof IllegalArgumentException);
diff --git a/core/src/test/java/org/elasticsearch/common/ChannelsTests.java b/core/src/test/java/org/elasticsearch/common/ChannelsTests.java
index 4f2bad36d4a..c0cb3482b0e 100644
--- a/core/src/test/java/org/elasticsearch/common/ChannelsTests.java
+++ b/core/src/test/java/org/elasticsearch/common/ChannelsTests.java
@@ -19,14 +19,11 @@
package org.elasticsearch.common;
-import org.elasticsearch.common.bytes.ByteBufferBytesReference;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.Channels;
import org.elasticsearch.test.ESTestCase;
import org.hamcrest.Matchers;
-import org.jboss.netty.buffer.ByteBufferBackedChannelBuffer;
-import org.jboss.netty.buffer.ChannelBuffer;
import org.junit.After;
import org.junit.Before;
@@ -85,7 +82,7 @@ public class ChannelsTests extends ESTestCase {
BytesReference source = new BytesArray(randomBytes, offset + offsetToRead, lengthToRead);
BytesReference read = new BytesArray(readBytes, offset + offsetToRead, lengthToRead);
- assertThat("read bytes didn't match written bytes", source.toBytes(), Matchers.equalTo(read.toBytes()));
+ assertThat("read bytes didn't match written bytes", BytesReference.toBytes(source), Matchers.equalTo(BytesReference.toBytes(read)));
}
public void testBufferReadPastEOFWithException() throws Exception {
@@ -157,7 +154,9 @@ public class ChannelsTests extends ESTestCase {
copy.flip();
BytesReference sourceRef = new BytesArray(randomBytes, offset + offsetToRead, lengthToRead);
- BytesReference copyRef = new ByteBufferBytesReference(copy);
+ byte[] tmp = new byte[copy.remaining()];
+ copy.duplicate().get(tmp);
+ BytesReference copyRef = new BytesArray(tmp);
assertTrue("read bytes didn't match written bytes", sourceRef.equals(copyRef));
}
diff --git a/core/src/test/java/org/elasticsearch/common/PriorityTests.java b/core/src/test/java/org/elasticsearch/common/PriorityTests.java
new file mode 100644
index 00000000000..06bbab6bf58
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/common/PriorityTests.java
@@ -0,0 +1,97 @@
+/*
+ * 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 org.elasticsearch.common.io.stream.BytesStreamOutput;
+import org.elasticsearch.test.ESTestCase;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+public class PriorityTests extends ESTestCase {
+
+ public void testValueOf() {
+ for (Priority p : Priority.values()) {
+ assertSame(p, Priority.valueOf(p.toString()));
+ }
+
+ IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> {
+ Priority.valueOf("foobar");
+ });
+ assertEquals("No enum constant org.elasticsearch.common.Priority.foobar", exception.getMessage());
+ }
+
+ public void testToString() {
+ assertEquals("IMMEDIATE", Priority.IMMEDIATE.toString());
+ assertEquals("HIGH", Priority.HIGH.toString());
+ assertEquals("LANGUID", Priority.LANGUID.toString());
+ assertEquals("LOW", Priority.LOW.toString());
+ assertEquals("URGENT", Priority.URGENT.toString());
+ assertEquals("NORMAL", Priority.NORMAL.toString());
+ assertEquals(6, Priority.values().length);
+ }
+
+ public void testSerialization() throws IOException {
+ for (Priority p : Priority.values()) {
+ BytesStreamOutput out = new BytesStreamOutput();
+ Priority.writeTo(p, out);
+ Priority priority = Priority.readFrom(out.bytes().streamInput());
+ assertSame(p, priority);
+ }
+ assertSame(Priority.IMMEDIATE, Priority.fromByte((byte) 0));
+ assertSame(Priority.HIGH, Priority.fromByte((byte) 2));
+ assertSame(Priority.LANGUID, Priority.fromByte((byte) 5));
+ assertSame(Priority.LOW, Priority.fromByte((byte) 4));
+ assertSame(Priority.NORMAL, Priority.fromByte((byte) 3));
+ assertSame(Priority.URGENT,Priority.fromByte((byte) 1));
+ assertEquals(6, Priority.values().length);
+ }
+
+ public void testCompareTo() {
+ assertTrue(Priority.IMMEDIATE.compareTo(Priority.URGENT) < 0);
+ assertTrue(Priority.URGENT.compareTo(Priority.HIGH) < 0);
+ assertTrue(Priority.HIGH.compareTo(Priority.NORMAL) < 0);
+ assertTrue(Priority.NORMAL.compareTo(Priority.LOW) < 0);
+ assertTrue(Priority.LOW.compareTo(Priority.LANGUID) < 0);
+
+ assertTrue(Priority.URGENT.compareTo(Priority.IMMEDIATE) > 0);
+ assertTrue(Priority.HIGH.compareTo(Priority.URGENT) > 0);
+ assertTrue(Priority.NORMAL.compareTo(Priority.HIGH) > 0);
+ assertTrue(Priority.LOW.compareTo(Priority.NORMAL) > 0);
+ assertTrue(Priority.LANGUID.compareTo(Priority.LOW) > 0);
+
+ for (Priority p : Priority.values()) {
+ assertEquals(0, p.compareTo(p));
+ }
+ List shuffeledAndSorted = Arrays.asList(Priority.values());
+ Collections.shuffle(shuffeledAndSorted, random());
+ Collections.sort(shuffeledAndSorted);
+ for (List priorities : Arrays.asList(shuffeledAndSorted,
+ Arrays.asList(Priority.values()))) { // #values() guarantees order!
+ assertSame(Priority.IMMEDIATE, priorities.get(0));
+ assertSame(Priority.URGENT, priorities.get(1));
+ assertSame(Priority.HIGH, priorities.get(2));
+ assertSame(Priority.NORMAL, priorities.get(3));
+ assertSame(Priority.LOW, priorities.get(4));
+ assertSame(Priority.LANGUID, priorities.get(5));
+ }
+ }
+}
diff --git a/core/src/test/java/org/elasticsearch/common/breaker/MemoryCircuitBreakerTests.java b/core/src/test/java/org/elasticsearch/common/breaker/MemoryCircuitBreakerTests.java
index bb9d23db1cb..f10a0da3029 100644
--- a/core/src/test/java/org/elasticsearch/common/breaker/MemoryCircuitBreakerTests.java
+++ b/core/src/test/java/org/elasticsearch/common/breaker/MemoryCircuitBreakerTests.java
@@ -43,7 +43,7 @@ public class MemoryCircuitBreakerTests extends ESTestCase {
final int BYTES_PER_THREAD = scaledRandomIntBetween(500, 4500);
final Thread[] threads = new Thread[NUM_THREADS];
final AtomicBoolean tripped = new AtomicBoolean(false);
- final AtomicReference lastException = new AtomicReference<>(null);
+ final AtomicReference lastException = new AtomicReference<>(null);
final MemoryCircuitBreaker breaker = new MemoryCircuitBreaker(new ByteSizeValue((BYTES_PER_THREAD * NUM_THREADS) - 1), 1.0, logger);
@@ -60,8 +60,8 @@ public class MemoryCircuitBreakerTests extends ESTestCase {
} else {
assertThat(tripped.compareAndSet(false, true), equalTo(true));
}
- } catch (Throwable e2) {
- lastException.set(e2);
+ } catch (Exception e) {
+ lastException.set(e);
}
}
}
@@ -117,8 +117,8 @@ public class MemoryCircuitBreakerTests extends ESTestCase {
} else {
assertThat(tripped.compareAndSet(false, true), equalTo(true));
}
- } catch (Throwable e2) {
- lastException.set(e2);
+ } catch (Exception e) {
+ lastException.set(e);
}
}
}
@@ -178,8 +178,8 @@ public class MemoryCircuitBreakerTests extends ESTestCase {
breaker.addEstimateBytesAndMaybeBreak(1L, "test");
} catch (CircuitBreakingException e) {
tripped.incrementAndGet();
- } catch (Throwable e2) {
- lastException.set(e2);
+ } catch (Exception e) {
+ lastException.set(e);
}
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/bytes/BytesArrayTests.java b/core/src/test/java/org/elasticsearch/common/bytes/BytesArrayTests.java
index 61d24ef44c3..fff030200b7 100644
--- a/core/src/test/java/org/elasticsearch/common/bytes/BytesArrayTests.java
+++ b/core/src/test/java/org/elasticsearch/common/bytes/BytesArrayTests.java
@@ -32,10 +32,28 @@ public class BytesArrayTests extends AbstractBytesReferenceTestCase {
out.writeByte((byte) random().nextInt(1 << 8));
}
assertEquals(length, out.size());
- BytesArray ref = out.bytes().toBytesArray();
+ BytesArray ref = new BytesArray(out.bytes().toBytesRef());
assertEquals(length, ref.length());
assertTrue(ref instanceof BytesArray);
assertThat(ref.length(), Matchers.equalTo(length));
return ref;
}
+
+ public void testArray() throws IOException {
+ int[] sizes = {0, randomInt(PAGE_SIZE), PAGE_SIZE, randomIntBetween(2, PAGE_SIZE * randomIntBetween(2, 5))};
+
+ for (int i = 0; i < sizes.length; i++) {
+ BytesArray pbr = (BytesArray) newBytesReference(sizes[i]);
+ byte[] array = pbr.array();
+ assertNotNull(array);
+ assertEquals(sizes[i], array.length);
+ assertSame(array, pbr.array());
+ }
+ }
+
+ public void testArrayOffset() throws IOException {
+ int length = randomInt(PAGE_SIZE * randomIntBetween(2, 5));
+ BytesArray pbr = (BytesArray) newBytesReference(length);
+ assertEquals(0, pbr.offset());
+ }
}
diff --git a/core/src/test/java/org/elasticsearch/common/bytes/BytesReferenceTests.java b/core/src/test/java/org/elasticsearch/common/bytes/BytesReferenceTests.java
deleted file mode 100644
index 60f4983dd19..00000000000
--- a/core/src/test/java/org/elasticsearch/common/bytes/BytesReferenceTests.java
+++ /dev/null
@@ -1,61 +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.bytes;
-
-
-import org.elasticsearch.test.ESTestCase;
-
-import java.util.Arrays;
-
-public class BytesReferenceTests extends ESTestCase {
-
- public void testEquals() {
- final int len = randomIntBetween(0, randomBoolean() ? 10: 100000);
- final int offset1 = randomInt(5);
- final byte[] array1 = new byte[offset1 + len + randomInt(5)];
- random().nextBytes(array1);
- final int offset2 = randomInt(offset1);
- final byte[] array2 = Arrays.copyOfRange(array1, offset1 - offset2, array1.length);
-
- final BytesArray b1 = new BytesArray(array1, offset1, len);
- final BytesArray b2 = new BytesArray(array2, offset2, len);
- assertTrue(BytesReference.Helper.bytesEqual(b1, b2));
- assertTrue(BytesReference.Helper.bytesEquals(b1, b2));
- assertEquals(Arrays.hashCode(b1.toBytes()), b1.hashCode());
- assertEquals(BytesReference.Helper.bytesHashCode(b1), BytesReference.Helper.slowHashCode(b2));
-
- // test same instance
- assertTrue(BytesReference.Helper.bytesEqual(b1, b1));
- assertTrue(BytesReference.Helper.bytesEquals(b1, b1));
- assertEquals(BytesReference.Helper.bytesHashCode(b1), BytesReference.Helper.slowHashCode(b1));
-
- if (len > 0) {
- // test different length
- BytesArray differentLen = new BytesArray(array1, offset1, randomInt(len - 1));
- assertFalse(BytesReference.Helper.bytesEqual(b1, differentLen));
-
- // test changed bytes
- array1[offset1 + randomInt(len - 1)] += 13;
- assertFalse(BytesReference.Helper.bytesEqual(b1, b2));
- assertFalse(BytesReference.Helper.bytesEquals(b1, b2));
- }
- }
-
-}
diff --git a/core/src/test/java/org/elasticsearch/common/bytes/CompositeBytesReferenceTests.java b/core/src/test/java/org/elasticsearch/common/bytes/CompositeBytesReferenceTests.java
new file mode 100644
index 00000000000..aec957aba68
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/common/bytes/CompositeBytesReferenceTests.java
@@ -0,0 +1,110 @@
+/*
+ * 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.bytes;
+
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
+import org.apache.lucene.util.BytesRefIterator;
+import org.elasticsearch.common.io.stream.BytesStreamOutput;
+import org.elasticsearch.common.io.stream.ReleasableBytesStreamOutput;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+public class CompositeBytesReferenceTests extends AbstractBytesReferenceTestCase {
+ @Override
+ protected BytesReference newBytesReference(int length) throws IOException {
+ // we know bytes stream output always creates a paged bytes reference, we use it to create randomized content
+ List referenceList = newRefList(length);
+ BytesReference ref = new CompositeBytesReference(referenceList.toArray(new BytesReference[0]));
+ assertEquals(length, ref.length());
+ return ref;
+ }
+
+ private List newRefList(int length) throws IOException {
+ List referenceList = new ArrayList<>();
+ for (int i = 0; i < length;) {
+ int remaining = length-i;
+ int sliceLength = randomIntBetween(1, remaining);
+ ReleasableBytesStreamOutput out = new ReleasableBytesStreamOutput(sliceLength, bigarrays);
+ for (int j = 0; j < sliceLength; j++) {
+ out.writeByte((byte) random().nextInt(1 << 8));
+ }
+ assertEquals(sliceLength, out.size());
+ referenceList.add(out.bytes());
+ i+=sliceLength;
+ }
+ return referenceList;
+ }
+
+ public void testCompositeBuffer() throws IOException {
+ List referenceList = newRefList(randomIntBetween(1, PAGE_SIZE * 2));
+ BytesReference ref = new CompositeBytesReference(referenceList.toArray(new BytesReference[0]));
+ BytesRefIterator iterator = ref.iterator();
+ BytesRefBuilder builder = new BytesRefBuilder();
+
+ for (BytesReference reference : referenceList) {
+ BytesRefIterator innerIter = reference.iterator(); // sometimes we have a paged ref - pull an iter and walk all pages!
+ BytesRef scratch;
+ while ((scratch = innerIter.next()) != null) {
+ BytesRef next = iterator.next();
+ assertNotNull(next);
+ assertEquals(next, scratch);
+ builder.append(next);
+ }
+
+ }
+ assertNull(iterator.next());
+
+ int offset = 0;
+ for (BytesReference reference : referenceList) {
+ assertEquals(reference, ref.slice(offset, reference.length()));
+ int probes = randomIntBetween(Math.min(10, reference.length()), reference.length());
+ for (int i = 0; i < probes; i++) {
+ int index = randomIntBetween(0, reference.length()-1);
+ assertEquals(ref.get(offset + index), reference.get(index));
+ }
+ offset += reference.length();
+ }
+
+ BytesArray array = new BytesArray(builder.toBytesRef());
+ assertEquals(array, ref);
+ assertEquals(array.hashCode(), ref.hashCode());
+
+ BytesStreamOutput output = new BytesStreamOutput();
+ ref.writeTo(output);
+ assertEquals(array, output.bytes());
+ }
+
+ @Override
+ public void testToBytesRefSharedPage() throws IOException {
+ // CompositeBytesReference doesn't share pages
+ }
+
+ @Override
+ public void testSliceArrayOffset() throws IOException {
+ // the assertions in this test only work on no-composite buffers
+ }
+
+ @Override
+ public void testSliceToBytesRef() throws IOException {
+ // CompositeBytesReference shifts offsets
+ }
+}
diff --git a/core/src/test/java/org/elasticsearch/common/bytes/PagedBytesReferenceTests.java b/core/src/test/java/org/elasticsearch/common/bytes/PagedBytesReferenceTests.java
index 5a299d82de8..6ae2b3cf943 100644
--- a/core/src/test/java/org/elasticsearch/common/bytes/PagedBytesReferenceTests.java
+++ b/core/src/test/java/org/elasticsearch/common/bytes/PagedBytesReferenceTests.java
@@ -50,15 +50,15 @@ public class PagedBytesReferenceTests extends AbstractBytesReferenceTestCase {
return ref;
}
- public void testToBytesArrayMaterializedPages() throws IOException {
+ public void testToBytesRefMaterializedPages() throws IOException {
// we need a length != (n * pagesize) to avoid page sharing at boundaries
int length = 0;
while ((length % PAGE_SIZE) == 0) {
length = randomIntBetween(PAGE_SIZE, PAGE_SIZE * randomIntBetween(2, 5));
}
BytesReference pbr = newBytesReference(length);
- BytesArray ba = pbr.toBytesArray();
- BytesArray ba2 = pbr.toBytesArray();
+ BytesArray ba = new BytesArray(pbr.toBytesRef());
+ BytesArray ba2 = new BytesArray(pbr.toBytesRef());
assertNotNull(ba);
assertNotNull(ba2);
assertEquals(pbr.length(), ba.length());
@@ -67,23 +67,23 @@ public class PagedBytesReferenceTests extends AbstractBytesReferenceTestCase {
assertNotSame(ba.array(), ba2.array());
}
- public void testArray() throws IOException {
+ public void testSinglePage() throws IOException {
int[] sizes = {0, randomInt(PAGE_SIZE), PAGE_SIZE, randomIntBetween(2, PAGE_SIZE * randomIntBetween(2, 5))};
for (int i = 0; i < sizes.length; i++) {
BytesReference pbr = newBytesReference(sizes[i]);
// verify that array() is cheap for small payloads
if (sizes[i] <= PAGE_SIZE) {
- byte[] array = pbr.array();
+ BytesRef page = getSinglePageOrNull(pbr);
+ assertNotNull(page);
+ byte[] array = page.bytes;
assertNotNull(array);
assertEquals(sizes[i], array.length);
- assertSame(array, pbr.array());
+ assertSame(array, page.bytes);
} else {
- try {
- pbr.array();
- fail("expected IllegalStateException");
- } catch (IllegalStateException isx) {
- // expected
+ BytesRef page = getSinglePageOrNull(pbr);
+ if (pbr.length() > 0) {
+ assertNull(page);
}
}
}
@@ -94,22 +94,42 @@ public class PagedBytesReferenceTests extends AbstractBytesReferenceTestCase {
for (int i = 0; i < sizes.length; i++) {
BytesReference pbr = newBytesReference(sizes[i]);
- byte[] bytes = pbr.toBytes();
+ byte[] bytes = BytesReference.toBytes(pbr);
assertEquals(sizes[i], bytes.length);
// verify that toBytes() is cheap for small payloads
if (sizes[i] <= PAGE_SIZE) {
- assertSame(bytes, pbr.toBytes());
+ assertSame(bytes, BytesReference.toBytes(pbr));
} else {
- assertNotSame(bytes, pbr.toBytes());
+ assertNotSame(bytes, BytesReference.toBytes(pbr));
}
}
}
- public void testHasArray() throws IOException {
+ public void testHasSinglePage() throws IOException {
int length = randomIntBetween(10, PAGE_SIZE * randomIntBetween(1, 3));
BytesReference pbr = newBytesReference(length);
// must return true for <= pagesize
- assertEquals(length <= PAGE_SIZE, pbr.hasArray());
+ assertEquals(length <= PAGE_SIZE, getNumPages(pbr) == 1);
+ }
+
+ public void testEquals() {
+ int length = randomIntBetween(100, PAGE_SIZE * randomIntBetween(2, 5));
+ ByteArray ba1 = bigarrays.newByteArray(length, false);
+ ByteArray ba2 = bigarrays.newByteArray(length, false);
+
+ // copy contents
+ for (long i = 0; i < length; i++) {
+ ba2.set(i, ba1.get(i));
+ }
+
+ // get refs & compare
+ BytesReference pbr = new PagedBytesReference(bigarrays, ba1, length);
+ BytesReference pbr2 = new PagedBytesReference(bigarrays, ba2, length);
+ assertEquals(pbr, pbr2);
+ int offsetToFlip = randomIntBetween(0, length - 1);
+ int value = ~Byte.toUnsignedInt(ba1.get(offsetToFlip));
+ ba2.set(offsetToFlip, (byte)value);
+ assertNotEquals(pbr, pbr2);
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java b/core/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java
index 72866d082ae..0ce95077965 100644
--- a/core/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java
+++ b/core/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java
@@ -91,8 +91,8 @@ public class DeflateCompressedXContentTests extends ESTestCase {
// of different size are being used
assertFalse(b1.equals(b2));
// we used the compressed representation directly and did not recompress
- assertArrayEquals(b1.toBytes(), new CompressedXContent(b1).compressed());
- assertArrayEquals(b2.toBytes(), new CompressedXContent(b2).compressed());
+ assertArrayEquals(BytesReference.toBytes(b1), new CompressedXContent(b1).compressed());
+ assertArrayEquals(BytesReference.toBytes(b2), new CompressedXContent(b2).compressed());
// but compressedstring instances are still equal
assertEquals(new CompressedXContent(b1), new CompressedXContent(b2));
}
diff --git a/core/src/test/java/org/elasticsearch/common/geo/GeoDistanceTests.java b/core/src/test/java/org/elasticsearch/common/geo/GeoDistanceTests.java
index 407c9790dbe..416299f8e7e 100644
--- a/core/src/test/java/org/elasticsearch/common/geo/GeoDistanceTests.java
+++ b/core/src/test/java/org/elasticsearch/common/geo/GeoDistanceTests.java
@@ -46,7 +46,7 @@ public class GeoDistanceTests extends ESTestCase {
GeoDistance geoDistance = randomFrom(GeoDistance.PLANE, GeoDistance.FACTOR, GeoDistance.ARC, GeoDistance.SLOPPY_ARC);
try (BytesStreamOutput out = new BytesStreamOutput()) {
geoDistance.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {;
+ try (StreamInput in = out.bytes().streamInput()) {;
GeoDistance copy = GeoDistance.readFromStream(in);
assertEquals(copy.toString() + " vs. " + geoDistance.toString(), copy, geoDistance);
}
@@ -60,7 +60,7 @@ public class GeoDistanceTests extends ESTestCase {
} else {
out.writeVInt(randomIntBetween(Integer.MIN_VALUE, -1));
}
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
GeoDistance.readFromStream(in);
} catch (IOException e) {
assertThat(e.getMessage(), containsString("Unknown GeoDistance ordinal ["));
diff --git a/core/src/test/java/org/elasticsearch/common/geo/GeoHashTests.java b/core/src/test/java/org/elasticsearch/common/geo/GeoHashTests.java
index 413062e4a2d..d2ae8401c55 100644
--- a/core/src/test/java/org/elasticsearch/common/geo/GeoHashTests.java
+++ b/core/src/test/java/org/elasticsearch/common/geo/GeoHashTests.java
@@ -18,6 +18,7 @@
*/
package org.elasticsearch.common.geo;
+import org.apache.lucene.geo.Rectangle;
import org.elasticsearch.test.ESTestCase;
/**
@@ -57,4 +58,16 @@ public class GeoHashTests extends ESTestCase {
}
}
}
+
+ public void testBboxFromHash() {
+ String hash = randomGeohash(1, 12);
+ int level = hash.length();
+ Rectangle bbox = GeoHashUtils.bbox(hash);
+ // check that the length is as expected
+ double expectedLonDiff = 360.0 / (Math.pow(8.0, (level + 1) / 2) * Math.pow(4.0, level / 2));
+ double expectedLatDiff = 180.0 / (Math.pow(4.0, (level + 1) / 2) * Math.pow(8.0, level / 2));
+ assertEquals(expectedLonDiff, bbox.maxLon - bbox.minLon, 0.00001);
+ assertEquals(expectedLatDiff, bbox.maxLat - bbox.minLat, 0.00001);
+ assertEquals(hash, GeoHashUtils.stringEncode(bbox.minLon, bbox.minLat, level));
+ }
}
diff --git a/core/src/test/java/org/elasticsearch/common/geo/GeoJSONShapeParserTests.java b/core/src/test/java/org/elasticsearch/common/geo/GeoJSONShapeParserTests.java
index 566d2148cae..76376a4d30d 100644
--- a/core/src/test/java/org/elasticsearch/common/geo/GeoJSONShapeParserTests.java
+++ b/core/src/test/java/org/elasticsearch/common/geo/GeoJSONShapeParserTests.java
@@ -56,7 +56,7 @@ import static org.elasticsearch.common.geo.builders.ShapeBuilder.SPATIAL_CONTEXT
*/
public class GeoJSONShapeParserTests extends ESTestCase {
- private final static GeometryFactory GEOMETRY_FACTORY = SPATIAL_CONTEXT.getGeometryFactory();
+ private static final GeometryFactory GEOMETRY_FACTORY = SPATIAL_CONTEXT.getGeometryFactory();
public void testParse_simplePoint() throws IOException {
String pointGeoJson = XContentFactory.jsonBuilder().startObject().field("type", "Point")
diff --git a/core/src/test/java/org/elasticsearch/common/geo/ShapeRelationTests.java b/core/src/test/java/org/elasticsearch/common/geo/ShapeRelationTests.java
index 6ee6a4fff83..e4eaa17874c 100644
--- a/core/src/test/java/org/elasticsearch/common/geo/ShapeRelationTests.java
+++ b/core/src/test/java/org/elasticsearch/common/geo/ShapeRelationTests.java
@@ -39,21 +39,21 @@ public class ShapeRelationTests extends ESTestCase {
public void testwriteTo() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
ShapeRelation.INTERSECTS.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(0));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
ShapeRelation.DISJOINT.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(1));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
ShapeRelation.WITHIN.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(2));
}
}
@@ -62,19 +62,19 @@ public class ShapeRelationTests extends ESTestCase {
public void testReadFrom() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(0);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(ShapeRelation.readFromStream(in), equalTo(ShapeRelation.INTERSECTS));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(1);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(ShapeRelation.readFromStream(in), equalTo(ShapeRelation.DISJOINT));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(2);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(ShapeRelation.readFromStream(in), equalTo(ShapeRelation.WITHIN));
}
}
@@ -83,7 +83,7 @@ public class ShapeRelationTests extends ESTestCase {
public void testInvalidReadFrom() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(randomIntBetween(3, Integer.MAX_VALUE));
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
ShapeRelation.readFromStream(in);
fail("Expected IOException");
} catch(IOException e) {
diff --git a/core/src/test/java/org/elasticsearch/common/geo/SpatialStrategyTests.java b/core/src/test/java/org/elasticsearch/common/geo/SpatialStrategyTests.java
index c2f29e6ecd7..b6eae97932f 100644
--- a/core/src/test/java/org/elasticsearch/common/geo/SpatialStrategyTests.java
+++ b/core/src/test/java/org/elasticsearch/common/geo/SpatialStrategyTests.java
@@ -38,14 +38,14 @@ public class SpatialStrategyTests extends ESTestCase {
public void testwriteTo() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
SpatialStrategy.TERM.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(0));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
SpatialStrategy.RECURSIVE.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(1));
}
}
@@ -54,13 +54,13 @@ public class SpatialStrategyTests extends ESTestCase {
public void testReadFrom() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(0);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(SpatialStrategy.readFromStream(in), equalTo(SpatialStrategy.TERM));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(1);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(SpatialStrategy.readFromStream(in), equalTo(SpatialStrategy.RECURSIVE));
}
}
@@ -69,7 +69,7 @@ public class SpatialStrategyTests extends ESTestCase {
public void testInvalidReadFrom() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(randomIntBetween(2, Integer.MAX_VALUE));
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
SpatialStrategy.readFromStream(in);
fail("Expected IOException");
} catch(IOException e) {
diff --git a/core/src/test/java/org/elasticsearch/common/geo/builders/AbstractShapeBuilderTestCase.java b/core/src/test/java/org/elasticsearch/common/geo/builders/AbstractShapeBuilderTestCase.java
index 9cbd4bb769d..4003a96e26f 100644
--- a/core/src/test/java/org/elasticsearch/common/geo/builders/AbstractShapeBuilderTestCase.java
+++ b/core/src/test/java/org/elasticsearch/common/geo/builders/AbstractShapeBuilderTestCase.java
@@ -137,7 +137,7 @@ public abstract class AbstractShapeBuilderTestCase exte
static ShapeBuilder copyShape(ShapeBuilder original) throws IOException {
try (BytesStreamOutput output = new BytesStreamOutput()) {
original.writeTo(output);
- try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) {
+ try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry)) {
return namedWriteableRegistry.getReader(ShapeBuilder.class, original.getWriteableName()).read(in);
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/io/StreamsTests.java b/core/src/test/java/org/elasticsearch/common/io/StreamsTests.java
index 5c6c1e1789b..76b52c08a85 100644
--- a/core/src/test/java/org/elasticsearch/common/io/StreamsTests.java
+++ b/core/src/test/java/org/elasticsearch/common/io/StreamsTests.java
@@ -84,7 +84,7 @@ public class StreamsTests extends ESTestCase {
byte stuff[] = new byte[] { 0, 1, 2, 3 };
BytesRef stuffRef = new BytesRef(stuff, 2, 2);
BytesArray stuffArray = new BytesArray(stuffRef);
- StreamInput input = StreamInput.wrap(stuffArray);
+ StreamInput input = stuffArray.streamInput();
assertEquals(2, input.read());
assertEquals(3, input.read());
assertEquals(-1, input.read());
diff --git a/core/src/test/java/org/elasticsearch/common/io/stream/AbstractWriteableEnumTestCase.java b/core/src/test/java/org/elasticsearch/common/io/stream/AbstractWriteableEnumTestCase.java
index a4d15173a7c..dc57b0c70d4 100644
--- a/core/src/test/java/org/elasticsearch/common/io/stream/AbstractWriteableEnumTestCase.java
+++ b/core/src/test/java/org/elasticsearch/common/io/stream/AbstractWriteableEnumTestCase.java
@@ -60,7 +60,7 @@ public abstract class AbstractWriteableEnumTestCase extends ESTestCase {
protected static void assertWriteToStream(final Writeable writeableEnum, final int ordinal) throws IOException {
try (BytesStreamOutput out = new BytesStreamOutput()) {
writeableEnum.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(ordinal));
}
}
@@ -70,7 +70,7 @@ public abstract class AbstractWriteableEnumTestCase extends ESTestCase {
protected void assertReadFromStream(final int ordinal, final Writeable expected) throws IOException {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(ordinal);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(reader.read(in), equalTo(expected));
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/io/stream/BytesStreamsTests.java b/core/src/test/java/org/elasticsearch/common/io/stream/BytesStreamsTests.java
index 9fcbb708156..dcd612198de 100644
--- a/core/src/test/java/org/elasticsearch/common/io/stream/BytesStreamsTests.java
+++ b/core/src/test/java/org/elasticsearch/common/io/stream/BytesStreamsTests.java
@@ -21,6 +21,7 @@ package org.elasticsearch.common.io.stream;
import org.apache.lucene.util.Constants;
import org.elasticsearch.common.bytes.BytesArray;
+import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.BytesRefs;
import org.elasticsearch.common.util.BigArrays;
@@ -29,7 +30,9 @@ import org.joda.time.DateTimeZone;
import java.io.IOException;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import java.util.Objects;
import static org.hamcrest.Matchers.closeTo;
@@ -48,7 +51,7 @@ public class BytesStreamsTests extends ESTestCase {
// test empty stream to array
assertEquals(0, out.size());
- assertEquals(0, out.bytes().toBytes().length);
+ assertEquals(0, out.bytes().length());
out.close();
}
@@ -63,7 +66,7 @@ public class BytesStreamsTests extends ESTestCase {
// write single byte
out.writeByte(expectedData[0]);
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -80,7 +83,7 @@ public class BytesStreamsTests extends ESTestCase {
}
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -108,14 +111,14 @@ public class BytesStreamsTests extends ESTestCase {
byte[] expectedData = randomizedByteArrayWithSize(expectedSize);
out.writeBytes(expectedData);
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
// bulk-write again with actual bytes
expectedSize = 10;
expectedData = randomizedByteArrayWithSize(expectedSize);
out.writeBytes(expectedData);
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -130,7 +133,7 @@ public class BytesStreamsTests extends ESTestCase {
out.writeBytes(expectedData);
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -149,7 +152,7 @@ public class BytesStreamsTests extends ESTestCase {
// now write the rest - more than fits into the remaining first page
out.writeBytes(expectedData, initialOffset, additionalLength);
assertEquals(expectedData.length, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -168,7 +171,7 @@ public class BytesStreamsTests extends ESTestCase {
// ie. we cross over into a third
out.writeBytes(expectedData, initialOffset, additionalLength);
assertEquals(expectedData.length, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -185,7 +188,7 @@ public class BytesStreamsTests extends ESTestCase {
}
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -202,7 +205,7 @@ public class BytesStreamsTests extends ESTestCase {
}
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -219,7 +222,7 @@ public class BytesStreamsTests extends ESTestCase {
}
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -235,7 +238,7 @@ public class BytesStreamsTests extends ESTestCase {
out.seek(position += BigArrays.BYTE_PAGE_SIZE + 10);
out.seek(position += BigArrays.BYTE_PAGE_SIZE * 2);
assertEquals(position, out.position());
- assertEquals(position, out.bytes().toBytes().length);
+ assertEquals(position, BytesReference.toBytes(out.bytes()).length);
out.close();
}
@@ -263,6 +266,7 @@ public class BytesStreamsTests extends ESTestCase {
out.writeVInt(2);
out.writeLong(-3);
out.writeVLong(4);
+ out.writeOptionalLong(11234234L);
out.writeFloat(1.1f);
out.writeDouble(2.2);
int[] intArray = {1, 2, 3};
@@ -288,16 +292,17 @@ public class BytesStreamsTests extends ESTestCase {
out.writeTimeZone(DateTimeZone.forID("CET"));
out.writeOptionalTimeZone(DateTimeZone.getDefault());
out.writeOptionalTimeZone(null);
- final byte[] bytes = out.bytes().toBytes();
- StreamInput in = StreamInput.wrap(out.bytes().toBytes());
+ final byte[] bytes = BytesReference.toBytes(out.bytes());
+ StreamInput in = StreamInput.wrap(BytesReference.toBytes(out.bytes()));
assertEquals(in.available(), bytes.length);
assertThat(in.readBoolean(), equalTo(false));
assertThat(in.readByte(), equalTo((byte)1));
assertThat(in.readShort(), equalTo((short)-1));
assertThat(in.readInt(), equalTo(-1));
assertThat(in.readVInt(), equalTo(2));
- assertThat(in.readLong(), equalTo((long)-3));
- assertThat(in.readVLong(), equalTo((long)4));
+ assertThat(in.readLong(), equalTo(-3L));
+ assertThat(in.readVLong(), equalTo(4L));
+ assertThat(in.readOptionalLong(), equalTo(11234234L));
assertThat((double)in.readFloat(), closeTo(1.1, 0.0001));
assertThat(in.readDouble(), closeTo(2.2, 0.0001));
assertThat(in.readGenericValue(), equalTo((Object) intArray));
@@ -328,12 +333,30 @@ public class BytesStreamsTests extends ESTestCase {
namedWriteableRegistry.register(BaseNamedWriteable.class, TestNamedWriteable.NAME, TestNamedWriteable::new);
TestNamedWriteable namedWriteableIn = new TestNamedWriteable(randomAsciiOfLengthBetween(1, 10), randomAsciiOfLengthBetween(1, 10));
out.writeNamedWriteable(namedWriteableIn);
- byte[] bytes = out.bytes().toBytes();
+ byte[] bytes = BytesReference.toBytes(out.bytes());
StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(bytes), namedWriteableRegistry);
assertEquals(in.available(), bytes.length);
BaseNamedWriteable namedWriteableOut = in.readNamedWriteable(BaseNamedWriteable.class);
- assertEquals(namedWriteableOut, namedWriteableIn);
- assertEquals(in.available(), 0);
+ assertEquals(namedWriteableIn, namedWriteableOut);
+ assertEquals(0, in.available());
+ }
+
+ public void testNamedWriteableList() throws IOException {
+ NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry();
+ namedWriteableRegistry.register(BaseNamedWriteable.class, TestNamedWriteable.NAME, TestNamedWriteable::new);
+ int size = between(0, 100);
+ List expected = new ArrayList<>(size);
+ for (int i = 0; i < size; i++) {
+ expected.add(new TestNamedWriteable(randomAsciiOfLengthBetween(1, 10), randomAsciiOfLengthBetween(1, 10)));
+ }
+
+ try (BytesStreamOutput out = new BytesStreamOutput()) {
+ out.writeNamedWriteableList(expected);
+ try (StreamInput in = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), namedWriteableRegistry)) {
+ assertEquals(expected, in.readNamedWriteableList(BaseNamedWriteable.class));
+ assertEquals(0, in.available());
+ }
+ }
}
public void testNamedWriteableDuplicates() throws IOException {
@@ -348,7 +371,7 @@ public class BytesStreamsTests extends ESTestCase {
public void testNamedWriteableUnknownCategory() throws IOException {
BytesStreamOutput out = new BytesStreamOutput();
out.writeNamedWriteable(new TestNamedWriteable("test1", "test2"));
- StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(out.bytes().toBytes()), new NamedWriteableRegistry());
+ StreamInput in = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), new NamedWriteableRegistry());
//no named writeable registered with given name, can write but cannot read it back
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> in.readNamedWriteable(BaseNamedWriteable.class));
assertThat(e.getMessage(), equalTo("unknown named writeable category [" + BaseNamedWriteable.class.getName() + "]"));
@@ -368,7 +391,7 @@ public class BytesStreamsTests extends ESTestCase {
public void writeTo(StreamOutput out) throws IOException {
}
});
- StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(out.bytes().toBytes()), namedWriteableRegistry);
+ StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(BytesReference.toBytes(out.bytes())), namedWriteableRegistry);
try {
//no named writeable registered with given name under test category, can write but cannot read it back
in.readNamedWriteable(BaseNamedWriteable.class);
@@ -382,7 +405,7 @@ public class BytesStreamsTests extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
TestNamedWriteable testNamedWriteable = new TestNamedWriteable("test1", "test2");
out.writeNamedWriteable(testNamedWriteable);
- StreamInput in = StreamInput.wrap(out.bytes().toBytes());
+ StreamInput in = StreamInput.wrap(BytesReference.toBytes(out.bytes()));
try {
in.readNamedWriteable(BaseNamedWriteable.class);
fail("Expected UnsupportedOperationException");
@@ -397,7 +420,7 @@ public class BytesStreamsTests extends ESTestCase {
namedWriteableRegistry.register(BaseNamedWriteable.class, TestNamedWriteable.NAME, (StreamInput in) -> null);
TestNamedWriteable namedWriteableIn = new TestNamedWriteable(randomAsciiOfLengthBetween(1, 10), randomAsciiOfLengthBetween(1, 10));
out.writeNamedWriteable(namedWriteableIn);
- byte[] bytes = out.bytes().toBytes();
+ byte[] bytes = BytesReference.toBytes(out.bytes());
StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(bytes), namedWriteableRegistry);
assertEquals(in.available(), bytes.length);
IOException e = expectThrows(IOException.class, () -> in.readNamedWriteable(BaseNamedWriteable.class));
@@ -407,7 +430,7 @@ public class BytesStreamsTests extends ESTestCase {
public void testOptionalWriteableReaderReturnsNull() throws IOException {
BytesStreamOutput out = new BytesStreamOutput();
out.writeOptionalWriteable(new TestNamedWriteable(randomAsciiOfLengthBetween(1, 10), randomAsciiOfLengthBetween(1, 10)));
- StreamInput in = StreamInput.wrap(out.bytes().toBytes());
+ StreamInput in = StreamInput.wrap(BytesReference.toBytes(out.bytes()));
IOException e = expectThrows(IOException.class, () -> in.readOptionalWriteable((StreamInput ignored) -> null));
assertThat(e.getMessage(), endsWith("] returned null which is not allowed and probably means it screwed up the stream."));
}
@@ -423,7 +446,7 @@ public class BytesStreamsTests extends ESTestCase {
});
TestNamedWriteable namedWriteableIn = new TestNamedWriteable(randomAsciiOfLengthBetween(1, 10), randomAsciiOfLengthBetween(1, 10));
out.writeNamedWriteable(namedWriteableIn);
- byte[] bytes = out.bytes().toBytes();
+ byte[] bytes = BytesReference.toBytes(out.bytes());
StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(bytes), namedWriteableRegistry);
assertEquals(in.available(), bytes.length);
AssertionError e = expectThrows(AssertionError.class, () -> in.readNamedWriteable(BaseNamedWriteable.class));
@@ -442,9 +465,9 @@ public class BytesStreamsTests extends ESTestCase {
final BytesStreamOutput out = new BytesStreamOutput();
out.writeStreamableList(expected);
- final StreamInput in = StreamInput.wrap(out.bytes().toBytes());
+ final StreamInput in = StreamInput.wrap(BytesReference.toBytes(out.bytes()));
- List loaded = in.readStreamableList(TestStreamable::new);
+ final List loaded = in.readStreamableList(TestStreamable::new);
assertThat(loaded, hasSize(expected.size()));
@@ -458,7 +481,49 @@ public class BytesStreamsTests extends ESTestCase {
out.close();
}
- private static abstract class BaseNamedWriteable implements NamedWriteable {
+ public void testWriteMapOfLists() throws IOException {
+ final int size = randomIntBetween(0, 5);
+ final Map> expected = new HashMap<>(size);
+
+ for (int i = 0; i < size; ++i) {
+ int listSize = randomIntBetween(0, 5);
+ List list = new ArrayList<>(listSize);
+
+ for (int j = 0; j < listSize; ++j) {
+ list.add(randomAsciiOfLength(5));
+ }
+
+ expected.put(randomAsciiOfLength(2), list);
+ }
+
+ final BytesStreamOutput out = new BytesStreamOutput();
+ out.writeMapOfLists(expected);
+
+ final StreamInput in = StreamInput.wrap(BytesReference.toBytes(out.bytes()));
+
+ final Map> loaded = in.readMapOfLists();
+
+ assertThat(loaded.size(), equalTo(expected.size()));
+
+ for (Map.Entry> entry : expected.entrySet()) {
+ assertThat(loaded.containsKey(entry.getKey()), equalTo(true));
+
+ List loadedList = loaded.get(entry.getKey());
+
+ assertThat(loadedList, hasSize(entry.getValue().size()));
+
+ for (int i = 0; i < loadedList.size(); ++i) {
+ assertEquals(entry.getValue().get(i), loadedList.get(i));
+ }
+ }
+
+ assertEquals(0, in.available());
+
+ in.close();
+ out.close();
+ }
+
+ private abstract static class BaseNamedWriteable implements NamedWriteable {
}
@@ -537,7 +602,7 @@ public class BytesStreamsTests extends ESTestCase {
// toByteArray() must fail
try {
- out.bytes().toBytes();
+ BytesReference.toBytes(out.bytes());
fail("expected IllegalStateException: stream closed");
}
catch (IllegalStateException iex1) {
@@ -558,7 +623,7 @@ public class BytesStreamsTests extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
GeoPoint geoPoint = new GeoPoint(randomDouble(), randomDouble());
out.writeGenericValue(geoPoint);
- StreamInput wrap = StreamInput.wrap(out.bytes());
+ StreamInput wrap = out.bytes().streamInput();
GeoPoint point = (GeoPoint) wrap.readGenericValue();
assertEquals(point, geoPoint);
}
@@ -566,7 +631,7 @@ public class BytesStreamsTests extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
GeoPoint geoPoint = new GeoPoint(randomDouble(), randomDouble());
out.writeGeoPoint(geoPoint);
- StreamInput wrap = StreamInput.wrap(out.bytes());
+ StreamInput wrap = out.bytes().streamInput();
GeoPoint point = wrap.readGeoPoint();
assertEquals(point, geoPoint);
}
diff --git a/core/src/test/java/org/elasticsearch/common/io/stream/StreamTests.java b/core/src/test/java/org/elasticsearch/common/io/stream/StreamTests.java
index aa6016774b0..06d39398c8e 100644
--- a/core/src/test/java/org/elasticsearch/common/io/stream/StreamTests.java
+++ b/core/src/test/java/org/elasticsearch/common/io/stream/StreamTests.java
@@ -19,13 +19,13 @@
package org.elasticsearch.common.io.stream;
-import org.elasticsearch.common.bytes.ByteBufferBytesReference;
+import org.elasticsearch.common.bytes.BytesArray;
+import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.test.ESTestCase;
import java.io.ByteArrayInputStream;
import java.io.IOException;
-import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -61,8 +61,8 @@ public class StreamTests extends ESTestCase {
for (Tuple value : values) {
BytesStreamOutput out = new BytesStreamOutput();
out.writeZLong(value.v1());
- assertArrayEquals(Long.toString(value.v1()), value.v2(), out.bytes().toBytes());
- ByteBufferBytesReference bytes = new ByteBufferBytesReference(ByteBuffer.wrap(value.v2()));
+ assertArrayEquals(Long.toString(value.v1()), value.v2(), BytesReference.toBytes(out.bytes()));
+ BytesReference bytes = new BytesArray(value.v2());
assertEquals(Arrays.toString(value.v2()), (long)value.v1(), bytes.streamInput().readZLong());
}
}
@@ -143,7 +143,7 @@ public class StreamTests extends ESTestCase {
assertThat(targetArray, equalTo(sourceArray));
}
- final static class WriteableString implements Writeable {
+ static final class WriteableString implements Writeable {
final String string;
public WriteableString(String string) {
diff --git a/core/src/test/java/org/elasticsearch/common/logging/DeprecationLoggerTests.java b/core/src/test/java/org/elasticsearch/common/logging/DeprecationLoggerTests.java
new file mode 100644
index 00000000000..f75e73ced2c
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/common/logging/DeprecationLoggerTests.java
@@ -0,0 +1,155 @@
+/*
+ * 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.logging;
+
+import org.elasticsearch.common.settings.Settings;
+import org.elasticsearch.common.util.concurrent.ThreadContext;
+import org.elasticsearch.test.ESTestCase;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.hasSize;
+
+/**
+ * Tests {@link DeprecationLogger}
+ */
+public class DeprecationLoggerTests extends ESTestCase {
+
+ private final DeprecationLogger logger = new DeprecationLogger(Loggers.getLogger(getClass()));
+
+ public void testAddsHeaderWithThreadContext() throws IOException {
+ String msg = "A simple message [{}]";
+ String param = randomAsciiOfLengthBetween(1, 5);
+ String formatted = LoggerMessageFormat.format(msg, (Object)param);
+
+ try (ThreadContext threadContext = new ThreadContext(Settings.EMPTY)) {
+ Set threadContexts = Collections.singleton(threadContext);
+
+ logger.deprecated(threadContexts, msg, param);
+
+ Map> responseHeaders = threadContext.getResponseHeaders();
+
+ assertEquals(1, responseHeaders.size());
+ assertEquals(formatted, responseHeaders.get(DeprecationLogger.DEPRECATION_HEADER).get(0));
+ }
+ }
+
+ public void testAddsCombinedHeaderWithThreadContext() throws IOException {
+ String msg = "A simple message [{}]";
+ String param = randomAsciiOfLengthBetween(1, 5);
+ String formatted = LoggerMessageFormat.format(msg, (Object)param);
+ String formatted2 = randomAsciiOfLengthBetween(1, 10);
+
+ try (ThreadContext threadContext = new ThreadContext(Settings.EMPTY)) {
+ Set threadContexts = Collections.singleton(threadContext);
+
+ logger.deprecated(threadContexts, msg, param);
+ logger.deprecated(threadContexts, formatted2);
+
+ Map> responseHeaders = threadContext.getResponseHeaders();
+
+ assertEquals(1, responseHeaders.size());
+
+ List responses = responseHeaders.get(DeprecationLogger.DEPRECATION_HEADER);
+
+ assertEquals(2, responses.size());
+ assertEquals(formatted, responses.get(0));
+ assertEquals(formatted2, responses.get(1));
+ }
+ }
+
+ public void testCanRemoveThreadContext() throws IOException {
+ final String expected = "testCanRemoveThreadContext";
+ final String unexpected = "testCannotRemoveThreadContext";
+
+ try (ThreadContext threadContext = new ThreadContext(Settings.EMPTY)) {
+ // NOTE: by adding it to the logger, we allow any concurrent test to write to it (from their own threads)
+ DeprecationLogger.setThreadContext(threadContext);
+
+ logger.deprecated(expected);
+
+ Map> responseHeaders = threadContext.getResponseHeaders();
+ List responses = responseHeaders.get(DeprecationLogger.DEPRECATION_HEADER);
+
+ // ensure it works (note: concurrent tests may be adding to it, but in different threads, so it should have no impact)
+ assertThat(responses, hasSize(atLeast(1)));
+ assertThat(responses, hasItem(equalTo(expected)));
+
+ DeprecationLogger.removeThreadContext(threadContext);
+
+ logger.deprecated(unexpected);
+
+ responseHeaders = threadContext.getResponseHeaders();
+ responses = responseHeaders.get(DeprecationLogger.DEPRECATION_HEADER);
+
+ assertThat(responses, hasSize(atLeast(1)));
+ assertThat(responses, hasItem(expected));
+ assertThat(responses, not(hasItem(unexpected)));
+ }
+ }
+
+ public void testIgnoresClosedThreadContext() throws IOException {
+ ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
+ Set threadContexts = new HashSet<>(1);
+
+ threadContexts.add(threadContext);
+
+ threadContext.close();
+
+ logger.deprecated(threadContexts, "Ignored logger message");
+
+ assertTrue(threadContexts.contains(threadContext));
+ }
+
+ public void testSafeWithoutThreadContext() {
+ logger.deprecated(Collections.emptySet(), "Ignored");
+ }
+
+ public void testFailsWithoutThreadContextSet() {
+ expectThrows(NullPointerException.class, () -> logger.deprecated((Set)null, "Does not explode"));
+ }
+
+ public void testFailsWhenDoubleSettingSameThreadContext() throws IOException {
+ try (ThreadContext threadContext = new ThreadContext(Settings.EMPTY)) {
+ DeprecationLogger.setThreadContext(threadContext);
+
+ try {
+ expectThrows(IllegalStateException.class, () -> DeprecationLogger.setThreadContext(threadContext));
+ } finally {
+ // cleanup after ourselves
+ DeprecationLogger.removeThreadContext(threadContext);
+ }
+ }
+ }
+
+ public void testFailsWhenRemovingUnknownThreadContext() throws IOException {
+ try (ThreadContext threadContext = new ThreadContext(Settings.EMPTY)) {
+ expectThrows(IllegalStateException.class, () -> DeprecationLogger.removeThreadContext(threadContext));
+ }
+ }
+
+}
diff --git a/core/src/test/java/org/elasticsearch/common/logging/LoggingConfigurationTests.java b/core/src/test/java/org/elasticsearch/common/logging/LoggingConfigurationTests.java
index fabace237b2..581a9599365 100644
--- a/core/src/test/java/org/elasticsearch/common/logging/LoggingConfigurationTests.java
+++ b/core/src/test/java/org/elasticsearch/common/logging/LoggingConfigurationTests.java
@@ -95,23 +95,6 @@ public class LoggingConfigurationTests extends ESTestCase {
assertThat(logSettings.get("json"), is("foo"));
}
- public void testResolvePropertiesLoggingConfig() throws Exception {
- Path tmpDir = createTempDir();
- Path loggingConf = tmpDir.resolve(loggingConfiguration("properties"));
- Files.write(loggingConf, "key: value".getBytes(StandardCharsets.UTF_8));
- Environment environment = new Environment(
- Settings.builder()
- .put(Environment.PATH_CONF_SETTING.getKey(), tmpDir.toAbsolutePath())
- .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
- .build());
-
- Settings.Builder builder = Settings.builder();
- LogConfigurator.resolveConfig(environment, builder);
-
- Settings logSettings = builder.build();
- assertThat(logSettings.get("key"), is("value"));
- }
-
public void testResolveYamlLoggingConfig() throws Exception {
Path tmpDir = createTempDir();
Path loggingConf1 = tmpDir.resolve(loggingConfiguration("yml"));
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 749ffa3c9d9..f5a5928c980 100644
--- a/core/src/test/java/org/elasticsearch/common/network/NetworkModuleTests.java
+++ b/core/src/test/java/org/elasticsearch/common/network/NetworkModuleTests.java
@@ -20,7 +20,7 @@
package org.elasticsearch.common.network;
import org.elasticsearch.action.support.replication.ReplicationTask;
-import org.elasticsearch.client.Client;
+import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.Table;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.ModuleTestCase;
@@ -59,7 +59,7 @@ public class NetworkModuleTests extends ModuleTestCase {
}
}
- static class FakeHttpTransport extends AbstractLifecycleComponent implements HttpServerTransport {
+ static class FakeHttpTransport extends AbstractLifecycleComponent implements HttpServerTransport {
public FakeHttpTransport() {
super(null);
}
@@ -87,18 +87,18 @@ public class NetworkModuleTests extends ModuleTestCase {
static class FakeRestHandler extends BaseRestHandler {
public FakeRestHandler() {
- super(null, null);
+ super(null);
}
@Override
- protected void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception {}
+ public void handleRequest(RestRequest request, RestChannel channel, NodeClient client) throws Exception {}
}
static class FakeCatRestHandler extends AbstractCatAction {
public FakeCatRestHandler() {
- super(null, null, null);
+ super(null);
}
@Override
- protected void doRequest(RestRequest request, RestChannel channel, Client client) {}
+ protected void doRequest(RestRequest request, RestChannel channel, NodeClient client) {}
@Override
protected void documentation(StringBuilder sb) {}
@Override
@@ -108,7 +108,10 @@ public class NetworkModuleTests extends ModuleTestCase {
}
public void testRegisterTransportService() {
- Settings settings = Settings.builder().put(NetworkModule.TRANSPORT_SERVICE_TYPE_KEY, "custom").build();
+ Settings settings = Settings.builder().put(NetworkModule.TRANSPORT_SERVICE_TYPE_KEY, "custom")
+ .put(NetworkModule.HTTP_ENABLED.getKey(), false)
+ .put(NetworkModule.TRANSPORT_TYPE_KEY, "local")
+ .build();
NetworkModule module = new NetworkModule(new NetworkService(settings), settings, false, new NamedWriteableRegistry());
module.registerTransportService("custom", FakeTransportService.class);
assertBinding(module, TransportService.class, FakeTransportService.class);
@@ -122,7 +125,9 @@ public class NetworkModuleTests extends ModuleTestCase {
}
public void testRegisterTransport() {
- Settings settings = Settings.builder().put(NetworkModule.TRANSPORT_TYPE_KEY, "custom").build();
+ Settings settings = Settings.builder().put(NetworkModule.TRANSPORT_TYPE_KEY, "custom")
+ .put(NetworkModule.HTTP_ENABLED.getKey(), false)
+ .build();
NetworkModule module = new NetworkModule(new NetworkService(settings), settings, false, new NamedWriteableRegistry());
module.registerTransport("custom", FakeTransport.class);
assertBinding(module, Transport.class, FakeTransport.class);
@@ -136,7 +141,9 @@ public class NetworkModuleTests extends ModuleTestCase {
}
public void testRegisterHttpTransport() {
- Settings settings = Settings.builder().put(NetworkModule.HTTP_TYPE_SETTING.getKey(), "custom").build();
+ Settings settings = Settings.builder()
+ .put(NetworkModule.HTTP_TYPE_SETTING.getKey(), "custom")
+ .put(NetworkModule.TRANSPORT_TYPE_KEY, "local").build();
NetworkModule module = new NetworkModule(new NetworkService(settings), settings, false, new NamedWriteableRegistry());
module.registerHttpTransport("custom", FakeHttpTransport.class);
assertBinding(module, HttpServerTransport.class, FakeHttpTransport.class);
@@ -154,7 +161,8 @@ public class NetworkModuleTests extends ModuleTestCase {
}
// not added if http is disabled
- settings = Settings.builder().put(NetworkModule.HTTP_ENABLED.getKey(), false).build();
+ settings = Settings.builder().put(NetworkModule.HTTP_ENABLED.getKey(), false)
+ .put(NetworkModule.TRANSPORT_TYPE_KEY, "local").build();
module = new NetworkModule(new NetworkService(settings), settings, false, new NamedWriteableRegistry());
assertNotBound(module, HttpServerTransport.class);
assertFalse(module.isTransportClient());
diff --git a/core/src/test/java/org/elasticsearch/common/rounding/TimeZoneRoundingTests.java b/core/src/test/java/org/elasticsearch/common/rounding/TimeZoneRoundingTests.java
index e82d37a5cf5..f9e5f6e3fbb 100644
--- a/core/src/test/java/org/elasticsearch/common/rounding/TimeZoneRoundingTests.java
+++ b/core/src/test/java/org/elasticsearch/common/rounding/TimeZoneRoundingTests.java
@@ -19,6 +19,7 @@
package org.elasticsearch.common.rounding;
+import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.rounding.TimeZoneRounding.TimeIntervalRounding;
import org.elasticsearch.common.rounding.TimeZoneRounding.TimeUnitRounding;
import org.elasticsearch.common.unit.TimeValue;
@@ -31,10 +32,13 @@ import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeZone;
import org.joda.time.format.ISODateTimeFormat;
+import java.util.ArrayList;
+import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
+import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
@@ -328,29 +332,70 @@ public class TimeZoneRoundingTests extends ESTestCase {
long interval = unit.toMillis(randomIntBetween(1, 365));
DateTimeZone tz = randomDateTimeZone();
TimeZoneRounding rounding = new TimeZoneRounding.TimeIntervalRounding(interval, tz);
- long date = Math.abs(randomLong() % (2 * (long) 10e11)); // 1970-01-01T00:00:00Z - 2033-05-18T05:33:20.000+02:00
- try {
- final long roundedDate = rounding.round(date);
- final long nextRoundingValue = rounding.nextRoundingValue(roundedDate);
- assertThat("Rounding should be idempotent", roundedDate, equalTo(rounding.round(roundedDate)));
- assertThat("Rounded value smaller or equal than unrounded", roundedDate, lessThanOrEqualTo(date));
- assertThat("Values smaller than rounded value should round further down", rounding.round(roundedDate - 1),
- lessThan(roundedDate));
+ long mainDate = Math.abs(randomLong() % (2 * (long) 10e11)); // 1970-01-01T00:00:00Z - 2033-05-18T05:33:20.000+02:00
+ if (randomBoolean()) {
+ mainDate = nastyDate(mainDate, tz, interval);
+ }
+ // check two intervals around date
+ long previousRoundedValue = Long.MIN_VALUE;
+ for (long date = mainDate - 2 * interval; date < mainDate + 2 * interval; date += interval / 2) {
+ try {
+ final long roundedDate = rounding.round(date);
+ final long nextRoundingValue = rounding.nextRoundingValue(roundedDate);
+ assertThat("Rounding should be idempotent", roundedDate, equalTo(rounding.round(roundedDate)));
+ assertThat("Rounded value smaller or equal than unrounded", roundedDate, lessThanOrEqualTo(date));
+ assertThat("Values smaller than rounded value should round further down", rounding.round(roundedDate - 1),
+ lessThan(roundedDate));
+ assertThat("Rounding should be >= previous rounding value", roundedDate, greaterThanOrEqualTo(previousRoundedValue));
- if (tz.isFixed()) {
- assertThat("NextRounding value should be greater than date", nextRoundingValue, greaterThan(roundedDate));
- assertThat("NextRounding value should be interval from rounded value", nextRoundingValue - roundedDate,
- equalTo(interval));
- assertThat("NextRounding value should be a rounded date", nextRoundingValue,
- equalTo(rounding.round(nextRoundingValue)));
+ if (tz.isFixed()) {
+ assertThat("NextRounding value should be greater than date", nextRoundingValue, greaterThan(roundedDate));
+ assertThat("NextRounding value should be interval from rounded value", nextRoundingValue - roundedDate,
+ equalTo(interval));
+ assertThat("NextRounding value should be a rounded date", nextRoundingValue,
+ equalTo(rounding.round(nextRoundingValue)));
+ }
+ previousRoundedValue = roundedDate;
+ } catch (AssertionError e) {
+ logger.error("Rounding error at {}, timezone {}, interval: {},", new DateTime(date, tz), tz, interval);
+ throw e;
}
- } catch (AssertionError e) {
- logger.error("Rounding error at {}, timezone {}, interval: {},", new DateTime(date, tz), tz, interval);
- throw e;
}
}
}
+ /**
+ * Test that rounded values are always greater or equal to last rounded value if date is increasing.
+ * The example covers an interval around 2011-10-30T02:10:00+01:00, time zone CET, interval: 2700000ms
+ */
+ public void testIntervalRoundingMonotonic_CET() {
+ long interval = TimeUnit.MINUTES.toMillis(45);
+ DateTimeZone tz = DateTimeZone.forID("CET");
+ TimeZoneRounding rounding = new TimeZoneRounding.TimeIntervalRounding(interval, tz);
+ List> expectedDates = new ArrayList>();
+ // first date is the date to be rounded, second the expected result
+ expectedDates.add(new Tuple<>("2011-10-30T01:40:00.000+02:00", "2011-10-30T01:30:00.000+02:00"));
+ expectedDates.add(new Tuple<>("2011-10-30T02:02:30.000+02:00", "2011-10-30T01:30:00.000+02:00"));
+ expectedDates.add(new Tuple<>("2011-10-30T02:25:00.000+02:00", "2011-10-30T02:15:00.000+02:00"));
+ expectedDates.add(new Tuple<>("2011-10-30T02:47:30.000+02:00", "2011-10-30T02:15:00.000+02:00"));
+ expectedDates.add(new Tuple<>("2011-10-30T02:10:00.000+01:00", "2011-10-30T02:15:00.000+02:00"));
+ expectedDates.add(new Tuple<>("2011-10-30T02:32:30.000+01:00", "2011-10-30T02:15:00.000+01:00"));
+ expectedDates.add(new Tuple<>("2011-10-30T02:55:00.000+01:00", "2011-10-30T02:15:00.000+01:00"));
+ expectedDates.add(new Tuple<>("2011-10-30T03:17:30.000+01:00", "2011-10-30T03:00:00.000+01:00"));
+
+ long previousDate = Long.MIN_VALUE;
+ for (Tuple dates : expectedDates) {
+ final long roundedDate = rounding.round(time(dates.v1()));
+ assertThat(roundedDate, isDate(time(dates.v2()), tz));
+ assertThat(roundedDate, greaterThanOrEqualTo(previousDate));
+ previousDate = roundedDate;
+ }
+ // here's what this means for interval widths
+ assertEquals(TimeUnit.MINUTES.toMillis(45), time("2011-10-30T02:15:00.000+02:00") - time("2011-10-30T01:30:00.000+02:00"));
+ assertEquals(TimeUnit.MINUTES.toMillis(60), time("2011-10-30T02:15:00.000+01:00") - time("2011-10-30T02:15:00.000+02:00"));
+ assertEquals(TimeUnit.MINUTES.toMillis(45), time("2011-10-30T03:00:00.000+01:00") - time("2011-10-30T02:15:00.000+01:00"));
+ }
+
/**
* special test for DST switch from #9491
*/
diff --git a/core/src/test/java/org/elasticsearch/common/settings/loader/PropertiesSettingsLoaderTests.java b/core/src/test/java/org/elasticsearch/common/settings/loader/PropertiesSettingsLoaderTests.java
deleted file mode 100644
index c13ae7cc68b..00000000000
--- a/core/src/test/java/org/elasticsearch/common/settings/loader/PropertiesSettingsLoaderTests.java
+++ /dev/null
@@ -1,57 +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.settings.loader;
-
-import org.elasticsearch.ElasticsearchParseException;
-import org.elasticsearch.test.ESTestCase;
-import org.junit.Before;
-
-import java.io.IOException;
-import java.nio.charset.Charset;
-
-public class PropertiesSettingsLoaderTests extends ESTestCase {
-
- private PropertiesSettingsLoader loader;
-
- @Before
- public void setUp() throws Exception {
- super.setUp();
- loader = new PropertiesSettingsLoader();
- }
-
- public void testDuplicateKeyFromStringThrowsException() throws IOException {
- final ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> loader.load("foo=bar\nfoo=baz"));
- assertEquals(e.getMessage(), "duplicate settings key [foo] found, previous value [bar], current value [baz]");
- }
-
- public void testDuplicateKeysFromBytesThrowsException() throws IOException {
- final ElasticsearchParseException e = expectThrows(
- ElasticsearchParseException.class,
- () -> loader.load("foo=bar\nfoo=baz".getBytes(Charset.defaultCharset()))
- );
- assertEquals(e.getMessage(), "duplicate settings key [foo] found, previous value [bar], current value [baz]");
- }
-
- public void testThatNoDuplicatesPropertiesDoesNotAcceptNullValues() {
- final PropertiesSettingsLoader.NoDuplicatesProperties properties = loader.new NoDuplicatesProperties();
- expectThrows(NullPointerException.class, () -> properties.put("key", null));
- }
-
-}
diff --git a/core/src/test/java/org/elasticsearch/common/transport/BoundTransportAddressTests.java b/core/src/test/java/org/elasticsearch/common/transport/BoundTransportAddressTests.java
index 45db5a33d21..1a3fa4db137 100644
--- a/core/src/test/java/org/elasticsearch/common/transport/BoundTransportAddressTests.java
+++ b/core/src/test/java/org/elasticsearch/common/transport/BoundTransportAddressTests.java
@@ -51,7 +51,7 @@ public class BoundTransportAddressTests extends ESTestCase {
// serialize
BytesStreamOutput streamOutput = new BytesStreamOutput();
transportAddress.writeTo(streamOutput);
- StreamInput in = ByteBufferStreamInput.wrap(streamOutput.bytes());
+ StreamInput in = streamOutput.bytes().streamInput();
BoundTransportAddress serializedAddress;
if (randomBoolean()) {
diff --git a/core/src/test/java/org/elasticsearch/common/unit/DistanceUnitTests.java b/core/src/test/java/org/elasticsearch/common/unit/DistanceUnitTests.java
index f9a4d3f22af..7c5463baed2 100644
--- a/core/src/test/java/org/elasticsearch/common/unit/DistanceUnitTests.java
+++ b/core/src/test/java/org/elasticsearch/common/unit/DistanceUnitTests.java
@@ -82,7 +82,7 @@ public class DistanceUnitTests extends ESTestCase {
for (DistanceUnit unit : DistanceUnit.values()) {
try (BytesStreamOutput out = new BytesStreamOutput()) {
unit.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat("Roundtrip serialisation failed.", DistanceUnit.readFromStream(in), equalTo(unit));
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/unit/FuzzinessTests.java b/core/src/test/java/org/elasticsearch/common/unit/FuzzinessTests.java
index 2b5a7c00e5d..3f6f1848fd8 100644
--- a/core/src/test/java/org/elasticsearch/common/unit/FuzzinessTests.java
+++ b/core/src/test/java/org/elasticsearch/common/unit/FuzzinessTests.java
@@ -145,7 +145,7 @@ public class FuzzinessTests extends ESTestCase {
private static Fuzziness doSerializeRoundtrip(Fuzziness in) throws IOException {
BytesStreamOutput output = new BytesStreamOutput();
in.writeTo(output);
- StreamInput streamInput = StreamInput.wrap(output.bytes());
+ StreamInput streamInput = output.bytes().streamInput();
return new Fuzziness(streamInput);
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/unit/TimeValueTests.java b/core/src/test/java/org/elasticsearch/common/unit/TimeValueTests.java
index 78afc9e514f..003d78ce42e 100644
--- a/core/src/test/java/org/elasticsearch/common/unit/TimeValueTests.java
+++ b/core/src/test/java/org/elasticsearch/common/unit/TimeValueTests.java
@@ -161,7 +161,7 @@ public class TimeValueTests extends ESTestCase {
value.writeTo(out);
assertEquals(expectedSize, out.size());
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
TimeValue inValue = new TimeValue(in);
assertThat(inValue, equalTo(value));
diff --git a/core/src/test/java/org/elasticsearch/common/util/CancellableThreadsTests.java b/core/src/test/java/org/elasticsearch/common/util/CancellableThreadsTests.java
index a89cb48c37a..729c431d2b2 100644
--- a/core/src/test/java/org/elasticsearch/common/util/CancellableThreadsTests.java
+++ b/core/src/test/java/org/elasticsearch/common/util/CancellableThreadsTests.java
@@ -132,7 +132,7 @@ public class CancellableThreadsTests extends ESTestCase {
public void testCancellableThreads() throws InterruptedException {
Thread[] threads = new Thread[randomIntBetween(3, 10)];
final TestPlan[] plans = new TestPlan[threads.length];
- final Throwable[] throwables = new Throwable[threads.length];
+ final Exception[] exceptions = new Exception[threads.length];
final boolean[] interrupted = new boolean[threads.length];
final CancellableThreads cancellableThreads = new CancellableThreads();
final CountDownLatch readyForCancel = new CountDownLatch(threads.length);
@@ -153,8 +153,8 @@ public class CancellableThreadsTests extends ESTestCase {
} else {
cancellableThreads.execute(new TestRunnable(plan, readyForCancel));
}
- } catch (Throwable t) {
- throwables[plan.id] = t;
+ } catch (Exception e) {
+ exceptions[plan.id] = e;
}
if (plan.exceptBeforeCancel || plan.exitBeforeCancel) {
// we have to mark we're ready now (actually done).
@@ -176,19 +176,19 @@ public class CancellableThreadsTests extends ESTestCase {
TestPlan plan = plans[i];
final Class> exceptionClass = plan.ioException ? IOCustomException.class : CustomException.class;
if (plan.exceptBeforeCancel) {
- assertThat(throwables[i], Matchers.instanceOf(exceptionClass));
+ assertThat(exceptions[i], Matchers.instanceOf(exceptionClass));
} else if (plan.exitBeforeCancel) {
- assertNull(throwables[i]);
+ assertNull(exceptions[i]);
} else {
// in all other cases, we expect a cancellation exception.
- assertThat(throwables[i], Matchers.instanceOf(CancellableThreads.ExecutionCancelledException.class));
+ assertThat(exceptions[i], Matchers.instanceOf(CancellableThreads.ExecutionCancelledException.class));
if (plan.exceptAfterCancel) {
- assertThat(throwables[i].getSuppressed(),
+ assertThat(exceptions[i].getSuppressed(),
Matchers.arrayContaining(
Matchers.instanceOf(exceptionClass)
));
} else {
- assertThat(throwables[i].getSuppressed(), Matchers.emptyArray());
+ assertThat(exceptions[i].getSuppressed(), Matchers.emptyArray());
}
}
assertThat(interrupted[plan.id], Matchers.equalTo(plan.presetInterrupt));
diff --git a/core/src/test/java/org/elasticsearch/common/util/IndexFolderUpgraderTests.java b/core/src/test/java/org/elasticsearch/common/util/IndexFolderUpgraderTests.java
index 26d6af1cd5f..5302ba8d55c 100644
--- a/core/src/test/java/org/elasticsearch/common/util/IndexFolderUpgraderTests.java
+++ b/core/src/test/java/org/elasticsearch/common/util/IndexFolderUpgraderTests.java
@@ -67,7 +67,7 @@ public class IndexFolderUpgraderTests extends ESTestCase {
public void testUpgradeCustomDataPath() throws IOException {
Path customPath = createTempDir();
final Settings nodeSettings = Settings.builder()
- .put(NodeEnvironment.ADD_NODE_ID_TO_CUSTOM_PATH.getKey(), randomBoolean())
+ .put(NodeEnvironment.ADD_NODE_LOCK_ID_TO_CUSTOM_PATH.getKey(), randomBoolean())
.put(Environment.PATH_SHARED_DATA_SETTING.getKey(), customPath.toAbsolutePath().toString()).build();
try (NodeEnvironment nodeEnv = newNodeEnvironment(nodeSettings)) {
final Index index = new Index(randomAsciiOfLength(10), UUIDs.randomBase64UUID());
@@ -96,7 +96,7 @@ public class IndexFolderUpgraderTests extends ESTestCase {
public void testPartialUpgradeCustomDataPath() throws IOException {
Path customPath = createTempDir();
final Settings nodeSettings = Settings.builder()
- .put(NodeEnvironment.ADD_NODE_ID_TO_CUSTOM_PATH.getKey(), randomBoolean())
+ .put(NodeEnvironment.ADD_NODE_LOCK_ID_TO_CUSTOM_PATH.getKey(), randomBoolean())
.put(Environment.PATH_SHARED_DATA_SETTING.getKey(), customPath.toAbsolutePath().toString()).build();
try (NodeEnvironment nodeEnv = newNodeEnvironment(nodeSettings)) {
final Index index = new Index(randomAsciiOfLength(10), UUIDs.randomBase64UUID());
@@ -136,7 +136,7 @@ public class IndexFolderUpgraderTests extends ESTestCase {
public void testUpgrade() throws IOException {
final Settings nodeSettings = Settings.builder()
- .put(NodeEnvironment.ADD_NODE_ID_TO_CUSTOM_PATH.getKey(), randomBoolean()).build();
+ .put(NodeEnvironment.ADD_NODE_LOCK_ID_TO_CUSTOM_PATH.getKey(), randomBoolean()).build();
try (NodeEnvironment nodeEnv = newNodeEnvironment(nodeSettings)) {
final Index index = new Index(randomAsciiOfLength(10), UUIDs.randomBase64UUID());
Settings settings = Settings.builder()
@@ -159,7 +159,7 @@ public class IndexFolderUpgraderTests extends ESTestCase {
public void testUpgradeIndices() throws IOException {
final Settings nodeSettings = Settings.builder()
- .put(NodeEnvironment.ADD_NODE_ID_TO_CUSTOM_PATH.getKey(), randomBoolean()).build();
+ .put(NodeEnvironment.ADD_NODE_LOCK_ID_TO_CUSTOM_PATH.getKey(), randomBoolean()).build();
try (NodeEnvironment nodeEnv = newNodeEnvironment(nodeSettings)) {
Map> indexSettingsMap = new HashMap<>();
for (int i = 0; i < randomIntBetween(2, 5); i++) {
@@ -256,7 +256,7 @@ public class IndexFolderUpgraderTests extends ESTestCase {
.numberOfReplicas(0)
.build();
try (NodeEnvironment nodeEnvironment = newNodeEnvironment()) {
- IndexMetaData.FORMAT.write(indexState, 1, nodeEnvironment.indexPaths(index));
+ IndexMetaData.FORMAT.write(indexState, nodeEnvironment.indexPaths(index));
assertFalse(IndexFolderUpgrader.needsUpgrade(index, index.getUUID()));
}
}
@@ -305,7 +305,7 @@ public class IndexFolderUpgraderTests extends ESTestCase {
for (int i = 0; i < nodePaths.length; i++) {
oldIndexPaths[i] = nodePaths[i].indicesPath.resolve(indexSettings.getIndex().getName());
}
- IndexMetaData.FORMAT.write(indexSettings.getIndexMetaData(), 1, oldIndexPaths);
+ IndexMetaData.FORMAT.write(indexSettings.getIndexMetaData(), oldIndexPaths);
for (int id = 0; id < indexSettings.getNumberOfShards(); id++) {
Path oldIndexPath = randomFrom(oldIndexPaths);
ShardId shardId = new ShardId(indexSettings.getIndex(), id);
@@ -316,7 +316,7 @@ public class IndexFolderUpgraderTests extends ESTestCase {
writeShard(shardId, oldIndexPath, numIdxFiles, numTranslogFiles);
}
ShardStateMetaData state = new ShardStateMetaData(true, indexSettings.getUUID(), AllocationId.newInitializing());
- ShardStateMetaData.FORMAT.write(state, 1, oldIndexPath.resolve(String.valueOf(shardId.getId())));
+ ShardStateMetaData.FORMAT.write(state, oldIndexPath.resolve(String.valueOf(shardId.getId())));
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractLifecycleRunnableTests.java b/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractLifecycleRunnableTests.java
index 4c2e4700943..02adb783197 100644
--- a/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractLifecycleRunnableTests.java
+++ b/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractLifecycleRunnableTests.java
@@ -48,7 +48,7 @@ public class AbstractLifecycleRunnableTests extends ESTestCase {
AbstractLifecycleRunnable runnable = new AbstractLifecycleRunnable(lifecycle, logger) {
@Override
- public void onFailure(Throwable t) {
+ public void onFailure(Exception e) {
fail("It should not fail");
}
@@ -77,7 +77,7 @@ public class AbstractLifecycleRunnableTests extends ESTestCase {
AbstractLifecycleRunnable runnable = new AbstractLifecycleRunnable(lifecycle, logger) {
@Override
- public void onFailure(Throwable t) {
+ public void onFailure(Exception e) {
fail("It should not fail");
}
@@ -106,7 +106,7 @@ public class AbstractLifecycleRunnableTests extends ESTestCase {
AbstractLifecycleRunnable runnable = new AbstractLifecycleRunnable(lifecycle, logger) {
@Override
- public void onFailure(Throwable t) {
+ public void onFailure(Exception e) {
fail("It should not fail");
}
@@ -145,7 +145,7 @@ public class AbstractLifecycleRunnableTests extends ESTestCase {
AbstractLifecycleRunnable runnable = new AbstractLifecycleRunnable(lifecycle, logger) {
@Override
- public void onFailure(Throwable t) {
+ public void onFailure(Exception e) {
fail("It should not fail");
}
diff --git a/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractRunnableTests.java b/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractRunnableTests.java
index 54491aade6f..2373b30e1b2 100644
--- a/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractRunnableTests.java
+++ b/core/src/test/java/org/elasticsearch/common/util/concurrent/AbstractRunnableTests.java
@@ -37,8 +37,8 @@ public class AbstractRunnableTests extends ESTestCase {
AbstractRunnable runnable = new AbstractRunnable() {
@Override
- public void onFailure(Throwable t) {
- fail("It should not fail");
+ public void onFailure(Exception e) {
+ fail(e.toString());
}
@Override
@@ -57,8 +57,8 @@ public class AbstractRunnableTests extends ESTestCase {
AbstractRunnable runnable = new AbstractRunnable() {
@Override
- public void onFailure(Throwable t) {
- assertSame(exception, t);
+ public void onFailure(Exception e) {
+ assertSame(exception, e);
}
@Override
@@ -76,8 +76,8 @@ public class AbstractRunnableTests extends ESTestCase {
AbstractRunnable runnable = new AbstractRunnable() {
@Override
- public void onFailure(Throwable t) {
- fail("It should not fail");
+ public void onFailure(Exception e) {
+ fail(e.toString());
}
@Override
@@ -91,7 +91,7 @@ public class AbstractRunnableTests extends ESTestCase {
afterCallable.call();
}
catch (Exception e) {
- fail("Unexpected for mock.");
+ fail(e.toString());
}
}
};
@@ -111,8 +111,8 @@ public class AbstractRunnableTests extends ESTestCase {
AbstractRunnable runnable = new AbstractRunnable() {
@Override
- public void onFailure(Throwable t) {
- assertSame(exception, t);
+ public void onFailure(Exception e) {
+ assertSame(exception, e);
}
@Override
@@ -126,7 +126,7 @@ public class AbstractRunnableTests extends ESTestCase {
afterCallable.call();
}
catch (Exception e) {
- fail("Unexpected for mock.");
+ fail(e.toString());
}
}
};
@@ -142,14 +142,15 @@ public class AbstractRunnableTests extends ESTestCase {
AbstractRunnable runnable = new AbstractRunnable() {
@Override
- public void onFailure(Throwable t) {
- assertSame(exception, t);
+ public void onFailure(Exception e) {
+ assertSame(exception, e);
try {
failureCallable.call();
}
- catch (Exception e) {
- fail("Unexpected for mock.");
+ catch (Exception inner) {
+ inner.addSuppressed(e);
+ fail(inner.toString());
}
}
@@ -165,8 +166,8 @@ public class AbstractRunnableTests extends ESTestCase {
public void testIsForceExecutuonDefaultsFalse() {
AbstractRunnable runnable = new AbstractRunnable() {
@Override
- public void onFailure(Throwable t) {
- fail("Not tested");
+ public void onFailure(Exception e) {
+ fail(e.toString());
}
@Override
diff --git a/core/src/test/java/org/elasticsearch/common/util/concurrent/EsExecutorsTests.java b/core/src/test/java/org/elasticsearch/common/util/concurrent/EsExecutorsTests.java
index 57da614e689..72db2911fc0 100644
--- a/core/src/test/java/org/elasticsearch/common/util/concurrent/EsExecutorsTests.java
+++ b/core/src/test/java/org/elasticsearch/common/util/concurrent/EsExecutorsTests.java
@@ -88,8 +88,8 @@ public class EsExecutorsTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable t) {
- throw new AssertionError(t);
+ public void onFailure(Exception e) {
+ throw new AssertionError(e);
}
});
@@ -178,7 +178,7 @@ public class EsExecutorsTests extends ESTestCase {
try {
barrier.await();
barrier.await();
- } catch (Throwable e) {
+ } catch (Exception e) {
barrier.reset(e);
}
}
@@ -214,7 +214,7 @@ public class EsExecutorsTests extends ESTestCase {
try {
barrier.await();
barrier.await();
- } catch (Throwable e) {
+ } catch (Exception e) {
barrier.reset(e);
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/util/concurrent/PrioritizedExecutorsTests.java b/core/src/test/java/org/elasticsearch/common/util/concurrent/PrioritizedExecutorsTests.java
index df51e6e2e0d..933a46de510 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
@@ -41,9 +41,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
-/**
- *
- */
public class PrioritizedExecutorsTests extends ESTestCase {
private final ThreadContext holder = new ThreadContext(Settings.EMPTY);
diff --git a/core/src/test/java/org/elasticsearch/common/util/concurrent/RefCountedTests.java b/core/src/test/java/org/elasticsearch/common/util/concurrent/RefCountedTests.java
index 9338beccb9a..c5d0ec4257e 100644
--- a/core/src/test/java/org/elasticsearch/common/util/concurrent/RefCountedTests.java
+++ b/core/src/test/java/org/elasticsearch/common/util/concurrent/RefCountedTests.java
@@ -88,7 +88,7 @@ public class RefCountedTests extends ESTestCase {
final MyRefCounted counted = new MyRefCounted();
Thread[] threads = new Thread[randomIntBetween(2, 5)];
final CountDownLatch latch = new CountDownLatch(1);
- final CopyOnWriteArrayList exceptions = new CopyOnWriteArrayList<>();
+ final CopyOnWriteArrayList exceptions = new CopyOnWriteArrayList<>();
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread() {
@Override
@@ -103,7 +103,7 @@ public class RefCountedTests extends ESTestCase {
counted.decRef();
}
}
- } catch (Throwable e) {
+ } catch (Exception e) {
exceptions.add(e);
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/util/concurrent/SuspendableRefContainerTests.java b/core/src/test/java/org/elasticsearch/common/util/concurrent/SuspendableRefContainerTests.java
deleted file mode 100644
index 83db2d4a7c6..00000000000
--- a/core/src/test/java/org/elasticsearch/common/util/concurrent/SuspendableRefContainerTests.java
+++ /dev/null
@@ -1,115 +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.util.concurrent;
-
-import org.elasticsearch.common.lease.Releasable;
-import org.elasticsearch.common.unit.TimeValue;
-import org.elasticsearch.test.ESTestCase;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.nullValue;
-
-public class SuspendableRefContainerTests extends ESTestCase {
-
- public void testBasicAcquire() throws InterruptedException {
- SuspendableRefContainer refContainer = new SuspendableRefContainer();
- assertThat(refContainer.activeRefs(), equalTo(0));
-
- Releasable lock1 = randomLockingMethod(refContainer);
- assertThat(refContainer.activeRefs(), equalTo(1));
- Releasable lock2 = randomLockingMethod(refContainer);
- assertThat(refContainer.activeRefs(), equalTo(2));
- lock1.close();
- assertThat(refContainer.activeRefs(), equalTo(1));
- lock1.close(); // check idempotence
- assertThat(refContainer.activeRefs(), equalTo(1));
- lock2.close();
- assertThat(refContainer.activeRefs(), equalTo(0));
- }
-
- public void testAcquisitionBlockingBlocksNewAcquisitions() throws InterruptedException {
- SuspendableRefContainer refContainer = new SuspendableRefContainer();
- assertThat(refContainer.activeRefs(), equalTo(0));
-
- try (Releasable block = refContainer.blockAcquisition()) {
- assertThat(refContainer.activeRefs(), equalTo(0));
- assertThat(refContainer.tryAcquire(), nullValue());
- assertThat(refContainer.activeRefs(), equalTo(0));
- }
- try (Releasable lock = refContainer.tryAcquire()) {
- assertThat(refContainer.activeRefs(), equalTo(1));
- }
-
- // same with blocking acquire
- AtomicBoolean acquired = new AtomicBoolean();
- Thread t = new Thread(() -> {
- try (Releasable lock = randomBoolean() ? refContainer.acquire() : refContainer.acquireUninterruptibly()) {
- acquired.set(true);
- assertThat(refContainer.activeRefs(), equalTo(1));
- } catch (InterruptedException e) {
- fail("Interrupted");
- }
- });
- try (Releasable block = refContainer.blockAcquisition()) {
- assertThat(refContainer.activeRefs(), equalTo(0));
- t.start();
- // check that blocking acquire really blocks
- assertThat(acquired.get(), equalTo(false));
- assertThat(refContainer.activeRefs(), equalTo(0));
- }
- t.join();
- assertThat(acquired.get(), equalTo(true));
- assertThat(refContainer.activeRefs(), equalTo(0));
- }
-
- public void testAcquisitionBlockingWaitsOnExistingAcquisitions() throws InterruptedException {
- SuspendableRefContainer refContainer = new SuspendableRefContainer();
-
- AtomicBoolean acquired = new AtomicBoolean();
- Thread t = new Thread(() -> {
- try (Releasable block = refContainer.blockAcquisition()) {
- acquired.set(true);
- assertThat(refContainer.activeRefs(), equalTo(0));
- }
- });
- try (Releasable lock = randomLockingMethod(refContainer)) {
- assertThat(refContainer.activeRefs(), equalTo(1));
- t.start();
- assertThat(acquired.get(), equalTo(false));
- assertThat(refContainer.activeRefs(), equalTo(1));
- }
- t.join();
- assertThat(acquired.get(), equalTo(true));
- assertThat(refContainer.activeRefs(), equalTo(0));
- }
-
- private Releasable randomLockingMethod(SuspendableRefContainer refContainer) throws InterruptedException {
- switch (randomInt(2)) {
- case 0: return refContainer.tryAcquire();
- case 1: return refContainer.acquire();
- case 2: return refContainer.acquireUninterruptibly();
- }
- throw new IllegalArgumentException("randomLockingMethod inconsistent");
- }
-}
diff --git a/core/src/test/java/org/elasticsearch/common/util/concurrent/ThreadContextTests.java b/core/src/test/java/org/elasticsearch/common/util/concurrent/ThreadContextTests.java
index 1a582d48f6b..d402f09f07d 100644
--- a/core/src/test/java/org/elasticsearch/common/util/concurrent/ThreadContextTests.java
+++ b/core/src/test/java/org/elasticsearch/common/util/concurrent/ThreadContextTests.java
@@ -19,14 +19,18 @@
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;
import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.sameInstance;
public class ThreadContextTests extends ESTestCase {
@@ -35,7 +39,7 @@ public class ThreadContextTests extends ESTestCase {
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.putTransient("ctx.foo", 1);
assertEquals("bar", threadContext.getHeader("foo"));
assertEquals(new Integer(1), threadContext.getTransient("ctx.foo"));
assertEquals("1", threadContext.getHeader("default"));
@@ -46,7 +50,7 @@ public class ThreadContextTests extends ESTestCase {
}
assertEquals("bar", threadContext.getHeader("foo"));
- assertEquals(new Integer(1), threadContext.getTransient("ctx.foo"));
+ assertEquals(Integer.valueOf(1), threadContext.getTransient("ctx.foo"));
assertEquals("1", threadContext.getHeader("default"));
}
@@ -54,7 +58,7 @@ public class ThreadContextTests extends ESTestCase {
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.putTransient("ctx.foo", 1);
assertEquals("bar", threadContext.getHeader("foo"));
assertEquals(new Integer(1), threadContext.getTransient("ctx.foo"));
assertEquals("1", threadContext.getHeader("default"));
@@ -70,7 +74,7 @@ public class ThreadContextTests extends ESTestCase {
assertNull(threadContext.getHeader("simon"));
assertEquals("bar", threadContext.getHeader("foo"));
- assertEquals(new Integer(1), threadContext.getTransient("ctx.foo"));
+ assertEquals(Integer.valueOf(1), threadContext.getTransient("ctx.foo"));
assertEquals("1", threadContext.getHeader("default"));
}
@@ -78,9 +82,9 @@ public class ThreadContextTests extends ESTestCase {
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.putTransient("ctx.foo", 1);
assertEquals("bar", threadContext.getHeader("foo"));
- assertEquals(new Integer(1), threadContext.getTransient("ctx.foo"));
+ assertEquals(Integer.valueOf(1), threadContext.getTransient("ctx.foo"));
assertEquals("1", threadContext.getHeader("default"));
ThreadContext.StoredContext storedContext = threadContext.newStoredContext();
threadContext.putHeader("foo.bar", "baz");
@@ -91,7 +95,7 @@ public class ThreadContextTests extends ESTestCase {
}
assertEquals("bar", threadContext.getHeader("foo"));
- assertEquals(new Integer(1), threadContext.getTransient("ctx.foo"));
+ assertEquals(Integer.valueOf(1), threadContext.getTransient("ctx.foo"));
assertEquals("1", threadContext.getHeader("default"));
assertEquals("baz", threadContext.getHeader("foo.bar"));
if (randomBoolean()) {
@@ -100,11 +104,44 @@ public class ThreadContextTests extends ESTestCase {
storedContext.close();
}
assertEquals("bar", threadContext.getHeader("foo"));
- assertEquals(new Integer(1), threadContext.getTransient("ctx.foo"));
+ assertEquals(Integer.valueOf(1), threadContext.getTransient("ctx.foo"));
assertEquals("1", threadContext.getHeader("default"));
assertNull(threadContext.getHeader("foo.bar"));
}
+ public void testResponseHeaders() {
+ final boolean expectThird = randomBoolean();
+
+ final ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
+
+ threadContext.addResponseHeader("foo", "bar");
+ // pretend that another thread created the same response
+ if (randomBoolean()) {
+ threadContext.addResponseHeader("foo", "bar");
+ }
+
+ threadContext.addResponseHeader("Warning", "One is the loneliest number");
+ threadContext.addResponseHeader("Warning", "Two can be as bad as one");
+ if (expectThird) {
+ threadContext.addResponseHeader("Warning", "No is the saddest experience");
+ }
+
+ final Map> responseHeaders = threadContext.getResponseHeaders();
+ final List foo = responseHeaders.get("foo");
+ final List warnings = responseHeaders.get("Warning");
+ final int expectedWarnings = expectThird ? 3 : 2;
+
+ assertThat(foo, hasSize(1));
+ assertEquals("bar", foo.get(0));
+ assertThat(warnings, hasSize(expectedWarnings));
+ assertThat(warnings, hasItem(equalTo("One is the loneliest number")));
+ assertThat(warnings, hasItem(equalTo("Two can be as bad as one")));
+
+ if (expectThird) {
+ assertThat(warnings, hasItem(equalTo("No is the saddest experience")));
+ }
+ }
+
public void testCopyHeaders() {
Settings build = Settings.builder().put("request.headers.default", "1").build();
ThreadContext threadContext = new ThreadContext(build);
@@ -117,7 +154,7 @@ public class ThreadContextTests extends ESTestCase {
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.putTransient("ctx.foo", 1);
threadContext.close();
try {
@@ -146,20 +183,35 @@ public class ThreadContextTests extends ESTestCase {
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.putTransient("ctx.foo", 1);
+ threadContext.addResponseHeader("Warning", "123456");
+ if (rarely()) {
+ threadContext.addResponseHeader("Warning", "123456");
+ }
+ threadContext.addResponseHeader("Warning", "234567");
+
BytesStreamOutput out = new BytesStreamOutput();
threadContext.writeTo(out);
try (ThreadContext.StoredContext ctx = threadContext.stashContext()) {
assertNull(threadContext.getHeader("foo"));
assertNull(threadContext.getTransient("ctx.foo"));
+ assertTrue(threadContext.getResponseHeaders().isEmpty());
assertEquals("1", threadContext.getHeader("default"));
- threadContext.readHeaders(StreamInput.wrap(out.bytes()));
+ threadContext.readHeaders(out.bytes().streamInput());
assertEquals("bar", threadContext.getHeader("foo"));
assertNull(threadContext.getTransient("ctx.foo"));
+
+ final Map> responseHeaders = threadContext.getResponseHeaders();
+ final List warnings = responseHeaders.get("Warning");
+
+ assertThat(responseHeaders.keySet(), hasSize(1));
+ assertThat(warnings, hasSize(2));
+ assertThat(warnings, hasItem(equalTo("123456")));
+ assertThat(warnings, hasItem(equalTo("234567")));
}
assertEquals("bar", threadContext.getHeader("foo"));
- assertEquals(new Integer(1), threadContext.getTransient("ctx.foo"));
+ assertEquals(Integer.valueOf(1), threadContext.getTransient("ctx.foo"));
assertEquals("1", threadContext.getHeader("default"));
}
@@ -169,30 +221,44 @@ public class ThreadContextTests extends ESTestCase {
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.putTransient("ctx.foo", 1);
+ threadContext.addResponseHeader("Warning", "123456");
+ if (rarely()) {
+ threadContext.addResponseHeader("Warning", "123456");
+ }
+ threadContext.addResponseHeader("Warning", "234567");
assertEquals("bar", threadContext.getHeader("foo"));
assertNotNull(threadContext.getTransient("ctx.foo"));
assertEquals("1", threadContext.getHeader("default"));
+ assertThat(threadContext.getResponseHeaders().keySet(), hasSize(1));
threadContext.writeTo(out);
}
{
Settings otherSettings = Settings.builder().put("request.headers.default", "5").build();
- ThreadContext otherhreadContext = new ThreadContext(otherSettings);
- otherhreadContext.readHeaders(StreamInput.wrap(out.bytes()));
+ ThreadContext otherThreadContext = new ThreadContext(otherSettings);
+ otherThreadContext.readHeaders(out.bytes().streamInput());
- assertEquals("bar", otherhreadContext.getHeader("foo"));
- assertNull(otherhreadContext.getTransient("ctx.foo"));
- assertEquals("1", otherhreadContext.getHeader("default"));
+ assertEquals("bar", otherThreadContext.getHeader("foo"));
+ assertNull(otherThreadContext.getTransient("ctx.foo"));
+ assertEquals("1", otherThreadContext.getHeader("default"));
+
+ final Map> responseHeaders = otherThreadContext.getResponseHeaders();
+ final List warnings = responseHeaders.get("Warning");
+
+ assertThat(responseHeaders.keySet(), hasSize(1));
+ assertThat(warnings, hasSize(2));
+ assertThat(warnings, hasItem(equalTo("123456")));
+ assertThat(warnings, hasItem(equalTo("234567")));
}
}
-
+
public void testSerializeInDifferentContextNoDefaults() throws IOException {
BytesStreamOutput out = new BytesStreamOutput();
{
ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
threadContext.putHeader("foo", "bar");
- threadContext.putTransient("ctx.foo", new Integer(1));
+ threadContext.putTransient("ctx.foo", 1);
assertEquals("bar", threadContext.getHeader("foo"));
assertNotNull(threadContext.getTransient("ctx.foo"));
@@ -202,7 +268,7 @@ public class ThreadContextTests extends ESTestCase {
{
Settings otherSettings = Settings.builder().put("request.headers.default", "5").build();
ThreadContext otherhreadContext = new ThreadContext(otherSettings);
- otherhreadContext.readHeaders(StreamInput.wrap(out.bytes()));
+ otherhreadContext.readHeaders(out.bytes().streamInput());
assertEquals("bar", otherhreadContext.getHeader("foo"));
assertNull(otherhreadContext.getTransient("ctx.foo"));
@@ -210,7 +276,6 @@ public class ThreadContextTests extends ESTestCase {
}
}
-
public void testCanResetDefault() {
Settings build = Settings.builder().put("request.headers.default", "1").build();
ThreadContext threadContext = new ThreadContext(build);
@@ -294,8 +359,8 @@ public class ThreadContextTests extends ESTestCase {
}
return new AbstractRunnable() {
@Override
- public void onFailure(Throwable t) {
- throw new RuntimeException(t);
+ public void onFailure(Exception e) {
+ throw new RuntimeException(e);
}
@Override
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/ConstructingObjectParserTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/ConstructingObjectParserTests.java
index f3592936765..bef4a047ef5 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/ConstructingObjectParserTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/ConstructingObjectParserTests.java
@@ -68,7 +68,7 @@ public class ConstructingObjectParserTests extends ESTestCase {
assertEquals(expected.b, parsed.b);
assertEquals(expected.c, parsed.c);
assertEquals(expected.d, parsed.d);
- } catch (Throwable e) {
+ } catch (Exception e) {
// It is convenient to decorate the error message with the json
throw new Exception("Error parsing: [" + builder.string() + "]", e);
}
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java
index 159d8a97be4..a8d26e87ecf 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java
@@ -35,7 +35,7 @@ import org.elasticsearch.test.ESTestCase;
public class ObjectParserTests extends ESTestCase {
- private final static ParseFieldMatcherSupplier STRICT_PARSING = () -> ParseFieldMatcher.STRICT;
+ private static final ParseFieldMatcherSupplier STRICT_PARSING = () -> ParseFieldMatcher.STRICT;
public void testBasics() throws IOException {
XContentParser parser = XContentType.JSON.xContent().createParser(
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/XContentFactoryTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/XContentFactoryTests.java
index 583234461b3..8319873878a 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/XContentFactoryTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/XContentFactoryTests.java
@@ -57,11 +57,10 @@ public class XContentFactoryTests extends ESTestCase {
builder.endObject();
assertThat(XContentFactory.xContentType(builder.bytes()), equalTo(type));
- BytesArray bytesArray = builder.bytes().toBytesArray();
- assertThat(XContentFactory.xContentType(StreamInput.wrap(bytesArray.array(), bytesArray.arrayOffset(), bytesArray.length())), equalTo(type));
+ assertThat(XContentFactory.xContentType(builder.bytes().streamInput()), equalTo(type));
// CBOR is binary, cannot use String
- if (type != XContentType.CBOR) {
+ if (type != XContentType.CBOR && type != XContentType.SMILE) {
assertThat(XContentFactory.xContentType(builder.string()), equalTo(type));
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java
index 34944e713bd..fe69fc1f05d 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java
@@ -94,7 +94,7 @@ public class XContentBuilderTests extends ESTestCase {
xContentBuilder.startObject();
xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.endObject();
- assertThat(xContentBuilder.bytes().toUtf8(), equalTo("{\"foo\":{\"test\":\"value\"}}"));
+ assertThat(xContentBuilder.bytes().utf8ToString(), equalTo("{\"foo\":{\"test\":\"value\"}}"));
}
{
XContentBuilder xContentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
@@ -102,7 +102,7 @@ public class XContentBuilderTests extends ESTestCase {
xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.rawField("foo1", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.endObject();
- assertThat(xContentBuilder.bytes().toUtf8(), equalTo("{\"foo\":{\"test\":\"value\"},\"foo1\":{\"test\":\"value\"}}"));
+ assertThat(xContentBuilder.bytes().utf8ToString(), equalTo("{\"foo\":{\"test\":\"value\"},\"foo1\":{\"test\":\"value\"}}"));
}
{
XContentBuilder xContentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
@@ -110,7 +110,7 @@ public class XContentBuilderTests extends ESTestCase {
xContentBuilder.field("test", "value");
xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.endObject();
- assertThat(xContentBuilder.bytes().toUtf8(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"}}"));
+ assertThat(xContentBuilder.bytes().utf8ToString(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"}}"));
}
{
XContentBuilder xContentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
@@ -119,7 +119,7 @@ public class XContentBuilderTests extends ESTestCase {
xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.field("test1", "value1");
xContentBuilder.endObject();
- assertThat(xContentBuilder.bytes().toUtf8(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"},\"test1\":\"value1\"}"));
+ assertThat(xContentBuilder.bytes().utf8ToString(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"},\"test1\":\"value1\"}"));
}
{
XContentBuilder xContentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
@@ -129,7 +129,7 @@ public class XContentBuilderTests extends ESTestCase {
xContentBuilder.rawField("foo1", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.field("test1", "value1");
xContentBuilder.endObject();
- assertThat(xContentBuilder.bytes().toUtf8(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"},\"foo1\":{\"test\":\"value\"},\"test1\":\"value1\"}"));
+ assertThat(xContentBuilder.bytes().utf8ToString(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"},\"foo1\":{\"test\":\"value\"},\"test1\":\"value1\"}"));
}
}
@@ -161,15 +161,14 @@ public class XContentBuilderTests extends ESTestCase {
gen.writeEndObject();
gen.close();
- byte[] data = bos.bytes().toBytes();
- String sData = new String(data, "UTF8");
+ String sData = bos.bytes().utf8ToString();
assertThat(sData, equalTo("{\"name\":\"something\", source : { test : \"value\" },\"name2\":\"something2\"}"));
}
public void testByteConversion() throws Exception {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.startObject().field("test_name", (Byte)(byte)120).endObject();
- assertThat(builder.bytes().toUtf8(), equalTo("{\"test_name\":120}"));
+ assertThat(builder.bytes().utf8ToString(), equalTo("{\"test_name\":120}"));
}
public void testDateTypesConversion() throws Exception {
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/cbor/JsonVsCborTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/cbor/JsonVsCborTests.java
index bf2dd442b64..efbca114aac 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/cbor/JsonVsCborTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/cbor/JsonVsCborTests.java
@@ -63,7 +63,8 @@ public class JsonVsCborTests extends ESTestCase {
xsonGen.close();
jsonGen.close();
- verifySameTokens(XContentFactory.xContent(XContentType.JSON).createParser(jsonOs.bytes().toBytes()), XContentFactory.xContent(XContentType.CBOR).createParser(xsonOs.bytes().toBytes()));
+ verifySameTokens(XContentFactory.xContent(XContentType.JSON).createParser(jsonOs.bytes()),
+ XContentFactory.xContent(XContentType.CBOR).createParser(xsonOs.bytes()));
}
private void verifySameTokens(XContentParser parser1, XContentParser parser2) throws IOException {
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/smile/JsonVsSmileTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/smile/JsonVsSmileTests.java
index 9e686fe78f1..63b19a63822 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/smile/JsonVsSmileTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/smile/JsonVsSmileTests.java
@@ -63,7 +63,8 @@ public class JsonVsSmileTests extends ESTestCase {
xsonGen.close();
jsonGen.close();
- verifySameTokens(XContentFactory.xContent(XContentType.JSON).createParser(jsonOs.bytes().toBytes()), XContentFactory.xContent(XContentType.SMILE).createParser(xsonOs.bytes().toBytes()));
+ verifySameTokens(XContentFactory.xContent(XContentType.JSON).createParser(jsonOs.bytes()),
+ XContentFactory.xContent(XContentType.SMILE).createParser(xsonOs.bytes()));
}
private void verifySameTokens(XContentParser parser1, XContentParser parser2) throws IOException {
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/AbstractFilteringJsonGeneratorTestCase.java b/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/AbstractFilteringJsonGeneratorTestCase.java
index e3d8735e05e..b8b38a543f6 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/AbstractFilteringJsonGeneratorTestCase.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/AbstractFilteringJsonGeneratorTestCase.java
@@ -27,7 +27,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;
-import java.io.ByteArrayInputStream;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
@@ -45,7 +44,7 @@ public abstract class AbstractFilteringJsonGeneratorTestCase extends ESTestCase
assertNotNull(expected);
// Verify that the result is equal to the expected string
- assertThat(builder.bytes().toUtf8(), is(expected.bytes().toUtf8()));
+ assertThat(builder.bytes().utf8ToString(), is(expected.bytes().utf8ToString()));
}
protected void assertBinary(XContentBuilder expected, XContentBuilder builder) {
@@ -1166,15 +1165,15 @@ public abstract class AbstractFilteringJsonGeneratorTestCase extends ESTestCase
// Test method: rawField(String fieldName, InputStream content)
assertXContentBuilder(expectedRawField,
- newXContentBuilder().startObject().field("foo", 0).rawField("raw", new ByteArrayInputStream(raw.toBytes())).endObject());
+ newXContentBuilder().startObject().field("foo", 0).rawField("raw", raw.streamInput()).endObject());
assertXContentBuilder(expectedRawFieldFiltered, newXContentBuilder("f*", true).startObject().field("foo", 0)
- .rawField("raw", new ByteArrayInputStream(raw.toBytes())).endObject());
+ .rawField("raw", raw.streamInput()).endObject());
assertXContentBuilder(expectedRawFieldFiltered, newXContentBuilder("r*", false).startObject().field("foo", 0)
- .rawField("raw", new ByteArrayInputStream(raw.toBytes())).endObject());
+ .rawField("raw", raw.streamInput()).endObject());
assertXContentBuilder(expectedRawFieldNotFiltered, newXContentBuilder("r*", true).startObject().field("foo", 0)
- .rawField("raw", new ByteArrayInputStream(raw.toBytes())).endObject());
+ .rawField("raw", raw.streamInput()).endObject());
assertXContentBuilder(expectedRawFieldNotFiltered, newXContentBuilder("f*", false).startObject().field("foo", 0)
- .rawField("raw", new ByteArrayInputStream(raw.toBytes())).endObject());
+ .rawField("raw", raw.streamInput()).endObject());
}
public void testArrays() throws Exception {
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/FilterPathGeneratorFilteringTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/FilterPathGeneratorFilteringTests.java
index dd2fe42eb8e..8dbefedb249 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/FilterPathGeneratorFilteringTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/FilterPathGeneratorFilteringTests.java
@@ -142,7 +142,7 @@ public class FilterPathGeneratorFilteringTests extends ESTestCase {
}
}
}
- assertThat(os.bytes().toUtf8(), equalTo(replaceQuotes(expected)));
+ assertThat(os.bytes().utf8ToString(), equalTo(replaceQuotes(expected)));
}
}
diff --git a/core/src/test/java/org/elasticsearch/consistencylevel/WriteConsistencyLevelIT.java b/core/src/test/java/org/elasticsearch/consistencylevel/WriteConsistencyLevelIT.java
index fb54e9b6f52..067f7e11530 100644
--- a/core/src/test/java/org/elasticsearch/consistencylevel/WriteConsistencyLevelIT.java
+++ b/core/src/test/java/org/elasticsearch/consistencylevel/WriteConsistencyLevelIT.java
@@ -22,6 +22,7 @@ package org.elasticsearch.consistencylevel;
import org.elasticsearch.action.UnavailableShardsException;
import org.elasticsearch.action.WriteConsistencyLevel;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
+import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.settings.Settings;
@@ -30,6 +31,7 @@ import org.elasticsearch.test.ESIntegTestCase;
import static org.elasticsearch.common.unit.TimeValue.timeValueMillis;
import static org.elasticsearch.common.unit.TimeValue.timeValueSeconds;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.hamcrest.Matchers.equalTo;
/**
@@ -37,12 +39,11 @@ import static org.hamcrest.Matchers.equalTo;
*/
public class WriteConsistencyLevelIT extends ESIntegTestCase {
public void testWriteConsistencyLevelReplication2() throws Exception {
- prepareCreate("test", 1, Settings.builder().put("index.number_of_shards", 1).put("index.number_of_replicas", 2)).execute().actionGet();
+ CreateIndexResponse createIndexResponse =
+ prepareCreate("test", 1, Settings.builder().put("index.number_of_shards", 1).put("index.number_of_replicas", 2))
+ .get();
- ClusterHealthResponse clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForActiveShards(1).setWaitForYellowStatus().execute().actionGet();
- logger.info("Done Cluster Health, status {}", clusterHealth.getStatus());
- assertThat(clusterHealth.isTimedOut(), equalTo(false));
- assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
+ assertAcked(createIndexResponse);
// indexing, by default, will work (ONE consistency level)
client().prepareIndex("test", "type1", "1").setSource(source("1", "test")).setConsistencyLevel(WriteConsistencyLevel.ONE).execute().actionGet();
@@ -59,7 +60,13 @@ public class WriteConsistencyLevelIT extends ESIntegTestCase {
allowNodes("test", 2);
- clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForActiveShards(2).setWaitForYellowStatus().execute().actionGet();
+ ClusterHealthResponse clusterHealth =
+ client().admin().cluster().prepareHealth()
+ .setWaitForEvents(Priority.LANGUID)
+ .setWaitForActiveShards(2)
+ .setWaitForYellowStatus()
+ .execute()
+ .actionGet();
logger.info("Done Cluster Health, status {}", clusterHealth.getStatus());
assertThat(clusterHealth.isTimedOut(), equalTo(false));
assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
diff --git a/core/src/test/java/org/elasticsearch/deps/jackson/JacksonLocationTests.java b/core/src/test/java/org/elasticsearch/deps/jackson/JacksonLocationTests.java
index 4efedd9154a..c25a0a6503b 100644
--- a/core/src/test/java/org/elasticsearch/deps/jackson/JacksonLocationTests.java
+++ b/core/src/test/java/org/elasticsearch/deps/jackson/JacksonLocationTests.java
@@ -56,8 +56,7 @@ public class JacksonLocationTests extends ESTestCase {
gen.close();
- byte[] data = os.bytes().toBytes();
- JsonParser parser = new JsonFactory().createParser(data);
+ JsonParser parser = new JsonFactory().createParser(os.bytes().streamInput());
assertThat(parser.nextToken(), equalTo(JsonToken.START_OBJECT));
assertThat(parser.nextToken(), equalTo(JsonToken.FIELD_NAME)); // "index"
diff --git a/core/src/test/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandlerTests.java b/core/src/test/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandlerTests.java
index f6aac190c4b..4ff4c4cd035 100644
--- a/core/src/test/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandlerTests.java
+++ b/core/src/test/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandlerTests.java
@@ -21,7 +21,7 @@ package org.elasticsearch.discovery;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.logging.ESLogger;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
import org.elasticsearch.test.ESTestCase;
@@ -40,7 +40,7 @@ import static org.hamcrest.Matchers.not;
public class BlockingClusterStatePublishResponseHandlerTests extends ESTestCase {
- static private class PublishResponder extends AbstractRunnable {
+ private static class PublishResponder extends AbstractRunnable {
final boolean fail;
final DiscoveryNode node;
@@ -58,8 +58,8 @@ public class BlockingClusterStatePublishResponseHandlerTests extends ESTestCase
}
@Override
- public void onFailure(Throwable t) {
- logger.error("unexpected error", t);
+ public void onFailure(Exception e) {
+ logger.error("unexpected error", e);
}
@Override
@@ -77,7 +77,7 @@ public class BlockingClusterStatePublishResponseHandlerTests extends ESTestCase
int nodeCount = scaledRandomIntBetween(10, 20);
DiscoveryNode[] allNodes = new DiscoveryNode[nodeCount];
for (int i = 0; i < nodeCount; i++) {
- DiscoveryNode node = new DiscoveryNode("node_" + i, DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ DiscoveryNode node = new DiscoveryNode("node_" + i, LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT);
allNodes[i] = node;
}
diff --git a/core/src/test/java/org/elasticsearch/discovery/DiscoveryModuleTests.java b/core/src/test/java/org/elasticsearch/discovery/DiscoveryModuleTests.java
index 86c3cd91bff..057b54c7a07 100644
--- a/core/src/test/java/org/elasticsearch/discovery/DiscoveryModuleTests.java
+++ b/core/src/test/java/org/elasticsearch/discovery/DiscoveryModuleTests.java
@@ -38,10 +38,8 @@ public class DiscoveryModuleTests extends ModuleTestCase {
}
}
-
public void testRegisterMasterElectionService() {
- Settings settings = Settings.builder().put(Node.NODE_LOCAL_SETTING.getKey(), false).
- put(DiscoveryModule.ZEN_MASTER_SERVICE_TYPE_SETTING.getKey(), "custom").build();
+ Settings settings = Settings.builder().put(DiscoveryModule.ZEN_MASTER_SERVICE_TYPE_SETTING.getKey(), "custom").build();
DiscoveryModule module = new DiscoveryModule(settings);
module.addElectMasterService("custom", DummyMasterElectionService.class);
assertBinding(module, ElectMasterService.class, DummyMasterElectionService.class);
@@ -49,24 +47,20 @@ public class DiscoveryModuleTests extends ModuleTestCase {
}
public void testLoadUnregisteredMasterElectionService() {
- Settings settings = Settings.builder().put(Node.NODE_LOCAL_SETTING.getKey(), false).
- put(DiscoveryModule.ZEN_MASTER_SERVICE_TYPE_SETTING.getKey(), "foobar").build();
+ Settings settings = Settings.builder().put(DiscoveryModule.ZEN_MASTER_SERVICE_TYPE_SETTING.getKey(), "foobar").build();
DiscoveryModule module = new DiscoveryModule(settings);
module.addElectMasterService("custom", DummyMasterElectionService.class);
assertBindingFailure(module, "Unknown master service type [foobar]");
}
public void testRegisterDefaults() {
- boolean local = randomBoolean();
- Settings settings = Settings.builder().put(Node.NODE_LOCAL_SETTING.getKey(), local).build();
+ Settings settings = Settings.EMPTY;
DiscoveryModule module = new DiscoveryModule(settings);
- assertBinding(module, Discovery.class, local ? LocalDiscovery.class : ZenDiscovery.class);
+ assertBinding(module, Discovery.class, ZenDiscovery.class);
}
public void testRegisterDiscovery() {
- boolean local = randomBoolean();
- Settings settings = Settings.builder().put(Node.NODE_LOCAL_SETTING.getKey(), local).
- put(DiscoveryModule.DISCOVERY_TYPE_SETTING.getKey(), "custom").build();
+ Settings settings = Settings.builder().put(DiscoveryModule.DISCOVERY_TYPE_SETTING.getKey(), "custom").build();
DiscoveryModule module = new DiscoveryModule(settings);
module.addDiscoveryType("custom", NoopDiscovery.class);
assertBinding(module, Discovery.class, NoopDiscovery.class);
diff --git a/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java b/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java
index 0187bb28f36..7d74c7ec2f0 100644
--- a/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java
+++ b/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java
@@ -62,6 +62,7 @@ import org.elasticsearch.test.ESIntegTestCase.Scope;
import org.elasticsearch.test.InternalTestCluster;
import org.elasticsearch.test.discovery.ClusterDiscoveryConfiguration;
import org.elasticsearch.test.disruption.BlockClusterStateProcessing;
+import org.elasticsearch.test.disruption.BridgePartition;
import org.elasticsearch.test.disruption.IntermittentLongGCDisruption;
import org.elasticsearch.test.disruption.LongGCDisruption;
import org.elasticsearch.test.disruption.NetworkDelaysPartition;
@@ -169,12 +170,11 @@ public class DiscoveryWithServiceDisruptionsIT extends ESIntegTestCase {
return nodes;
}
- final static Settings DEFAULT_SETTINGS = Settings.builder()
+ static final Settings DEFAULT_SETTINGS = Settings.builder()
.put(FaultDetection.PING_TIMEOUT_SETTING.getKey(), "1s") // for hitting simulated network failures quickly
.put(FaultDetection.PING_RETRIES_SETTING.getKey(), "1") // for hitting simulated network failures quickly
.put("discovery.zen.join_timeout", "10s") // still long to induce failures but to long so test won't time out
.put(DiscoverySettings.PUBLISH_TIMEOUT_SETTING.getKey(), "1s") // <-- for hitting simulated network failures quickly
- .put("http.enabled", false) // just to make test quicker
.build();
@Override
@@ -447,8 +447,7 @@ public class DiscoveryWithServiceDisruptionsIT extends ESIntegTestCase {
final int seconds = !(TEST_NIGHTLY && rarely()) ? 1 : 5;
final String timeout = seconds + "s";
- // TODO: add node count randomizaion
- final List nodes = startCluster(3);
+ final List nodes = startCluster(rarely() ? 5 : 3);
assertAcked(prepareCreate("test")
.setSettings(Settings.builder()
@@ -503,8 +502,8 @@ public class DiscoveryWithServiceDisruptionsIT extends ESIntegTestCase {
}
} catch (InterruptedException e) {
// fine - semaphore interrupt
- } catch (Throwable t) {
- logger.info("unexpected exception in background thread of [{}]", t, node);
+ } catch (AssertionError | Exception e) {
+ logger.info("unexpected exception in background thread of [{}]", e, node);
}
}
});
@@ -540,7 +539,7 @@ public class DiscoveryWithServiceDisruptionsIT extends ESIntegTestCase {
logger.info("stopping disruption");
disruptionScheme.stopDisrupting();
for (String node : internalCluster().getNodeNames()) {
- ensureStableCluster(3, TimeValue.timeValueMillis(disruptionScheme.expectedTimeToHeal().millis() +
+ ensureStableCluster(nodes.size(), TimeValue.timeValueMillis(disruptionScheme.expectedTimeToHeal().millis() +
DISRUPTION_HEALING_OVERHEAD.millis()), true, node);
}
ensureGreen("test");
@@ -548,7 +547,7 @@ public class DiscoveryWithServiceDisruptionsIT extends ESIntegTestCase {
logger.info("validating successful docs");
for (String node : nodes) {
try {
- logger.debug("validating through node [{}]", node);
+ logger.debug("validating through node [{}] ([{}] acked docs)", node, ackedDocs.size());
for (String id : ackedDocs.keySet()) {
assertTrue("doc [" + id + "] indexed via node [" + ackedDocs.get(id) + "] not found",
client(node).prepareGet("test", "type", id).setPreference("_local").get().isExists());
@@ -690,8 +689,8 @@ public class DiscoveryWithServiceDisruptionsIT extends ESIntegTestCase {
}
@Override
- public void onFailure(String source, Throwable t) {
- logger.warn("failure [{}]", t, source);
+ public void onFailure(String source, Exception e) {
+ logger.warn("failure [{}]", e, source);
}
});
@@ -960,7 +959,7 @@ public class DiscoveryWithServiceDisruptionsIT extends ESIntegTestCase {
}
@Override
- public void onFailure(Throwable t) {
+ public void onFailure(Exception e) {
success.set(false);
latch.countDown();
assert false;
@@ -1133,7 +1132,6 @@ public class DiscoveryWithServiceDisruptionsIT extends ESIntegTestCase {
final List allMasterEligibleNodes = masterNodes.get();
ensureStableCluster(3);
assertAcked(prepareCreate("test"));
- ensureYellow();
final String masterNode1 = internalCluster().getMasterName();
NetworkPartition networkPartition = new NetworkUnresponsivePartition(masterNode1, dataNode.get(), random());
@@ -1192,7 +1190,8 @@ public class DiscoveryWithServiceDisruptionsIT extends ESIntegTestCase {
new NetworkUnresponsivePartition(random()),
new NetworkDelaysPartition(random()),
new NetworkDisconnectPartition(random()),
- new SlowClusterStateProcessing(random())
+ new SlowClusterStateProcessing(random()),
+ new BridgePartition(random(), randomBoolean())
);
Collections.shuffle(list, random());
setDisruptionScheme(list.get(0));
diff --git a/core/src/test/java/org/elasticsearch/discovery/zen/ElectMasterServiceTests.java b/core/src/test/java/org/elasticsearch/discovery/zen/ElectMasterServiceTests.java
index 0f93e5d460c..b31b0cbaa55 100644
--- a/core/src/test/java/org/elasticsearch/discovery/zen/ElectMasterServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/discovery/zen/ElectMasterServiceTests.java
@@ -22,7 +22,7 @@ package org.elasticsearch.discovery.zen;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.discovery.zen.elect.ElectMasterService;
import org.elasticsearch.test.ESTestCase;
@@ -46,7 +46,7 @@ public class ElectMasterServiceTests extends ESTestCase {
if (randomBoolean()) {
roles.add(DiscoveryNode.Role.MASTER);
}
- DiscoveryNode node = new DiscoveryNode("n_" + i, "n_" + i, DummyTransportAddress.INSTANCE, Collections.emptyMap(),
+ DiscoveryNode node = new DiscoveryNode("n_" + i, "n_" + i, LocalTransportAddress.buildUnique(), Collections.emptyMap(),
roles, Version.CURRENT);
nodes.add(node);
}
diff --git a/core/src/test/java/org/elasticsearch/discovery/zen/NodeJoinControllerTests.java b/core/src/test/java/org/elasticsearch/discovery/zen/NodeJoinControllerTests.java
index 135352343b6..cd2b4eaf2e4 100644
--- a/core/src/test/java/org/elasticsearch/discovery/zen/NodeJoinControllerTests.java
+++ b/core/src/test/java/org/elasticsearch/discovery/zen/NodeJoinControllerTests.java
@@ -24,7 +24,6 @@ import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.NotMasterException;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
-import org.elasticsearch.cluster.routing.RoutingService;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.FailedRerouteAllocation;
@@ -32,7 +31,6 @@ import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
@@ -41,6 +39,7 @@ import org.elasticsearch.discovery.DiscoverySettings;
import org.elasticsearch.discovery.zen.elect.ElectMasterService;
import org.elasticsearch.discovery.zen.membership.MembershipAction;
import org.elasticsearch.test.ESTestCase;
+import org.elasticsearch.test.VersionUtils;
import org.elasticsearch.test.junit.annotations.TestLogging;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
@@ -50,6 +49,8 @@ import org.junit.Before;
import org.junit.BeforeClass;
import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -68,6 +69,7 @@ import static java.util.Collections.emptySet;
import static java.util.Collections.shuffle;
import static org.elasticsearch.test.ClusterServiceUtils.createClusterService;
import static org.elasticsearch.test.ClusterServiceUtils.setState;
+import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
@@ -99,10 +101,9 @@ public class NodeJoinControllerTests extends ESTestCase {
// make sure we have a master
setState(clusterService, ClusterState.builder(clusterService.state()).nodes(
DiscoveryNodes.builder(initialNodes).masterNodeId(localNode.getId())));
- nodeJoinController = new NodeJoinController(clusterService, new NoopRoutingService(Settings.EMPTY),
- new ElectMasterService(Settings.EMPTY),
- new DiscoverySettings(Settings.EMPTY, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)),
- Settings.EMPTY);
+ nodeJoinController = new NodeJoinController(clusterService, new NoopAllocationService(Settings.EMPTY),
+ new ElectMasterService(Settings.EMPTY), new DiscoverySettings(Settings.EMPTY, new ClusterSettings(Settings.EMPTY,
+ ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)), Settings.EMPTY);
}
@After
@@ -198,17 +199,19 @@ public class NodeJoinControllerTests extends ESTestCase {
final SimpleFuture electionFuture = new SimpleFuture("master election");
final Thread masterElection = new Thread(new AbstractRunnable() {
@Override
- public void onFailure(Throwable t) {
- logger.error("unexpected error from waitToBeElectedAsMaster", t);
- electionFuture.markAsFailed(t);
+ public void onFailure(Exception e) {
+ logger.error("unexpected error from waitToBeElectedAsMaster", e);
+ electionFuture.markAsFailed(e);
}
@Override
protected void doRun() throws Exception {
- nodeJoinController.waitToBeElectedAsMaster(requiredJoins, TimeValue.timeValueHours(30), new NodeJoinController.ElectionCallback() {
+ nodeJoinController.waitToBeElectedAsMaster(requiredJoins, TimeValue.timeValueHours(30),
+ new NodeJoinController.ElectionCallback() {
@Override
public void onElectedAsMaster(ClusterState state) {
- assertThat("callback called with elected as master, but state disagrees", state.nodes().isLocalNodeElectedMaster(), equalTo(true));
+ assertThat("callback called with elected as master, but state disagrees", state.nodes().isLocalNodeElectedMaster(),
+ equalTo(true));
electionFuture.markAsDone();
}
@@ -246,17 +249,19 @@ public class NodeJoinControllerTests extends ESTestCase {
final SimpleFuture electionFuture = new SimpleFuture("master election");
final Thread masterElection = new Thread(new AbstractRunnable() {
@Override
- public void onFailure(Throwable t) {
- logger.error("unexpected error from waitToBeElectedAsMaster", t);
- electionFuture.markAsFailed(t);
+ public void onFailure(Exception e) {
+ logger.error("unexpected error from waitToBeElectedAsMaster", e);
+ electionFuture.markAsFailed(e);
}
@Override
protected void doRun() throws Exception {
- nodeJoinController.waitToBeElectedAsMaster(requiredJoins, TimeValue.timeValueHours(30), new NodeJoinController.ElectionCallback() {
+ nodeJoinController.waitToBeElectedAsMaster(requiredJoins, TimeValue.timeValueHours(30),
+ new NodeJoinController.ElectionCallback() {
@Override
public void onElectedAsMaster(ClusterState state) {
- assertThat("callback called with elected as master, but state disagrees", state.nodes().isLocalNodeElectedMaster(), equalTo(true));
+ assertThat("callback called with elected as master, but state disagrees", state.nodes().isLocalNodeElectedMaster(),
+ equalTo(true));
electionFuture.markAsDone();
}
@@ -298,7 +303,8 @@ public class NodeJoinControllerTests extends ESTestCase {
}
logger.debug("--> asserting master election didn't finish yet");
- assertThat("election finished after [" + initialJoins + "] master nodes but required joins is [" + requiredJoins + "]", electionFuture.isDone(), equalTo(false));
+ assertThat("election finished after [" + initialJoins + "] master nodes but required joins is [" + requiredJoins + "]",
+ electionFuture.isDone(), equalTo(false));
final int finalJoins = requiredJoins - initialJoins + randomInt(5);
nodesToJoin.clear();
@@ -374,7 +380,8 @@ public class NodeJoinControllerTests extends ESTestCase {
nodeJoinController.waitToBeElectedAsMaster(requiredJoins, TimeValue.timeValueMillis(1), new NodeJoinController.ElectionCallback() {
@Override
public void onElectedAsMaster(ClusterState state) {
- assertThat("callback called with elected as master, but state disagrees", state.nodes().isLocalNodeElectedMaster(), equalTo(true));
+ assertThat("callback called with elected as master, but state disagrees", state.nodes().isLocalNodeElectedMaster(),
+ equalTo(true));
latch.countDown();
}
@@ -403,7 +410,7 @@ public class NodeJoinControllerTests extends ESTestCase {
public void testNewClusterStateOnExistingNodeJoin() throws InterruptedException, ExecutionException {
ClusterState state = clusterService.state();
final DiscoveryNodes.Builder nodesBuilder = DiscoveryNodes.builder(state.nodes());
- final DiscoveryNode other_node = new DiscoveryNode("other_node", DummyTransportAddress.INSTANCE,
+ final DiscoveryNode other_node = new DiscoveryNode("other_node", LocalTransportAddress.buildUnique(),
emptyMap(), emptySet(), Version.CURRENT);
nodesBuilder.put(other_node);
setState(clusterService, ClusterState.builder(state).nodes(nodesBuilder));
@@ -425,9 +432,9 @@ public class NodeJoinControllerTests extends ESTestCase {
nodes.add(node);
threads[i] = new Thread(new AbstractRunnable() {
@Override
- public void onFailure(Throwable t) {
- logger.error("unexpected error in join thread", t);
- backgroundExceptions.add(t);
+ public void onFailure(Exception e) {
+ logger.error("unexpected error in join thread", e);
+ backgroundExceptions.add(e);
}
@Override
@@ -468,9 +475,9 @@ public class NodeJoinControllerTests extends ESTestCase {
nodes.add(node);
threads[i] = new Thread(new AbstractRunnable() {
@Override
- public void onFailure(Throwable t) {
- logger.error("unexpected error in join thread", t);
- backgroundExceptions.add(t);
+ public void onFailure(Exception e) {
+ logger.error("unexpected error in join thread", e);
+ backgroundExceptions.add(e);
}
@Override
@@ -492,7 +499,8 @@ public class NodeJoinControllerTests extends ESTestCase {
nodeJoinController.waitToBeElectedAsMaster(requiredJoins, TimeValue.timeValueHours(30), new NodeJoinController.ElectionCallback() {
@Override
public void onElectedAsMaster(ClusterState state) {
- assertThat("callback called with elected as master, but state disagrees", state.nodes().isLocalNodeElectedMaster(), equalTo(true));
+ assertThat("callback called with elected as master, but state disagrees", state.nodes().isLocalNodeElectedMaster(),
+ equalTo(true));
latch.countDown();
}
@@ -515,17 +523,37 @@ public class NodeJoinControllerTests extends ESTestCase {
assertNodesInCurrentState(nodes);
}
+ public void testRejectingJoinWithSameAddressButDifferentId() throws InterruptedException, ExecutionException {
+ ClusterState state = clusterService.state();
+ final DiscoveryNode other_node = new DiscoveryNode("other_node", state.nodes().getLocalNode().getAddress(),
+ emptyMap(), emptySet(), Version.CURRENT);
- static class NoopRoutingService extends RoutingService {
+ ExecutionException e = expectThrows(ExecutionException.class, () -> joinNode(other_node));
+ assertThat(e.getMessage(), containsString("found existing node"));
+ }
- public NoopRoutingService(Settings settings) {
- super(settings, null, new NoopAllocationService(settings));
- }
+ public void testRejectingJoinWithSameIdButDifferentAddress() throws InterruptedException, ExecutionException {
+ ClusterState state = clusterService.state();
+ final DiscoveryNode other_node = new DiscoveryNode(state.nodes().getLocalNode().getId(),
+ new LocalTransportAddress(randomAsciiOfLength(20)), emptyMap(), emptySet(), Version.CURRENT);
- @Override
- protected void performReroute(String reason) {
+ ExecutionException e = expectThrows(ExecutionException.class, () -> joinNode(other_node));
+ assertThat(e.getMessage(), containsString("found existing node"));
+ }
- }
+ public void testJoinWithSameIdSameAddressButDifferentMeta() throws InterruptedException, ExecutionException {
+ ClusterState state = clusterService.state();
+ final DiscoveryNode localNode = state.nodes().getLocalNode();
+ final DiscoveryNode other_node = new DiscoveryNode(
+ randomBoolean() ? localNode.getName() : "other_name",
+ localNode.getId(), localNode.getAddress(),
+ randomBoolean() ? localNode.getAttributes() : Collections.singletonMap("attr", "other"),
+ randomBoolean() ? localNode.getRoles() : new HashSet<>(randomSubsetOf(Arrays.asList(DiscoveryNode.Role.values()))),
+ randomBoolean() ? localNode.getVersion() : VersionUtils.randomVersion(random()));
+
+ joinNode(other_node);
+
+ assertThat(clusterService.localNode(), equalTo(other_node));
}
static class NoopAllocationService extends AllocationService {
@@ -535,12 +563,14 @@ public class NodeJoinControllerTests extends ESTestCase {
}
@Override
- public RoutingAllocation.Result applyStartedShards(ClusterState clusterState, List extends ShardRouting> startedShards, boolean withReroute) {
+ public RoutingAllocation.Result applyStartedShards(ClusterState clusterState, List extends ShardRouting> startedShards,
+ boolean withReroute) {
return new RoutingAllocation.Result(false, clusterState.routingTable(), clusterState.metaData());
}
@Override
- public RoutingAllocation.Result applyFailedShards(ClusterState clusterState, List failedShards) {
+ public RoutingAllocation.Result applyFailedShards(ClusterState clusterState,
+ List failedShards) {
return new RoutingAllocation.Result(false, clusterState.routingTable(), clusterState.metaData());
}
@@ -581,7 +611,7 @@ public class NodeJoinControllerTests extends ESTestCase {
}
}
- final static AtomicInteger joinId = new AtomicInteger();
+ static final AtomicInteger joinId = new AtomicInteger();
private SimpleFuture joinNodeAsync(final DiscoveryNode node) throws InterruptedException {
final SimpleFuture future = new SimpleFuture("join of " + node + " (id [" + joinId.incrementAndGet() + "]");
@@ -596,9 +626,9 @@ public class NodeJoinControllerTests extends ESTestCase {
}
@Override
- public void onFailure(Throwable t) {
- logger.error("unexpected error for {}", t, future);
- future.markAsFailed(t);
+ public void onFailure(Exception e) {
+ logger.error("unexpected error for {}", e, future);
+ future.markAsFailed(e);
}
});
return future;
@@ -608,8 +638,8 @@ public class NodeJoinControllerTests extends ESTestCase {
* creates an object clone of node, so it will be a different object instance
*/
private DiscoveryNode cloneNode(DiscoveryNode node) {
- return new DiscoveryNode(node.getName(), node.getId(), node.getHostName(), node.getHostAddress(), node.getAddress(),
- node.getAttributes(), node.getRoles(), node.getVersion());
+ return new DiscoveryNode(node.getName(), node.getId(), node.getEphemeralId(), node.getHostName(), node.getHostAddress(),
+ node.getAddress(), node.getAttributes(), node.getRoles(), node.getVersion());
}
private void joinNode(final DiscoveryNode node) throws InterruptedException, ExecutionException {
diff --git a/core/src/test/java/org/elasticsearch/discovery/zen/NodeRemovalClusterStateTaskExecutorTests.java b/core/src/test/java/org/elasticsearch/discovery/zen/NodeRemovalClusterStateTaskExecutorTests.java
new file mode 100644
index 00000000000..667ca6fbccb
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/discovery/zen/NodeRemovalClusterStateTaskExecutorTests.java
@@ -0,0 +1,185 @@
+/*
+ * 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.discovery.zen;
+
+import org.elasticsearch.Version;
+import org.elasticsearch.cluster.ClusterName;
+import org.elasticsearch.cluster.ClusterState;
+import org.elasticsearch.cluster.ClusterStateTaskExecutor;
+import org.elasticsearch.cluster.node.DiscoveryNode;
+import org.elasticsearch.cluster.node.DiscoveryNodes;
+import org.elasticsearch.cluster.routing.allocation.AllocationService;
+import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
+import org.elasticsearch.common.logging.ESLogger;
+import org.elasticsearch.common.transport.LocalTransportAddress;
+import org.elasticsearch.discovery.zen.elect.ElectMasterService;
+import org.elasticsearch.test.ESTestCase;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+public class NodeRemovalClusterStateTaskExecutorTests extends ESTestCase {
+
+ public void testRemovingNonExistentNodes() throws Exception {
+ final ZenDiscovery.NodeRemovalClusterStateTaskExecutor executor =
+ new ZenDiscovery.NodeRemovalClusterStateTaskExecutor(null, null, null, logger);
+ final DiscoveryNodes.Builder builder = DiscoveryNodes.builder();
+ final int nodes = randomIntBetween(2, 16);
+ for (int i = 0; i < nodes; i++) {
+ builder.put(node(i));
+ }
+ final ClusterState clusterState = ClusterState.builder(new ClusterName("test")).nodes(builder).build();
+
+ final DiscoveryNodes.Builder removeBuilder = DiscoveryNodes.builder();
+ for (int i = nodes; i < nodes + randomIntBetween(1, 16); i++) {
+ removeBuilder.put(node(i));
+ }
+ final List tasks =
+ StreamSupport
+ .stream(removeBuilder.build().spliterator(), false)
+ .map(node -> new ZenDiscovery.NodeRemovalClusterStateTaskExecutor.Task(node, randomBoolean() ? "left" : "failed"))
+ .collect(Collectors.toList());
+
+ final ClusterStateTaskExecutor.BatchResult result
+ = executor.execute(clusterState, tasks);
+ assertThat(result.resultingState, equalTo(clusterState));
+ }
+
+ public void testNotEnoughMasterNodesAfterRemove() throws Exception {
+ final ElectMasterService electMasterService = mock(ElectMasterService.class);
+ when(electMasterService.hasEnoughMasterNodes(any(Iterable.class))).thenReturn(false);
+
+ final AllocationService allocationService = mock(AllocationService.class);
+
+ final AtomicBoolean rejoined = new AtomicBoolean();
+ final AtomicReference rejoinedClusterState = new AtomicReference<>();
+ final BiFunction rejoin = (cs, r) -> {
+ rejoined.set(true);
+ rejoinedClusterState.set(ClusterState.builder(cs).build());
+ return rejoinedClusterState.get();
+ };
+
+ final AtomicReference remainingNodesClusterState = new AtomicReference<>();
+ final ZenDiscovery.NodeRemovalClusterStateTaskExecutor executor =
+ new ZenDiscovery.NodeRemovalClusterStateTaskExecutor(allocationService, electMasterService, rejoin, logger) {
+ @Override
+ ClusterState remainingNodesClusterState(ClusterState currentState, DiscoveryNodes.Builder remainingNodesBuilder) {
+ remainingNodesClusterState.set(super.remainingNodesClusterState(currentState, remainingNodesBuilder));
+ return remainingNodesClusterState.get();
+ }
+ };
+
+ final DiscoveryNodes.Builder builder = DiscoveryNodes.builder();
+ final int nodes = randomIntBetween(2, 16);
+ final List tasks = new ArrayList<>();
+ // to ensure there is at least one removal
+ boolean first = true;
+ for (int i = 0; i < nodes; i++) {
+ final DiscoveryNode node = node(i);
+ builder.put(node);
+ if (first || randomBoolean()) {
+ tasks.add(new ZenDiscovery.NodeRemovalClusterStateTaskExecutor.Task(node, randomBoolean() ? "left" : "failed"));
+ }
+ first = false;
+ }
+ final ClusterState clusterState = ClusterState.builder(new ClusterName("test")).nodes(builder).build();
+
+ final ClusterStateTaskExecutor.BatchResult result =
+ executor.execute(clusterState, tasks);
+ verify(electMasterService).hasEnoughMasterNodes(eq(remainingNodesClusterState.get().nodes()));
+ verifyNoMoreInteractions(electMasterService);
+
+ // ensure that we did not reroute
+ verifyNoMoreInteractions(allocationService);
+ assertTrue(rejoined.get());
+ assertThat(result.resultingState, equalTo(rejoinedClusterState.get()));
+
+ for (final ZenDiscovery.NodeRemovalClusterStateTaskExecutor.Task task : tasks) {
+ assertNull(result.resultingState.nodes().get(task.node().getId()));
+ }
+ }
+
+ public void testRerouteAfterRemovingNodes() throws Exception {
+ final ElectMasterService electMasterService = mock(ElectMasterService.class);
+ when(electMasterService.hasEnoughMasterNodes(any(Iterable.class))).thenReturn(true);
+
+ final AllocationService allocationService = mock(AllocationService.class);
+ when(allocationService.reroute(any(ClusterState.class), any(String.class))).thenReturn(mock(RoutingAllocation.Result.class));
+
+ final BiFunction rejoin = (cs, r) -> {
+ fail("rejoin should not be invoked");
+ return cs;
+ };
+
+ final AtomicReference remainingNodesClusterState = new AtomicReference<>();
+ final ZenDiscovery.NodeRemovalClusterStateTaskExecutor executor =
+ new ZenDiscovery.NodeRemovalClusterStateTaskExecutor(allocationService, electMasterService, rejoin, logger) {
+ @Override
+ ClusterState remainingNodesClusterState(ClusterState currentState, DiscoveryNodes.Builder remainingNodesBuilder) {
+ remainingNodesClusterState.set(super.remainingNodesClusterState(currentState, remainingNodesBuilder));
+ return remainingNodesClusterState.get();
+ }
+ };
+
+ final DiscoveryNodes.Builder builder = DiscoveryNodes.builder();
+ final int nodes = randomIntBetween(2, 16);
+ final List tasks = new ArrayList<>();
+ // to ensure that there is at least one removal
+ boolean first = true;
+ for (int i = 0; i < nodes; i++) {
+ final DiscoveryNode node = node(i);
+ builder.put(node);
+ if (first || randomBoolean()) {
+ tasks.add(new ZenDiscovery.NodeRemovalClusterStateTaskExecutor.Task(node, randomBoolean() ? "left" : "failed"));
+ }
+ first = false;
+ }
+ final ClusterState clusterState = ClusterState.builder(new ClusterName("test")).nodes(builder).build();
+
+ final ClusterStateTaskExecutor.BatchResult result =
+ executor.execute(clusterState, tasks);
+ verify(electMasterService).hasEnoughMasterNodes(eq(remainingNodesClusterState.get().nodes()));
+ verifyNoMoreInteractions(electMasterService);
+
+ verify(allocationService).reroute(eq(remainingNodesClusterState.get()), any(String.class));
+
+ for (final ZenDiscovery.NodeRemovalClusterStateTaskExecutor.Task task : tasks) {
+ assertNull(result.resultingState.nodes().get(task.node().getId()));
+ }
+ }
+
+ private DiscoveryNode node(final int id) {
+ return new DiscoveryNode(Integer.toString(id), LocalTransportAddress.buildUnique(), Version.CURRENT);
+ }
+
+}
diff --git a/core/src/test/java/org/elasticsearch/discovery/zen/ZenDiscoveryIT.java b/core/src/test/java/org/elasticsearch/discovery/zen/ZenDiscoveryIT.java
index fd0b11eae01..3d0d9ddd8b1 100644
--- a/core/src/test/java/org/elasticsearch/discovery/zen/ZenDiscoveryIT.java
+++ b/core/src/test/java/org/elasticsearch/discovery/zen/ZenDiscoveryIT.java
@@ -261,8 +261,8 @@ public class ZenDiscoveryIT extends ESIntegTestCase {
}
@Override
- public void onFailure(Throwable t) {
- holder.set((IllegalStateException) t);
+ public void onFailure(Exception e) {
+ holder.set((IllegalStateException) e);
}
});
@@ -309,8 +309,8 @@ public class ZenDiscoveryIT extends ESIntegTestCase {
}
@Override
- public void onFailure(Throwable t) {
- holder.set((IllegalStateException) t);
+ public void onFailure(Exception e) {
+ holder.set((IllegalStateException) e);
}
});
diff --git a/core/src/test/java/org/elasticsearch/discovery/zen/ZenDiscoveryUnitTests.java b/core/src/test/java/org/elasticsearch/discovery/zen/ZenDiscoveryUnitTests.java
index a6638eb19cf..9db83f48f0e 100644
--- a/core/src/test/java/org/elasticsearch/discovery/zen/ZenDiscoveryUnitTests.java
+++ b/core/src/test/java/org/elasticsearch/discovery/zen/ZenDiscoveryUnitTests.java
@@ -24,8 +24,7 @@ import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
-import org.elasticsearch.common.Strings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.discovery.zen.ping.ZenPing;
import org.elasticsearch.test.ESTestCase;
@@ -51,9 +50,9 @@ public class ZenDiscoveryUnitTests extends ESTestCase {
ClusterName clusterName = new ClusterName("abc");
DiscoveryNodes.Builder currentNodes = DiscoveryNodes.builder();
- currentNodes.masterNodeId("a").put(new DiscoveryNode("a", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT));
+ currentNodes.masterNodeId("a").put(new DiscoveryNode("a", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT));
DiscoveryNodes.Builder newNodes = DiscoveryNodes.builder();
- newNodes.masterNodeId("a").put(new DiscoveryNode("a", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT));
+ newNodes.masterNodeId("a").put(new DiscoveryNode("a", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT));
ClusterState.Builder currentState = ClusterState.builder(clusterName);
currentState.nodes(currentNodes);
@@ -71,7 +70,7 @@ public class ZenDiscoveryUnitTests extends ESTestCase {
assertFalse("should not ignore, because new state's version is higher to current state's version", shouldIgnoreOrRejectNewClusterState(logger, currentState.build(), newState.build()));
currentNodes = DiscoveryNodes.builder();
- currentNodes.masterNodeId("b").put(new DiscoveryNode("b", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT));
+ currentNodes.masterNodeId("b").put(new DiscoveryNode("b", LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT));
;
// version isn't taken into account, so randomize it to ensure this.
if (randomBoolean()) {
@@ -109,7 +108,7 @@ public class ZenDiscoveryUnitTests extends ESTestCase {
ArrayList allNodes = new ArrayList<>();
for (int i = randomIntBetween(10, 20); i >= 0; i--) {
Set roles = new HashSet<>(randomSubsetOf(Arrays.asList(DiscoveryNode.Role.values())));
- DiscoveryNode node = new DiscoveryNode("node_" + i, "id_" + i, DummyTransportAddress.INSTANCE, Collections.emptyMap(),
+ DiscoveryNode node = new DiscoveryNode("node_" + i, "id_" + i, LocalTransportAddress.buildUnique(), Collections.emptyMap(),
roles, Version.CURRENT);
responses.add(new ZenPing.PingResponse(node, randomBoolean() ? null : node, new ClusterName("test"), randomBoolean()));
allNodes.add(node);
diff --git a/core/src/test/java/org/elasticsearch/discovery/zen/ZenPingTests.java b/core/src/test/java/org/elasticsearch/discovery/zen/ZenPingTests.java
index 8aa5114c387..72674f44e3d 100644
--- a/core/src/test/java/org/elasticsearch/discovery/zen/ZenPingTests.java
+++ b/core/src/test/java/org/elasticsearch/discovery/zen/ZenPingTests.java
@@ -23,7 +23,7 @@ import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.discovery.zen.ping.ZenPing;
import org.elasticsearch.test.ESTestCase;
@@ -42,7 +42,7 @@ public class ZenPingTests extends ESTestCase {
boolean hasJoinedOncePerNode[] = new boolean[nodes.length];
ArrayList pings = new ArrayList<>();
for (int i = 0; i < nodes.length; i++) {
- nodes[i] = new DiscoveryNode("" + i, DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
+ nodes[i] = new DiscoveryNode("" + i, LocalTransportAddress.buildUnique(), emptyMap(), emptySet(), Version.CURRENT);
}
for (int pingCount = scaledRandomIntBetween(10, nodes.length * 10); pingCount > 0; pingCount--) {
diff --git a/core/src/test/java/org/elasticsearch/discovery/zen/ping/unicast/UnicastZenPingIT.java b/core/src/test/java/org/elasticsearch/discovery/zen/ping/unicast/UnicastZenPingIT.java
index f072c5faf8a..6696174c08f 100644
--- a/core/src/test/java/org/elasticsearch/discovery/zen/ping/unicast/UnicastZenPingIT.java
+++ b/core/src/test/java/org/elasticsearch/discovery/zen/ping/unicast/UnicastZenPingIT.java
@@ -20,7 +20,6 @@
package org.elasticsearch.discovery.zen.ping.unicast;
import org.elasticsearch.Version;
-import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
@@ -31,6 +30,7 @@ import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.BigArrays;
+import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
import org.elasticsearch.discovery.zen.elect.ElectMasterService;
import org.elasticsearch.discovery.zen.ping.PingContextProvider;
import org.elasticsearch.discovery.zen.ping.ZenPing;
@@ -39,11 +39,10 @@ import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.VersionUtils;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
+import org.elasticsearch.transport.MockTcpTransport;
import org.elasticsearch.transport.TransportConnectionListener;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.transport.TransportSettings;
-import org.elasticsearch.transport.netty.NettyTransport;
-import org.jboss.netty.util.internal.ConcurrentHashMap;
import java.net.InetSocketAddress;
import java.util.concurrent.ConcurrentMap;
@@ -199,17 +198,12 @@ public class UnicastZenPingIT extends ESTestCase {
private NetworkHandle startServices(Settings settings, ThreadPool threadPool, NetworkService networkService, String nodeId,
Version version) {
- NettyTransport transport = new NettyTransport(settings, threadPool, networkService, BigArrays.NON_RECYCLING_INSTANCE,
- new NamedWriteableRegistry(), new NoneCircuitBreakerService()) {
- @Override
- protected Version getCurrentVersion() {
- return version;
- }
- };
+ MockTcpTransport transport = new MockTcpTransport(settings, threadPool, BigArrays.NON_RECYCLING_INSTANCE,
+ new NoneCircuitBreakerService(), new NamedWriteableRegistry(), networkService, version);
final TransportService transportService = new TransportService(settings, transport, threadPool);
transportService.start();
transportService.acceptIncomingRequests();
- ConcurrentMap counters = new ConcurrentHashMap<>();
+ ConcurrentMap counters = ConcurrentCollections.newConcurrentMap();
transportService.addConnectionListener(new TransportConnectionListener() {
@Override
public void onNodeConnected(DiscoveryNode node) {
diff --git a/core/src/test/java/org/elasticsearch/discovery/zen/publish/PendingClusterStatesQueueTests.java b/core/src/test/java/org/elasticsearch/discovery/zen/publish/PendingClusterStatesQueueTests.java
index ab9aed6ba44..42aa792c95f 100644
--- a/core/src/test/java/org/elasticsearch/discovery/zen/publish/PendingClusterStatesQueueTests.java
+++ b/core/src/test/java/org/elasticsearch/discovery/zen/publish/PendingClusterStatesQueueTests.java
@@ -25,7 +25,7 @@ import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.discovery.zen.publish.PendingClusterStatesQueue.ClusterStateContext;
import org.elasticsearch.test.ESTestCase;
@@ -237,7 +237,7 @@ public class PendingClusterStatesQueueTests extends ESTestCase {
ClusterState state = lastClusterStatePerMaster[masterIndex];
if (state == null) {
state = ClusterState.builder(ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY)).nodes(DiscoveryNodes.builder()
- .put(new DiscoveryNode(masters[masterIndex], DummyTransportAddress.INSTANCE,
+ .put(new DiscoveryNode(masters[masterIndex], LocalTransportAddress.buildUnique(),
emptyMap(), emptySet(),Version.CURRENT)).masterNodeId(masters[masterIndex]).build()
).build();
} else {
@@ -259,8 +259,8 @@ public class PendingClusterStatesQueueTests extends ESTestCase {
}
@Override
- public void onNewClusterStateFailed(Throwable t) {
- failure = t;
+ public void onNewClusterStateFailed(Exception e) {
+ failure = e;
}
}
diff --git a/core/src/test/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateActionTests.java b/core/src/test/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateActionTests.java
index 61374cc0d8f..7d72fa5c4dc 100644
--- a/core/src/test/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateActionTests.java
+++ b/core/src/test/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateActionTests.java
@@ -30,7 +30,6 @@ import org.elasticsearch.cluster.block.ClusterBlocks;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
-import org.elasticsearch.cluster.node.DiscoveryNodeService;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Randomness;
@@ -43,6 +42,7 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.discovery.Discovery;
import org.elasticsearch.discovery.DiscoverySettings;
import org.elasticsearch.discovery.zen.DiscoveryNodesProvider;
+import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.node.Node;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.junit.annotations.TestLogging;
@@ -152,16 +152,16 @@ public class PublishClusterStateActionTests extends ESTestCase {
return createMockNode(name, settings, null);
}
- public MockNode createMockNode(String name, Settings settings, @Nullable ClusterStateListener listener) throws Exception {
- settings = Settings.builder()
+ public MockNode createMockNode(String name, final Settings basSettings, @Nullable ClusterStateListener listener) throws Exception {
+ final Settings settings = Settings.builder()
.put("name", name)
.put(TransportService.TRACE_LOG_INCLUDE_SETTING.getKey(), "", TransportService.TRACE_LOG_EXCLUDE_SETTING.getKey(), "NOTHING")
- .put(settings)
+ .put(basSettings)
.build();
MockTransportService service = buildTransportService(settings);
- DiscoveryNodeService discoveryNodeService = new DiscoveryNodeService(settings);
- DiscoveryNode discoveryNode = discoveryNodeService.buildLocalNode(service.boundAddress().publishAddress());
+ DiscoveryNode discoveryNode = DiscoveryNode.createLocal(settings, service.boundAddress().publishAddress(),
+ NodeEnvironment.generateNodeId(settings));
MockNode node = new MockNode(discoveryNode, service, listener, logger);
node.action = buildPublishClusterStateAction(settings, service, () -> node.clusterState, node);
final CountDownLatch latch = new CountDownLatch(nodes.size() * 2 + 1);
@@ -797,9 +797,9 @@ public class PublishClusterStateActionTests extends ESTestCase {
}
@Override
- public void onNodeAck(DiscoveryNode node, @Nullable Throwable t) {
- if (t != null) {
- errors.add(new Tuple<>(node, t));
+ public void onNodeAck(DiscoveryNode node, @Nullable Exception e) {
+ if (e != null) {
+ errors.add(new Tuple<>(node, e));
}
countDown.countDown();
}
@@ -910,8 +910,8 @@ public class PublishClusterStateActionTests extends ESTestCase {
}
@Override
- public void sendResponse(Throwable error) throws IOException {
- this.error.set(error);
+ public void sendResponse(Exception exception) throws IOException {
+ this.error.set(exception);
assertThat(response.get(), nullValue());
}
diff --git a/core/src/test/java/org/elasticsearch/env/NodeEnvironmentTests.java b/core/src/test/java/org/elasticsearch/env/NodeEnvironmentTests.java
index ad425d8afc9..50e05d97985 100644
--- a/core/src/test/java/org/elasticsearch/env/NodeEnvironmentTests.java
+++ b/core/src/test/java/org/elasticsearch/env/NodeEnvironmentTests.java
@@ -22,7 +22,6 @@ import org.apache.lucene.index.SegmentInfos;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.LuceneTestCase;
-import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.io.PathUtils;
@@ -48,12 +47,11 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFileExists;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFileNotExists;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
+import static org.hamcrest.Matchers.not;
@LuceneTestCase.SuppressFileSystems("ExtrasFS") // TODO: fix test to allow extras
public class NodeEnvironmentTests extends ESTestCase {
@@ -269,9 +267,9 @@ public class NodeEnvironmentTests extends ESTestCase {
if (randomBoolean()) {
Thread t = new Thread(new AbstractRunnable() {
@Override
- public void onFailure(Throwable t) {
- logger.error("unexpected error", t);
- threadException.set(t);
+ public void onFailure(Exception e) {
+ logger.error("unexpected error", e);
+ threadException.set(e);
latch.countDown();
blockLatch.countDown();
}
@@ -392,7 +390,7 @@ public class NodeEnvironmentTests extends ESTestCase {
env.close();
NodeEnvironment env2 = newNodeEnvironment(dataPaths, "/tmp",
- Settings.builder().put(NodeEnvironment.ADD_NODE_ID_TO_CUSTOM_PATH.getKey(), false).build());
+ Settings.builder().put(NodeEnvironment.ADD_NODE_LOCK_ID_TO_CUSTOM_PATH.getKey(), false).build());
assertThat(env2.availableShardPaths(sid), equalTo(env2.availableShardPaths(sid)));
assertThat(env2.resolveCustomLocation(s2, sid), equalTo(PathUtils.get("/tmp/foo/" + index.getUUID() + "/0")));
@@ -450,6 +448,27 @@ public class NodeEnvironmentTests extends ESTestCase {
}
}
+ public void testPersistentNodeId() throws IOException {
+ String[] paths = tmpPaths();
+ NodeEnvironment env = newNodeEnvironment(paths, Settings.builder()
+ .put("node.local_storage", false)
+ .put("node.master", false)
+ .put("node.data", false)
+ .build());
+ String nodeID = env.nodeId();
+ env.close();
+ env = newNodeEnvironment(paths, Settings.EMPTY);
+ assertThat("previous node didn't have local storage enabled, id should change", env.nodeId(), not(equalTo(nodeID)));
+ nodeID = env.nodeId();
+ env.close();
+ env = newNodeEnvironment(paths, Settings.EMPTY);
+ assertThat(env.nodeId(), equalTo(nodeID));
+ env.close();
+ env = newNodeEnvironment(Settings.EMPTY);
+ assertThat(env.nodeId(), not(equalTo(nodeID)));
+ env.close();
+ }
+
/** Converts an array of Strings to an array of Paths, adding an additional child if specified */
private Path[] stringsToPaths(String[] strings, String additional) {
Path[] locations = new Path[strings.length];
diff --git a/core/src/test/java/org/elasticsearch/fieldstats/FieldStatsIntegrationIT.java b/core/src/test/java/org/elasticsearch/fieldstats/FieldStatsIntegrationIT.java
index e87cc5f6571..6240a13a0bd 100644
--- a/core/src/test/java/org/elasticsearch/fieldstats/FieldStatsIntegrationIT.java
+++ b/core/src/test/java/org/elasticsearch/fieldstats/FieldStatsIntegrationIT.java
@@ -169,18 +169,25 @@ public class FieldStatsIntegrationIT extends ESIntegTestCase {
assertThat(response.getAllFieldStats().get("byte").getMinValue(), equalTo(minByte));
assertThat(response.getAllFieldStats().get("byte").getMaxValue(), equalTo(maxByte));
+ assertThat(response.getAllFieldStats().get("byte").getDisplayType(), equalTo("integer"));
assertThat(response.getAllFieldStats().get("short").getMinValue(), equalTo(minShort));
assertThat(response.getAllFieldStats().get("short").getMaxValue(), equalTo(maxShort));
+ assertThat(response.getAllFieldStats().get("short").getDisplayType(), equalTo("integer"));
assertThat(response.getAllFieldStats().get("integer").getMinValue(), equalTo(minInt));
assertThat(response.getAllFieldStats().get("integer").getMaxValue(), equalTo(maxInt));
+ assertThat(response.getAllFieldStats().get("integer").getDisplayType(), equalTo("integer"));
assertThat(response.getAllFieldStats().get("long").getMinValue(), equalTo(minLong));
assertThat(response.getAllFieldStats().get("long").getMaxValue(), equalTo(maxLong));
+ assertThat(response.getAllFieldStats().get("long").getDisplayType(), equalTo("integer"));
assertThat(response.getAllFieldStats().get("half_float").getMinValue(), equalTo(minHalfFloat));
assertThat(response.getAllFieldStats().get("half_float").getMaxValue(), equalTo(maxHalfFloat));
+ assertThat(response.getAllFieldStats().get("half_float").getDisplayType(), equalTo("float"));
assertThat(response.getAllFieldStats().get("float").getMinValue(), equalTo(minFloat));
assertThat(response.getAllFieldStats().get("float").getMaxValue(), equalTo(maxFloat));
+ assertThat(response.getAllFieldStats().get("float").getDisplayType(), equalTo("float"));
assertThat(response.getAllFieldStats().get("double").getMinValue(), equalTo(minDouble));
assertThat(response.getAllFieldStats().get("double").getMaxValue(), equalTo(maxDouble));
+ assertThat(response.getAllFieldStats().get("double").getDisplayType(), equalTo("float"));
}
public void testFieldStatsIndexLevel() throws Exception {
@@ -207,6 +214,8 @@ public class FieldStatsIntegrationIT extends ESIntegTestCase {
assertThat(response.getIndicesMergedFieldStats().size(), equalTo(1));
assertThat(response.getIndicesMergedFieldStats().get("_all").get("value").getMinValue(), equalTo(-10L));
assertThat(response.getIndicesMergedFieldStats().get("_all").get("value").getMaxValue(), equalTo(300L));
+ assertThat(response.getIndicesMergedFieldStats().get("_all").get("value").getDisplayType(),
+ equalTo("integer"));
// Level: cluster
response = client().prepareFieldStats().setFields("value").setLevel("cluster").get();
@@ -216,6 +225,8 @@ public class FieldStatsIntegrationIT extends ESIntegTestCase {
assertThat(response.getIndicesMergedFieldStats().size(), equalTo(1));
assertThat(response.getIndicesMergedFieldStats().get("_all").get("value").getMinValue(), equalTo(-10L));
assertThat(response.getIndicesMergedFieldStats().get("_all").get("value").getMaxValue(), equalTo(300L));
+ assertThat(response.getIndicesMergedFieldStats().get("_all").get("value").getDisplayType(),
+ equalTo("integer"));
// Level: indices
response = client().prepareFieldStats().setFields("value").setLevel("indices").get();
@@ -228,6 +239,8 @@ public class FieldStatsIntegrationIT extends ESIntegTestCase {
assertThat(response.getIndicesMergedFieldStats().get("test2").get("value").getMaxValue(), equalTo(200L));
assertThat(response.getIndicesMergedFieldStats().get("test3").get("value").getMinValue(), equalTo(201L));
assertThat(response.getIndicesMergedFieldStats().get("test3").get("value").getMaxValue(), equalTo(300L));
+ assertThat(response.getIndicesMergedFieldStats().get("test3").get("value").getDisplayType(),
+ equalTo("integer"));
// Illegal level option:
try {
@@ -259,7 +272,7 @@ public class FieldStatsIntegrationIT extends ESIntegTestCase {
assertThat(response.getIndicesMergedFieldStats().get("_all").size(), equalTo(0));
assertThat(response.getConflicts().size(), equalTo(1));
assertThat(response.getConflicts().get("value"),
- equalTo("Field [value] of type [whole-number] conflicts with existing field of type [text] " +
+ equalTo("Field [value] of type [integer] conflicts with existing field of type [string] " +
"in other index."));
response = client().prepareFieldStats().setFields("value").setLevel("indices").get();
@@ -296,7 +309,7 @@ public class FieldStatsIntegrationIT extends ESIntegTestCase {
assertThat(response.getIndicesMergedFieldStats().get("_all").get("value2").getMaxValue(), equalTo(1L));
assertThat(response.getConflicts().size(), equalTo(1));
assertThat(response.getConflicts().get("value"),
- equalTo("Field [value] of type [whole-number] conflicts with existing field of type [text] " +
+ equalTo("Field [value] of type [integer] conflicts with existing field of type [string] " +
"in other index."));
response = client().prepareFieldStats().setFields("value", "value2").setLevel("indices").get();
@@ -310,6 +323,8 @@ public class FieldStatsIntegrationIT extends ESIntegTestCase {
equalTo(new BytesRef("a")));
assertThat(response.getIndicesMergedFieldStats().get("test2").get("value").getMaxValue(),
equalTo(new BytesRef("b")));
+ assertThat(response.getIndicesMergedFieldStats().get("test2").get("value").getDisplayType(),
+ equalTo("string"));
}
public void testFieldStatsFiltering() throws Exception {
diff --git a/core/src/test/java/org/elasticsearch/fieldstats/FieldStatsTests.java b/core/src/test/java/org/elasticsearch/fieldstats/FieldStatsTests.java
index 20db1bf20c4..bfee11f7f0e 100644
--- a/core/src/test/java/org/elasticsearch/fieldstats/FieldStatsTests.java
+++ b/core/src/test/java/org/elasticsearch/fieldstats/FieldStatsTests.java
@@ -89,6 +89,8 @@ public class FieldStatsTests extends ESSingleNodeTestCase {
equalTo(String.format(Locale.ENGLISH, "%03d", 0)));
assertThat(result.getAllFieldStats().get("field").getMaxValueAsString(),
equalTo(String.format(Locale.ENGLISH, "%03d", 10)));
+ assertThat(result.getAllFieldStats().get("field").getDisplayType(),
+ equalTo("string"));
}
public void testDouble() {
@@ -106,6 +108,7 @@ public class FieldStatsTests extends ESSingleNodeTestCase {
assertThat(result.getAllFieldStats().get(fieldName).getMinValue(), equalTo(-1d));
assertThat(result.getAllFieldStats().get(fieldName).getMaxValue(), equalTo(9d));
assertThat(result.getAllFieldStats().get(fieldName).getMinValueAsString(), equalTo(Double.toString(-1)));
+ assertThat(result.getAllFieldStats().get(fieldName).getDisplayType(), equalTo("float"));
}
public void testHalfFloat() {
@@ -124,6 +127,7 @@ public class FieldStatsTests extends ESSingleNodeTestCase {
assertThat(result.getAllFieldStats().get(fieldName).getMaxValue(), equalTo(9d));
assertThat(result.getAllFieldStats().get(fieldName).getMinValueAsString(), equalTo(Float.toString(-1)));
assertThat(result.getAllFieldStats().get(fieldName).getMaxValueAsString(), equalTo(Float.toString(9)));
+ assertThat(result.getAllFieldStats().get(fieldName).getDisplayType(), equalTo("float"));
}
public void testFloat() {
@@ -169,6 +173,11 @@ public class FieldStatsTests extends ESSingleNodeTestCase {
equalTo(java.lang.Long.toString(max)));
assertThat(result.getAllFieldStats().get(fieldName).isSearchable(), equalTo(true));
assertThat(result.getAllFieldStats().get(fieldName).isAggregatable(), equalTo(true));
+ if (fieldType.equals("float") || fieldType.equals("double") || fieldType.equals("half-float")) {
+ assertThat(result.getAllFieldStats().get(fieldName).getDisplayType(), equalTo("float"));
+ } else {
+ assertThat(result.getAllFieldStats().get(fieldName).getDisplayType(), equalTo("integer"));
+ }
client().admin().indices().prepareDelete("test").get();
client().admin().indices().prepareDelete("test1").get();
@@ -191,6 +200,7 @@ public class FieldStatsTests extends ESSingleNodeTestCase {
assertThat(stat.getSumTotalTermFreq(), equalTo(4L));
assertThat(stat.isSearchable(), equalTo(true));
assertThat(stat.isAggregatable(), equalTo(false));
+ assertThat(stat.getDisplayType(), equalTo("integer"));
}
public void testMerge_notAvailable() {
@@ -209,6 +219,7 @@ public class FieldStatsTests extends ESSingleNodeTestCase {
assertThat(stat.getSumTotalTermFreq(), equalTo(-1L));
assertThat(stat.isSearchable(), equalTo(true));
assertThat(stat.isAggregatable(), equalTo(true));
+ assertThat(stat.getDisplayType(), equalTo("integer"));
stats.add(new FieldStats.Long(1, -1L, -1L, -1L, true, true, 1L, 1L));
stat = stats.remove(0);
@@ -221,6 +232,7 @@ public class FieldStatsTests extends ESSingleNodeTestCase {
assertThat(stat.getSumTotalTermFreq(), equalTo(-1L));
assertThat(stat.isSearchable(), equalTo(true));
assertThat(stat.isAggregatable(), equalTo(true));
+ assertThat(stat.getDisplayType(), equalTo("integer"));
}
public void testNumberFiltering() {
@@ -350,6 +362,8 @@ public class FieldStatsTests extends ESSingleNodeTestCase {
equalTo(dateTime1Str));
assertThat(response.getIndicesMergedFieldStats().get("test2").get("value").getMinValueAsString(),
equalTo(dateTime2Str));
+ assertThat(response.getIndicesMergedFieldStats().get("test2").get("value").getDisplayType(),
+ equalTo("date"));
response = client().prepareFieldStats()
.setFields("value")
@@ -370,6 +384,8 @@ public class FieldStatsTests extends ESSingleNodeTestCase {
equalTo(dateTime1.getMillis()));
assertThat(response.getIndicesMergedFieldStats().get("test1").get("value").getMinValueAsString(),
equalTo(dateTime1Str));
+ assertThat(response.getIndicesMergedFieldStats().get("test1").get("value").getDisplayType(),
+ equalTo("date"));
response = client().prepareFieldStats()
.setFields("value")
@@ -402,6 +418,8 @@ public class FieldStatsTests extends ESSingleNodeTestCase {
equalTo(dateTime2.getMillis()));
assertThat(response.getIndicesMergedFieldStats().get("test2").get("value").getMinValueAsString(),
equalTo(dateTime2Str));
+ assertThat(response.getIndicesMergedFieldStats().get("test2").get("value").getDisplayType(),
+ equalTo("date"));
response = client().prepareFieldStats()
.setFields("value")
@@ -417,6 +435,8 @@ public class FieldStatsTests extends ESSingleNodeTestCase {
equalTo(dateTime1Str));
assertThat(response.getIndicesMergedFieldStats().get("test2").get("value").getMinValueAsString(),
equalTo(dateTime2Str));
+ assertThat(response.getIndicesMergedFieldStats().get("test2").get("value").getDisplayType(),
+ equalTo("date"));
response = client().prepareFieldStats()
.setFields("value")
@@ -432,6 +452,8 @@ public class FieldStatsTests extends ESSingleNodeTestCase {
equalTo(dateTime1Str));
assertThat(response.getIndicesMergedFieldStats().get("test2").get("value").getMinValueAsString(),
equalTo(dateTime2Str));
+ assertThat(response.getIndicesMergedFieldStats().get("test2").get("value").getDisplayType(),
+ equalTo("date"));
}
public void testDateFiltering_optionalFormat() {
@@ -453,6 +475,8 @@ public class FieldStatsTests extends ESSingleNodeTestCase {
assertThat(response.getIndicesMergedFieldStats().size(), equalTo(1));
assertThat(response.getIndicesMergedFieldStats().get("test2").get("value").getMinValueAsString(),
equalTo("2014-01-02T00:00:00.000Z"));
+ assertThat(response.getIndicesMergedFieldStats().get("test2").get("value").getDisplayType(),
+ equalTo("date"));
try {
client().prepareFieldStats()
@@ -487,6 +511,6 @@ public class FieldStatsTests extends ESSingleNodeTestCase {
.get();
assertThat(response.getAllFieldStats().size(), equalTo(1));
assertThat(response.getAllFieldStats().get("_type").isSearchable(), equalTo(true));
- // assertThat(response.getAllFieldStats().get("_type").isAggregatable(), equalTo(true));
+ assertThat(response.getAllFieldStats().get("_type").isAggregatable(), equalTo(true));
}
}
diff --git a/core/src/test/java/org/elasticsearch/gateway/AsyncShardFetchTests.java b/core/src/test/java/org/elasticsearch/gateway/AsyncShardFetchTests.java
index 948f4820439..092e6eaff8a 100644
--- a/core/src/test/java/org/elasticsearch/gateway/AsyncShardFetchTests.java
+++ b/core/src/test/java/org/elasticsearch/gateway/AsyncShardFetchTests.java
@@ -24,7 +24,7 @@ import org.elasticsearch.action.support.nodes.BaseNodeResponse;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.logging.Loggers;
-import org.elasticsearch.common.transport.DummyTransportAddress;
+import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.TestThreadPool;
@@ -45,11 +45,11 @@ import static org.hamcrest.Matchers.sameInstance;
/**
*/
public class AsyncShardFetchTests extends ESTestCase {
- private final DiscoveryNode node1 = new DiscoveryNode("node1", DummyTransportAddress.INSTANCE, Collections.emptyMap(),
+ private final DiscoveryNode node1 = new DiscoveryNode("node1", LocalTransportAddress.buildUnique(), Collections.emptyMap(),
Collections.singleton(DiscoveryNode.Role.DATA), Version.CURRENT);
private final Response response1 = new Response(node1);
private final Throwable failure1 = new Throwable("simulated failure 1");
- private final DiscoveryNode node2 = new DiscoveryNode("node2", DummyTransportAddress.INSTANCE, Collections.emptyMap(),
+ private final DiscoveryNode node2 = new DiscoveryNode("node2", LocalTransportAddress.buildUnique(), Collections.emptyMap(),
Collections.singleton(DiscoveryNode.Role.DATA), Version.CURRENT);
private final Response response2 = new Response(node2);
private final Throwable failure2 = new Throwable("simulate failure 2");
@@ -292,7 +292,7 @@ public class AsyncShardFetchTests extends ESTestCase {
} else {
processAsyncFetch(shardId, Collections.singletonList(entry.response), null);
}
- } catch (Throwable e) {
+ } catch (Exception e) {
logger.error("unexpected failure", e);
} finally {
if (entry != null) {
diff --git a/core/src/test/java/org/elasticsearch/gateway/GatewayIndexStateIT.java b/core/src/test/java/org/elasticsearch/gateway/GatewayIndexStateIT.java
index 129495ea15e..7ea916f4a52 100644
--- a/core/src/test/java/org/elasticsearch/gateway/GatewayIndexStateIT.java
+++ b/core/src/test/java/org/elasticsearch/gateway/GatewayIndexStateIT.java
@@ -24,6 +24,7 @@ import org.elasticsearch.Version;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.action.get.GetResponse;
+import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.cluster.ClusterState;
@@ -76,9 +77,6 @@ public class GatewayIndexStateIT extends ESIntegTestCase {
.field("required", true).endObject().endObject().endObject())
.execute().actionGet();
- logger.info("--> waiting for yellow status");
- ensureYellow();
-
logger.info("--> verify meta _routing required exists");
MappingMetaData mappingMd = client().admin().cluster().prepareState().execute().actionGet().getState().metaData()
.index("test").mapping("type1");
@@ -205,7 +203,7 @@ public class GatewayIndexStateIT extends ESIntegTestCase {
internalCluster().startNode(Settings.builder().put(Node.NODE_DATA_SETTING.getKey(), false).build());
logger.info("--> create an index");
- client().admin().indices().prepareCreate("test").execute().actionGet();
+ client().admin().indices().prepareCreate("test").setWaitForActiveShards(ActiveShardCount.NONE).execute().actionGet();
logger.info("--> closing master node");
internalCluster().closeNonSharedNodes(false);
@@ -233,9 +231,6 @@ public class GatewayIndexStateIT extends ESIntegTestCase {
logger.info("--> create an index");
client().admin().indices().prepareCreate("test").execute().actionGet();
- logger.info("--> waiting for test index to be created");
- ensureYellow();
-
client().prepareIndex("test", "type1").setSource("field1", "value1").setTimeout("100ms").execute().actionGet();
}
@@ -346,7 +341,7 @@ public class GatewayIndexStateIT extends ESIntegTestCase {
logger.info("--> created temp data path for shadow replicas [{}]", dataPath);
logger.info("--> starting a cluster with " + numNodes + " nodes");
final Settings nodeSettings = Settings.builder()
- .put("node.add_id_to_custom_path", false)
+ .put("node.add_lock_id_to_custom_path", false)
.put(Environment.PATH_SHARED_DATA_SETTING.getKey(), dataPath.toString())
.put("index.store.fs.fs_lock", randomFrom("native", "simple"))
.build();
@@ -426,7 +421,7 @@ public class GatewayIndexStateIT extends ESIntegTestCase {
// this one is not validated ahead of time and breaks allocation
.put("index.analysis.filter.myCollator.type", "icu_collation")
).build();
- IndexMetaData.FORMAT.write(brokenMeta, brokenMeta.getVersion(), services.indexPaths(brokenMeta.getIndex()));
+ IndexMetaData.FORMAT.write(brokenMeta, services.indexPaths(brokenMeta.getIndex()));
}
internalCluster().fullRestart();
// ensureGreen(closedIndex) waits for the index to show up in the metadata
@@ -483,7 +478,7 @@ public class GatewayIndexStateIT extends ESIntegTestCase {
for (NodeEnvironment services : internalCluster().getInstances(NodeEnvironment.class)) {
IndexMetaData brokenMeta = IndexMetaData.builder(metaData).settings(metaData.getSettings()
.filter((s) -> "index.analysis.analyzer.test.tokenizer".equals(s) == false)).build();
- IndexMetaData.FORMAT.write(brokenMeta, brokenMeta.getVersion(), services.indexPaths(brokenMeta.getIndex()));
+ IndexMetaData.FORMAT.write(brokenMeta, services.indexPaths(brokenMeta.getIndex()));
}
internalCluster().fullRestart();
// ensureGreen(closedIndex) waits for the index to show up in the metadata
@@ -521,7 +516,7 @@ public class GatewayIndexStateIT extends ESIntegTestCase {
MetaData brokenMeta = MetaData.builder(metaData).persistentSettings(Settings.builder()
.put(metaData.persistentSettings()).put("this.is.unknown", true)
.put(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES_SETTING.getKey(), "broken").build()).build();
- MetaData.FORMAT.write(brokenMeta, metaData.version(), nodeEnv.nodeDataPaths());
+ MetaData.FORMAT.write(brokenMeta, nodeEnv.nodeDataPaths());
}
internalCluster().fullRestart();
ensureYellow("test"); // wait for state recovery
diff --git a/core/src/test/java/org/elasticsearch/gateway/GatewayServiceTests.java b/core/src/test/java/org/elasticsearch/gateway/GatewayServiceTests.java
index 4f65c5fafdd..d2085ab9147 100644
--- a/core/src/test/java/org/elasticsearch/gateway/GatewayServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/gateway/GatewayServiceTests.java
@@ -19,7 +19,6 @@
package org.elasticsearch.gateway;
-import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
@@ -36,11 +35,8 @@ public class GatewayServiceTests extends ESTestCase {
ClusterService clusterService = new ClusterService(Settings.builder().put("cluster.name", "GatewayServiceTests").build(),
new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS),
null);
- return new GatewayService(Settings.builder()
- .put("http.enabled", "false")
- .put("discovery.type", "local")
- .put(settings.build()).build(),
- null, clusterService, null, null, null, null, new NoopDiscovery(), null, null);
+ return new GatewayService(settings.build(),
+ null, clusterService, null, null, null, new NoopDiscovery(), null, null);
}
public void testDefaultRecoverAfterTime() throws IOException {
diff --git a/core/src/test/java/org/elasticsearch/gateway/MetaDataStateFormatTests.java b/core/src/test/java/org/elasticsearch/gateway/MetaDataStateFormatTests.java
index 41eba406009..4cf505d839a 100644
--- a/core/src/test/java/org/elasticsearch/gateway/MetaDataStateFormatTests.java
+++ b/core/src/test/java/org/elasticsearch/gateway/MetaDataStateFormatTests.java
@@ -104,7 +104,7 @@ public class MetaDataStateFormatTests extends ESTestCase {
Format format = new Format(randomFrom(XContentType.values()), "foo-");
DummyState state = new DummyState(randomRealisticUnicodeOfCodepointLengthBetween(1, 1000), randomInt(), randomLong(), randomDouble(), randomBoolean());
int version = between(0, Integer.MAX_VALUE/2);
- format.write(state, version, dirs);
+ format.write(state, dirs);
for (Path file : dirs) {
Path[] list = content("*", file);
assertEquals(list.length, 1);
@@ -119,7 +119,7 @@ public class MetaDataStateFormatTests extends ESTestCase {
}
final int version2 = between(version, Integer.MAX_VALUE);
DummyState state2 = new DummyState(randomRealisticUnicodeOfCodepointLengthBetween(1, 1000), randomInt(), randomLong(), randomDouble(), randomBoolean());
- format.write(state2, version2, dirs);
+ format.write(state2, dirs);
for (Path file : dirs) {
Path[] list = content("*", file);
@@ -146,7 +146,7 @@ public class MetaDataStateFormatTests extends ESTestCase {
Format format = new Format(randomFrom(XContentType.values()), "foo-");
DummyState state = new DummyState(randomRealisticUnicodeOfCodepointLengthBetween(1, 1000), randomInt(), randomLong(), randomDouble(), randomBoolean());
int version = between(0, Integer.MAX_VALUE/2);
- format.write(state, version, dirs);
+ format.write(state, dirs);
for (Path file : dirs) {
Path[] list = content("*", file);
assertEquals(list.length, 1);
@@ -170,7 +170,7 @@ public class MetaDataStateFormatTests extends ESTestCase {
Format format = new Format(randomFrom(XContentType.values()), "foo-");
DummyState state = new DummyState(randomRealisticUnicodeOfCodepointLengthBetween(1, 1000), randomInt(), randomLong(), randomDouble(), randomBoolean());
int version = between(0, Integer.MAX_VALUE/2);
- format.write(state, version, dirs);
+ format.write(state, dirs);
for (Path file : dirs) {
Path[] list = content("*", file);
assertEquals(list.length, 1);
@@ -261,7 +261,7 @@ public class MetaDataStateFormatTests extends ESTestCase {
}
}
for (int j = numLegacy; j < numStates; j++) {
- format.write(meta.get(j), j, dirs[i]);
+ format.write(meta.get(j), dirs[i]);
if (randomBoolean() && (j < numStates - 1 || dirs.length > 0 && i != 0)) { // corrupt a file that we do not necessarily need here....
Path file = dirs[i].resolve(MetaDataStateFormat.STATE_DIR_NAME).resolve("global-" + j + ".st");
corruptedFiles.add(file);
diff --git a/core/src/test/java/org/elasticsearch/gateway/MetaDataWriteDataNodesIT.java b/core/src/test/java/org/elasticsearch/gateway/MetaDataWriteDataNodesIT.java
index 4999ef5eac5..795046ba10c 100644
--- a/core/src/test/java/org/elasticsearch/gateway/MetaDataWriteDataNodesIT.java
+++ b/core/src/test/java/org/elasticsearch/gateway/MetaDataWriteDataNodesIT.java
@@ -161,8 +161,8 @@ public class MetaDataWriteDataNodesIT extends ESIntegTestCase {
logger.info("checking if meta state exists...");
try {
assertTrue("Expecting meta state of index " + indexName + " to be on node " + nodeName, getIndicesMetaDataOnNode(nodeName).containsKey(indexName));
- } catch (Throwable t) {
- logger.info("failed to load meta state", t);
+ } catch (Exception e) {
+ logger.info("failed to load meta state", e);
fail("could not load meta state");
}
}
diff --git a/core/src/test/java/org/elasticsearch/gateway/PrimaryShardAllocatorTests.java b/core/src/test/java/org/elasticsearch/gateway/PrimaryShardAllocatorTests.java
index 96e360550af..e86fa6f014b 100644
--- a/core/src/test/java/org/elasticsearch/gateway/PrimaryShardAllocatorTests.java
+++ b/core/src/test/java/org/elasticsearch/gateway/PrimaryShardAllocatorTests.java
@@ -21,10 +21,12 @@ package org.elasticsearch.gateway;
import org.apache.lucene.index.CorruptIndexException;
import org.elasticsearch.Version;
+import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
+import org.elasticsearch.cluster.health.ClusterHealthStatus;
+import org.elasticsearch.cluster.health.ClusterStateHealth;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
-import org.elasticsearch.snapshots.SnapshotId;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RestoreSource;
@@ -41,6 +43,7 @@ import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.ShardStateMetaData;
import org.elasticsearch.snapshots.Snapshot;
+import org.elasticsearch.snapshots.SnapshotId;
import org.elasticsearch.test.ESAllocationTestCase;
import org.junit.Before;
@@ -50,6 +53,7 @@ import java.util.Map;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.lessThanOrEqualTo;
/**
*/
@@ -77,6 +81,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
assertThat(changed, equalTo(false));
assertThat(allocation.routingNodes().unassigned().size(), equalTo(1));
assertThat(allocation.routingNodes().unassigned().iterator().next().shardId(), equalTo(shardId));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -90,9 +95,10 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
allocation = routingAllocationWithOnePrimaryNoReplicas(yesAllocationDeciders(), false, Version.V_2_1_0);
}
boolean changed = testAllocator.allocateUnassigned(allocation);
- assertThat(changed, equalTo(false));
+ assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().size(), equalTo(1));
assertThat(allocation.routingNodes().unassigned().ignored().get(0).shardId(), equalTo(shardId));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -108,9 +114,10 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
}
testAllocator.addData(node1, ShardStateMetaData.NO_VERSION, null, randomBoolean());
boolean changed = testAllocator.allocateUnassigned(allocation);
- assertThat(changed, equalTo(false));
+ assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().size(), equalTo(1));
assertThat(allocation.routingNodes().unassigned().ignored().get(0).shardId(), equalTo(shardId));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -120,9 +127,10 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
RoutingAllocation allocation = routingAllocationWithOnePrimaryNoReplicas(yesAllocationDeciders(), false, Version.CURRENT, "id2");
testAllocator.addData(node1, ShardStateMetaData.NO_VERSION, "id1", randomBoolean());
boolean changed = testAllocator.allocateUnassigned(allocation);
- assertThat(changed, equalTo(false));
+ assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().size(), equalTo(1));
assertThat(allocation.routingNodes().unassigned().ignored().get(0).shardId(), equalTo(shardId));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -137,6 +145,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
assertThat(allocation.routingNodes().unassigned().ignored().isEmpty(), equalTo(true));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).size(), equalTo(1));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).get(0).currentNodeId(), equalTo(node1.getId()));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -152,9 +161,10 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
testAllocator.addData(node1, 3, null, randomBoolean(), new CorruptIndexException("test", "test"));
}
boolean changed = testAllocator.allocateUnassigned(allocation);
- assertThat(changed, equalTo(false));
+ assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().size(), equalTo(1));
assertThat(allocation.routingNodes().unassigned().ignored().get(0).shardId(), equalTo(shardId));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -179,6 +189,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
// check that allocation id is reused
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).get(0).allocationId().getId(), equalTo("allocId1"));
}
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -197,6 +208,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).size(), equalTo(1));
DiscoveryNode allocatedNode = node1HasPrimaryShard ? node1 : node2;
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).get(0).currentNodeId(), equalTo(allocatedNode.getId()));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -213,9 +225,10 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
testAllocator.addData(node1, 3, null, randomBoolean());
}
boolean changed = testAllocator.allocateUnassigned(allocation);
- assertThat(changed, equalTo(false));
+ assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().size(), equalTo(1));
assertThat(allocation.routingNodes().unassigned().ignored().get(0).shardId(), equalTo(shardId));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -236,6 +249,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
assertThat(allocation.routingNodes().unassigned().ignored().isEmpty(), equalTo(true));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).size(), equalTo(1));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).get(0).currentNodeId(), equalTo(node1.getId()));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -249,6 +263,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
assertThat(allocation.routingNodes().unassigned().ignored().isEmpty(), equalTo(true));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).size(), equalTo(1));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).get(0).currentNodeId(), equalTo(node2.getId()));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -268,6 +283,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).size(), equalTo(1));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).get(0).currentNodeId(), equalTo(node2.getId()));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).get(0).allocationId().getId(), equalTo("some allocId"));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -285,6 +301,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().isEmpty(), equalTo(true));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).size(), equalTo(1));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -299,8 +316,9 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
RoutingAllocation allocation = getRestoreRoutingAllocation(throttleAllocationDeciders(), clusterHasActiveAllocationIds);
testAllocator.addData(node1, legacyVersion, allocationId, randomBoolean());
boolean changed = testAllocator.allocateUnassigned(allocation);
- assertThat(changed, equalTo(false));
+ assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().isEmpty(), equalTo(false));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -318,6 +336,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().isEmpty(), equalTo(true));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).size(), equalTo(1));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -331,6 +350,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
assertThat(changed, equalTo(false));
assertThat(allocation.routingNodes().unassigned().ignored().isEmpty(), equalTo(true));
assertThat(allocation.routingNodes().unassigned().size(), equalTo(1));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
private RoutingAllocation getRestoreRoutingAllocation(AllocationDeciders allocationDeciders, boolean hasActiveAllocation) {
@@ -365,6 +385,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().isEmpty(), equalTo(true));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).size(), equalTo(1));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.RED);
}
/**
@@ -378,8 +399,9 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
RoutingAllocation allocation = getRecoverOnAnyNodeRoutingAllocation(throttleAllocationDeciders(), hasActiveAllocation);
testAllocator.addData(node1, legacyVersion, allocationId, randomBoolean());
boolean changed = testAllocator.allocateUnassigned(allocation);
- assertThat(changed, equalTo(false));
+ assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().isEmpty(), equalTo(false));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
/**
@@ -396,6 +418,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().isEmpty(), equalTo(true));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).size(), equalTo(1));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.RED);
}
/**
@@ -409,6 +432,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
assertThat(changed, equalTo(false));
assertThat(allocation.routingNodes().unassigned().ignored().isEmpty(), equalTo(true));
assertThat(allocation.routingNodes().unassigned().size(), equalTo(1));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.YELLOW);
}
private RoutingAllocation getRecoverOnAnyNodeRoutingAllocation(AllocationDeciders allocationDeciders, boolean hasActiveAllocation) {
@@ -448,18 +472,20 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
RoutingAllocation allocation = new RoutingAllocation(yesAllocationDeciders(), new RoutingNodes(state, false), state, null, System.nanoTime(), false);
boolean changed = testAllocator.allocateUnassigned(allocation);
- assertThat(changed, equalTo(false));
+ assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().size(), equalTo(1));
assertThat(allocation.routingNodes().unassigned().ignored().get(0).shardId(), equalTo(shardId));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.UNASSIGNED).size(), equalTo(2)); // replicas
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.RED);
testAllocator.addData(node1, 1, null, randomBoolean());
allocation = new RoutingAllocation(yesAllocationDeciders(), new RoutingNodes(state, false), state, null, System.nanoTime(), false);
changed = testAllocator.allocateUnassigned(allocation);
- assertThat(changed, equalTo(false));
+ assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().size(), equalTo(1));
assertThat(allocation.routingNodes().unassigned().ignored().get(0).shardId(), equalTo(shardId));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.UNASSIGNED).size(), equalTo(2)); // replicas
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.RED);
testAllocator.addData(node2, 1, null, randomBoolean());
allocation = new RoutingAllocation(yesAllocationDeciders(), new RoutingNodes(state, false), state, null, System.nanoTime(), false);
@@ -469,6 +495,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.UNASSIGNED).size(), equalTo(2)); // replicas
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).size(), equalTo(1));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).get(0).currentNodeId(), anyOf(equalTo(node2.getId()), equalTo(node1.getId())));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.RED);
}
/**
@@ -489,18 +516,20 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
RoutingAllocation allocation = new RoutingAllocation(yesAllocationDeciders(), new RoutingNodes(state, false), state, null, System.nanoTime(), false);
boolean changed = testAllocator.allocateUnassigned(allocation);
- assertThat(changed, equalTo(false));
+ assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().size(), equalTo(1));
assertThat(allocation.routingNodes().unassigned().ignored().get(0).shardId(), equalTo(shardId));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.UNASSIGNED).size(), equalTo(2)); // replicas
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.RED);
testAllocator.addData(node1, 1, null, randomBoolean());
allocation = new RoutingAllocation(yesAllocationDeciders(), new RoutingNodes(state, false), state, null, System.nanoTime(), false);
changed = testAllocator.allocateUnassigned(allocation);
- assertThat(changed, equalTo(false));
+ assertThat(changed, equalTo(true));
assertThat(allocation.routingNodes().unassigned().ignored().size(), equalTo(1));
assertThat(allocation.routingNodes().unassigned().ignored().get(0).shardId(), equalTo(shardId));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.UNASSIGNED).size(), equalTo(2)); // replicas
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.RED);
testAllocator.addData(node2, 2, null, randomBoolean());
allocation = new RoutingAllocation(yesAllocationDeciders(), new RoutingNodes(state, false), state, null, System.nanoTime(), false);
@@ -510,6 +539,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.UNASSIGNED).size(), equalTo(2)); // replicas
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).size(), equalTo(1));
assertThat(allocation.routingNodes().shardsWithState(ShardRoutingState.INITIALIZING).get(0).currentNodeId(), equalTo(node2.getId()));
+ assertClusterHealthStatus(allocation, ClusterHealthStatus.RED);
}
private RoutingAllocation routingAllocationWithOnePrimaryNoReplicas(AllocationDeciders deciders, boolean asNew, Version version, String... activeAllocationIds) {
@@ -530,6 +560,19 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
return new RoutingAllocation(deciders, new RoutingNodes(state, false), state, null, System.nanoTime(), false);
}
+ private void assertClusterHealthStatus(RoutingAllocation allocation, ClusterHealthStatus expectedStatus) {
+ RoutingTable oldRoutingTable = allocation.routingTable();
+ RoutingNodes newRoutingNodes = allocation.routingNodes();
+ final RoutingTable newRoutingTable = new RoutingTable.Builder()
+ .updateNodes(oldRoutingTable.version(), newRoutingNodes)
+ .build();
+ ClusterState clusterState = ClusterState.builder(new ClusterName("test-cluster"))
+ .routingTable(newRoutingTable)
+ .build();
+ ClusterStateHealth clusterStateHealth = new ClusterStateHealth(clusterState);
+ assertThat(clusterStateHealth.getStatus().ordinal(), lessThanOrEqualTo(expectedStatus.ordinal()));
+ }
+
class TestAllocator extends PrimaryShardAllocator {
private Map data;
@@ -547,7 +590,7 @@ public class PrimaryShardAllocatorTests extends ESAllocationTestCase {
return addData(node, version, allocationId, primary, null);
}
- public TestAllocator addData(DiscoveryNode node, long version, String allocationId, boolean primary, @Nullable Throwable storeException) {
+ public TestAllocator addData(DiscoveryNode node, long version, String allocationId, boolean primary, @Nullable Exception storeException) {
if (data == null) {
data = new HashMap<>();
}
diff --git a/core/src/test/java/org/elasticsearch/gateway/RecoverAfterNodesIT.java b/core/src/test/java/org/elasticsearch/gateway/RecoverAfterNodesIT.java
index d6e8d61a7a6..1e35bcdd469 100644
--- a/core/src/test/java/org/elasticsearch/gateway/RecoverAfterNodesIT.java
+++ b/core/src/test/java/org/elasticsearch/gateway/RecoverAfterNodesIT.java
@@ -36,7 +36,7 @@ import static org.hamcrest.Matchers.hasItem;
@ClusterScope(scope = Scope.TEST, numDataNodes = 0)
public class RecoverAfterNodesIT extends ESIntegTestCase {
- private final static TimeValue BLOCK_WAIT_TIMEOUT = TimeValue.timeValueSeconds(10);
+ private static final TimeValue BLOCK_WAIT_TIMEOUT = TimeValue.timeValueSeconds(10);
public Set waitForNoBlocksOnNode(TimeValue timeout, Client nodeClient) throws InterruptedException {
long start = System.currentTimeMillis();
diff --git a/core/src/test/java/org/elasticsearch/gateway/ReplicaShardAllocatorTests.java b/core/src/test/java/org/elasticsearch/gateway/ReplicaShardAllocatorTests.java
index b417553a609..dedd26d68b5 100644
--- a/core/src/test/java/org/elasticsearch/gateway/ReplicaShardAllocatorTests.java
+++ b/core/src/test/java/org/elasticsearch/gateway/ReplicaShardAllocatorTests.java
@@ -299,7 +299,7 @@ public class ReplicaShardAllocatorTests extends ESAllocationTestCase {
.addShard(primaryShard)
.addShard(ShardRouting.newUnassigned(shardId, null, false,
new UnassignedInfo(reason, null, null, failedAllocations, System.nanoTime(),
- System.currentTimeMillis(), delayed)))
+ System.currentTimeMillis(), delayed, UnassignedInfo.AllocationStatus.NO_ATTEMPT)))
.build())
)
.build();
diff --git a/core/src/test/java/org/elasticsearch/http/HttpServerTests.java b/core/src/test/java/org/elasticsearch/http/HttpServerTests.java
index 2ba7da84c14..f9de466e978 100644
--- a/core/src/test/java/org/elasticsearch/http/HttpServerTests.java
+++ b/core/src/test/java/org/elasticsearch/http/HttpServerTests.java
@@ -18,9 +18,10 @@
*/
package org.elasticsearch.http;
-import org.elasticsearch.cluster.service.ClusterService;
+import java.util.Collections;
+import java.util.Map;
+
import org.elasticsearch.common.breaker.CircuitBreaker;
-import org.elasticsearch.common.bytes.ByteBufferBytesReference;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
@@ -33,7 +34,6 @@ import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.indices.breaker.CircuitBreakerService;
import org.elasticsearch.indices.breaker.HierarchyCircuitBreakerService;
-import org.elasticsearch.node.service.NodeService;
import org.elasticsearch.rest.AbstractRestChannel;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestController;
@@ -43,10 +43,6 @@ import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.test.ESTestCase;
import org.junit.Before;
-import java.nio.ByteBuffer;
-import java.nio.charset.StandardCharsets;
-import java.util.Map;
-
public class HttpServerTests extends ESTestCase {
private static final ByteSizeValue BREAKER_LIMIT = new ByteSizeValue(20);
private HttpServer httpServer;
@@ -64,19 +60,15 @@ public class HttpServerTests extends ESTestCase {
inFlightRequestsBreaker = circuitBreakerService.getBreaker(CircuitBreaker.IN_FLIGHT_REQUESTS);
HttpServerTransport httpServerTransport = new TestHttpServerTransport();
- RestController restController = new RestController(settings);
+ RestController restController = new RestController(settings, Collections.emptySet());
restController.registerHandler(RestRequest.Method.GET, "/",
- (request, channel) -> channel.sendResponse(
+ (request, channel, client) -> channel.sendResponse(
new BytesRestResponse(RestStatus.OK, BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY)));
- restController.registerHandler(RestRequest.Method.GET, "/error", (request, channel) -> {
+ restController.registerHandler(RestRequest.Method.GET, "/error", (request, channel, client) -> {
throw new IllegalArgumentException("test error");
});
- ClusterService clusterService = new ClusterService(Settings.EMPTY,
- new ClusterSettings(settings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS), null);
- NodeService nodeService = new NodeService(Settings.EMPTY, null, null, null, null, null, null, null, null,
- clusterService, null);
- httpServer = new HttpServer(settings, httpServerTransport, restController, nodeService, circuitBreakerService);
+ httpServer = new HttpServer(settings, httpServerTransport, restController, null, circuitBreakerService);
httpServer.start();
}
@@ -129,7 +121,7 @@ public class HttpServerTests extends ESTestCase {
assertEquals(0, inFlightRequestsBreaker.getUsed());
}
- private static final class TestHttpServerTransport extends AbstractLifecycleComponent implements
+ private static final class TestHttpServerTransport extends AbstractLifecycleComponent implements
HttpServerTransport {
public TestHttpServerTransport() {
@@ -202,7 +194,7 @@ public class HttpServerTests extends ESTestCase {
private TestRestRequest(String path, String content) {
this.path = path;
- this.content = new ByteBufferBytesReference(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)));
+ this.content = new BytesArray(content);
}
@Override
diff --git a/core/src/test/java/org/elasticsearch/index/IndexModuleTests.java b/core/src/test/java/org/elasticsearch/index/IndexModuleTests.java
index 2769534aee0..91e9bb2c016 100644
--- a/core/src/test/java/org/elasticsearch/index/IndexModuleTests.java
+++ b/core/src/test/java/org/elasticsearch/index/IndexModuleTests.java
@@ -193,7 +193,6 @@ public class IndexModuleTests extends ESTestCase {
IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(index, settings);
IndexModule module = new IndexModule(indexSettings, null,
new AnalysisRegistry(environment, emptyMap(), emptyMap(), emptyMap(), emptyMap()));
- Consumer listener = (s) -> {};
module.addIndexEventListener(eventListener);
IndexService indexService = module.newIndexService(nodeEnvironment, deleter, nodeServicesProvider, indicesQueryCache, mapperRegistry,
new IndicesFieldDataCache(settings, this.listener));
diff --git a/core/src/test/java/org/elasticsearch/index/IndexRequestBuilderIT.java b/core/src/test/java/org/elasticsearch/index/IndexRequestBuilderIT.java
index c41051ec59c..84a9fe2970b 100644
--- a/core/src/test/java/org/elasticsearch/index/IndexRequestBuilderIT.java
+++ b/core/src/test/java/org/elasticsearch/index/IndexRequestBuilderIT.java
@@ -22,6 +22,7 @@ package org.elasticsearch.index;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.bytes.BytesArray;
+import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.hamcrest.ElasticsearchAssertions;
@@ -35,7 +36,6 @@ import static org.hamcrest.Matchers.containsString;
public class IndexRequestBuilderIT extends ESIntegTestCase {
public void testSetSource() throws InterruptedException, ExecutionException {
createIndex("test");
- ensureYellow();
Map map = new HashMap<>();
map.put("test_field", "foobar");
IndexRequestBuilder[] builders = new IndexRequestBuilder[] {
@@ -43,7 +43,7 @@ public class IndexRequestBuilderIT extends ESIntegTestCase {
client().prepareIndex("test", "test").setSource("{\"test_field\" : \"foobar\"}"),
client().prepareIndex("test", "test").setSource(new BytesArray("{\"test_field\" : \"foobar\"}")),
client().prepareIndex("test", "test").setSource(new BytesArray("{\"test_field\" : \"foobar\"}")),
- client().prepareIndex("test", "test").setSource(new BytesArray("{\"test_field\" : \"foobar\"}").toBytes()),
+ client().prepareIndex("test", "test").setSource(BytesReference.toBytes(new BytesArray("{\"test_field\" : \"foobar\"}"))),
client().prepareIndex("test", "test").setSource(map)
};
indexRandom(true, builders);
diff --git a/core/src/test/java/org/elasticsearch/index/IndexServiceTests.java b/core/src/test/java/org/elasticsearch/index/IndexServiceTests.java
index 97258b12a3b..22324e1ff2b 100644
--- a/core/src/test/java/org/elasticsearch/index/IndexServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/index/IndexServiceTests.java
@@ -77,7 +77,6 @@ public class IndexServiceTests extends ESSingleNodeTestCase {
public void testFilteringAliases() throws Exception {
IndexService indexService = createIndex("test", Settings.EMPTY);
- IndexShard shard = indexService.getShard(0);
add(indexService, "cats", filter(termQuery("animal", "cat")));
add(indexService, "dogs", filter(termQuery("animal", "dog")));
add(indexService, "all", null);
@@ -101,7 +100,6 @@ public class IndexServiceTests extends ESSingleNodeTestCase {
public void testAliasFilters() throws Exception {
IndexService indexService = createIndex("test", Settings.EMPTY);
- IndexShard shard = indexService.getShard(0);
add(indexService, "cats", filter(termQuery("animal", "cat")));
add(indexService, "dogs", filter(termQuery("animal", "dog")));
@@ -118,7 +116,6 @@ public class IndexServiceTests extends ESSingleNodeTestCase {
public void testRemovedAliasFilter() throws Exception {
IndexService indexService = createIndex("test", Settings.EMPTY);
- IndexShard shard = indexService.getShard(0);
add(indexService, "cats", filter(termQuery("animal", "cat")));
remove(indexService, "cats");
@@ -132,7 +129,6 @@ public class IndexServiceTests extends ESSingleNodeTestCase {
public void testUnknownAliasFilter() throws Exception {
IndexService indexService = createIndex("test", Settings.EMPTY);
- IndexShard shard = indexService.getShard(0);
add(indexService, "cats", filter(termQuery("animal", "cat")));
add(indexService, "dogs", filter(termQuery("animal", "dog")));
diff --git a/core/src/test/java/org/elasticsearch/index/IndexWithShadowReplicasIT.java b/core/src/test/java/org/elasticsearch/index/IndexWithShadowReplicasIT.java
index f0e12abeac8..9f2ec74329b 100644
--- a/core/src/test/java/org/elasticsearch/index/IndexWithShadowReplicasIT.java
+++ b/core/src/test/java/org/elasticsearch/index/IndexWithShadowReplicasIT.java
@@ -94,7 +94,7 @@ public class IndexWithShadowReplicasIT extends ESIntegTestCase {
private Settings nodeSettings(String dataPath) {
return Settings.builder()
- .put(NodeEnvironment.ADD_NODE_ID_TO_CUSTOM_PATH.getKey(), false)
+ .put(NodeEnvironment.ADD_NODE_LOCK_ID_TO_CUSTOM_PATH.getKey(), false)
.put(Environment.PATH_SHARED_DATA_SETTING.getKey(), dataPath)
.put(FsDirectoryService.INDEX_LOCK_FACTOR_SETTING.getKey(), randomFrom("native", "simple"))
.build();
@@ -277,7 +277,6 @@ public class IndexWithShadowReplicasIT extends ESIntegTestCase {
.build();
prepareCreate(IDX).setSettings(idxSettings).addMapping("doc", "foo", "type=text").get();
- ensureYellow(IDX);
client().prepareIndex(IDX, "doc", "1").setSource("foo", "bar").get();
client().prepareIndex(IDX, "doc", "2").setSource("foo", "bar").get();
@@ -335,7 +334,6 @@ public class IndexWithShadowReplicasIT extends ESIntegTestCase {
.build();
prepareCreate(IDX).setSettings(idxSettings).addMapping("doc", "foo", "type=text").get();
- ensureYellow(IDX);
client().prepareIndex(IDX, "doc", "1").setSource("foo", "bar").get();
client().prepareIndex(IDX, "doc", "2").setSource("foo", "bar").get();
@@ -379,7 +377,7 @@ public class IndexWithShadowReplicasIT extends ESIntegTestCase {
assertThat(gResp2.getField("foo").getValue().toString(), equalTo("bar"));
}
- public void testPrimaryRelocationWithConcurrentIndexing() throws Throwable {
+ public void testPrimaryRelocationWithConcurrentIndexing() throws Exception {
Path dataPath = createTempDir();
Settings nodeSettings = nodeSettings(dataPath);
@@ -395,7 +393,6 @@ public class IndexWithShadowReplicasIT extends ESIntegTestCase {
.build();
prepareCreate(IDX).setSettings(idxSettings).addMapping("doc", "foo", "type=text").get();
- ensureYellow(IDX);
// Node1 has the primary, now node2 has the replica
String node2 = internalCluster().startNode(nodeSettings);
ensureGreen(IDX);
@@ -408,7 +405,7 @@ public class IndexWithShadowReplicasIT extends ESIntegTestCase {
final int numPhase2Docs = scaledRandomIntBetween(25, 200);
final CountDownLatch phase1finished = new CountDownLatch(1);
final CountDownLatch phase2finished = new CountDownLatch(1);
- final CopyOnWriteArrayList exceptions = new CopyOnWriteArrayList<>();
+ final CopyOnWriteArrayList exceptions = new CopyOnWriteArrayList<>();
Thread thread = new Thread() {
@Override
public void run() {
@@ -418,8 +415,8 @@ public class IndexWithShadowReplicasIT extends ESIntegTestCase {
final IndexResponse indexResponse = client().prepareIndex(IDX, "doc",
Integer.toString(counter.incrementAndGet())).setSource("foo", "bar").get();
assertTrue(indexResponse.isCreated());
- } catch (Throwable t) {
- exceptions.add(t);
+ } catch (Exception e) {
+ exceptions.add(e);
}
final int docCount = counter.get();
if (docCount == numPhase1Docs) {
@@ -454,7 +451,7 @@ public class IndexWithShadowReplicasIT extends ESIntegTestCase {
public void testPrimaryRelocationWhereRecoveryFails() throws Exception {
Path dataPath = createTempDir();
Settings nodeSettings = Settings.builder()
- .put("node.add_id_to_custom_path", false)
+ .put("node.add_lock_id_to_custom_path", false)
.put(Environment.PATH_SHARED_DATA_SETTING.getKey(), dataPath)
.build();
@@ -470,7 +467,6 @@ public class IndexWithShadowReplicasIT extends ESIntegTestCase {
.build();
prepareCreate(IDX).setSettings(idxSettings).addMapping("doc", "foo", "type=text").get();
- ensureYellow(IDX);
// Node1 has the primary, now node2 has the replica
String node2 = internalCluster().startNode(nodeSettings);
ensureGreen(IDX);
@@ -677,7 +673,7 @@ public class IndexWithShadowReplicasIT extends ESIntegTestCase {
client().prepareIndex(IDX, "doc", "4").setSource("foo", "eggplant").get();
flushAndRefresh(IDX);
- SearchResponse resp = client().prepareSearch(IDX).setQuery(matchAllQuery()).addFieldDataField("foo").addSort("foo", SortOrder.ASC).get();
+ SearchResponse resp = client().prepareSearch(IDX).setQuery(matchAllQuery()).addDocValueField("foo").addSort("foo", SortOrder.ASC).get();
assertHitCount(resp, 4);
assertOrderedSearchHits(resp, "2", "3", "4", "1");
SearchHit[] hits = resp.getHits().hits();
@@ -859,7 +855,6 @@ public class IndexWithShadowReplicasIT extends ESIntegTestCase {
.build();
prepareCreate(IDX).setSettings(idxSettings).addMapping("doc", "foo", "type=text").get();
- ensureYellow(IDX);
client().prepareIndex(IDX, "doc", "1").setSource("foo", "bar").get();
client().prepareIndex(IDX, "doc", "2").setSource("foo", "bar").get();
diff --git a/core/src/test/java/org/elasticsearch/index/SettingsListenerIT.java b/core/src/test/java/org/elasticsearch/index/SettingsListenerIT.java
index 000d2509ea8..4f16be6f541 100644
--- a/core/src/test/java/org/elasticsearch/index/SettingsListenerIT.java
+++ b/core/src/test/java/org/elasticsearch/index/SettingsListenerIT.java
@@ -45,8 +45,6 @@ public class SettingsListenerIT extends ESIntegTestCase {
public static class SettingsListenerPlugin extends Plugin {
private final SettingsTestingService service = new SettingsTestingService();
- private static final Setting SETTING = Setting.intSetting("index.test.new.setting", 0,
- Property.Dynamic, Property.IndexScope);
@Override
public List> getSettings() {
@@ -62,7 +60,7 @@ public class SettingsListenerIT extends ESIntegTestCase {
}
@Override
- public Collection nodeModules() {
+ public Collection createGuiceModules() {
return Collections.singletonList(new SettingsListenerModule(service));
}
}
diff --git a/core/src/test/java/org/elasticsearch/index/WaitUntilRefreshIT.java b/core/src/test/java/org/elasticsearch/index/WaitUntilRefreshIT.java
index a0a51d01e03..959aba4c520 100644
--- a/core/src/test/java/org/elasticsearch/index/WaitUntilRefreshIT.java
+++ b/core/src/test/java/org/elasticsearch/index/WaitUntilRefreshIT.java
@@ -58,10 +58,6 @@ import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSear
* Tests that requests with RefreshPolicy.WAIT_UNTIL will be visible when they return.
*/
public class WaitUntilRefreshIT extends ESIntegTestCase {
- @Override
- protected Settings nodeSettings(int nodeOrdinal) {
- return Settings.builder().put(super.nodeSettings(nodeOrdinal)).put(NetworkModule.HTTP_ENABLED.getKey(), true).build();
- }
@Override
public Settings indexSettings() {
diff --git a/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java b/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java
index a0396b7abc6..a3fd266f603 100644
--- a/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java
+++ b/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java
@@ -297,7 +297,7 @@ public class InternalEngineTests extends ESTestCase {
}
Engine.EventListener listener = new Engine.EventListener() {
@Override
- public void onFailedEngine(String reason, @Nullable Throwable t) {
+ public void onFailedEngine(String reason, @Nullable Exception e) {
// we don't need to notify anybody in this test
}
};
@@ -539,7 +539,7 @@ public class InternalEngineTests extends ESTestCase {
public void testCommitStats() {
Document document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
engine.index(new Engine.Index(newUid("1"), doc));
@@ -716,7 +716,7 @@ public class InternalEngineTests extends ESTestCase {
// create a document
Document document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
engine.index(new Engine.Index(newUid("1"), doc));
@@ -729,7 +729,7 @@ public class InternalEngineTests extends ESTestCase {
// but, we can still get it (in realtime)
Engine.GetResult getResult = engine.get(new Engine.Get(true, newUid("1")));
assertThat(getResult.exists(), equalTo(true));
- assertThat(getResult.source().source.toBytesArray(), equalTo(B_1.toBytesArray()));
+ assertThat(getResult.source().source, equalTo(B_1));
assertThat(getResult.docIdAndVersion(), nullValue());
getResult.release();
@@ -755,7 +755,7 @@ public class InternalEngineTests extends ESTestCase {
// now do an update
document = testDocument();
document.add(new TextField("value", "test1", Field.Store.YES));
- document.add(new Field(SourceFieldMapper.NAME, B_2.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_2), SourceFieldMapper.Defaults.FIELD_TYPE));
doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_2, null);
engine.index(new Engine.Index(newUid("1"), doc));
@@ -769,7 +769,7 @@ public class InternalEngineTests extends ESTestCase {
// but, we can still get it (in realtime)
getResult = engine.get(new Engine.Get(true, newUid("1")));
assertThat(getResult.exists(), equalTo(true));
- assertThat(getResult.source().source.toBytesArray(), equalTo(B_2.toBytesArray()));
+ assertThat(getResult.source().source, equalTo(B_2));
assertThat(getResult.docIdAndVersion(), nullValue());
getResult.release();
@@ -808,7 +808,7 @@ public class InternalEngineTests extends ESTestCase {
// add it back
document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
engine.index(new Engine.Index(newUid("1"), doc, Versions.MATCH_DELETED));
@@ -2092,7 +2092,7 @@ public class InternalEngineTests extends ESTestCase {
}
public void testShardNotAvailableExceptionWhenEngineClosedConcurrently() throws IOException, InterruptedException {
- AtomicReference throwable = new AtomicReference<>();
+ AtomicReference exception = new AtomicReference<>();
String operation = randomFrom("optimize", "refresh", "flush");
Thread mergeThread = new Thread() {
@Override
@@ -2115,8 +2115,8 @@ public class InternalEngineTests extends ESTestCase {
break;
}
}
- } catch (Throwable t) {
- throwable.set(t);
+ } catch (Exception e) {
+ exception.set(e);
stop = true;
}
}
@@ -2125,8 +2125,8 @@ public class InternalEngineTests extends ESTestCase {
mergeThread.start();
engine.close();
mergeThread.join();
- logger.info("exception caught: ", throwable.get());
- assertTrue("expected an Exception that signals shard is not available", TransportActions.isShardNotAvailableException(throwable.get()));
+ logger.info("exception caught: ", exception.get());
+ assertTrue("expected an Exception that signals shard is not available", TransportActions.isShardNotAvailableException(exception.get()));
}
public void testCurrentTranslogIDisCommitted() throws IOException {
diff --git a/core/src/test/java/org/elasticsearch/index/engine/ShadowEngineTests.java b/core/src/test/java/org/elasticsearch/index/engine/ShadowEngineTests.java
index ef443d1e102..672686926bd 100644
--- a/core/src/test/java/org/elasticsearch/index/engine/ShadowEngineTests.java
+++ b/core/src/test/java/org/elasticsearch/index/engine/ShadowEngineTests.java
@@ -242,7 +242,7 @@ public class ShadowEngineTests extends ESTestCase {
}
Engine.EventListener eventListener = new Engine.EventListener() {
@Override
- public void onFailedEngine(String reason, @Nullable Throwable t) {
+ public void onFailedEngine(String reason, @Nullable Exception e) {
// we don't need to notify anybody in this test
}
};
@@ -500,7 +500,7 @@ public class ShadowEngineTests extends ESTestCase {
public void testShadowEngineIgnoresWriteOperations() throws Exception {
// create a document
ParseContext.Document document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
try {
replicaEngine.index(new Engine.Index(newUid("1"), doc));
@@ -538,7 +538,7 @@ public class ShadowEngineTests extends ESTestCase {
// Now, add a document to the primary so we can test shadow engine deletes
document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
primaryEngine.index(new Engine.Index(newUid("1"), doc));
primaryEngine.flush();
@@ -593,7 +593,7 @@ public class ShadowEngineTests extends ESTestCase {
// create a document
ParseContext.Document document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
primaryEngine.index(new Engine.Index(newUid("1"), doc));
@@ -612,7 +612,7 @@ public class ShadowEngineTests extends ESTestCase {
// but, we can still get it (in realtime)
Engine.GetResult getResult = primaryEngine.get(new Engine.Get(true, newUid("1")));
assertThat(getResult.exists(), equalTo(true));
- assertThat(getResult.source().source.toBytesArray(), equalTo(B_1.toBytesArray()));
+ assertThat(getResult.source().source, equalTo(B_1));
assertThat(getResult.docIdAndVersion(), nullValue());
getResult.release();
@@ -649,7 +649,7 @@ public class ShadowEngineTests extends ESTestCase {
// now do an update
document = testDocument();
document.add(new TextField("value", "test1", Field.Store.YES));
- document.add(new Field(SourceFieldMapper.NAME, B_2.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_2), SourceFieldMapper.Defaults.FIELD_TYPE));
doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_2, null);
primaryEngine.index(new Engine.Index(newUid("1"), doc));
@@ -663,7 +663,7 @@ public class ShadowEngineTests extends ESTestCase {
// but, we can still get it (in realtime)
getResult = primaryEngine.get(new Engine.Get(true, newUid("1")));
assertThat(getResult.exists(), equalTo(true));
- assertThat(getResult.source().source.toBytesArray(), equalTo(B_2.toBytesArray()));
+ assertThat(getResult.source().source, equalTo(B_2));
assertThat(getResult.docIdAndVersion(), nullValue());
getResult.release();
@@ -720,7 +720,7 @@ public class ShadowEngineTests extends ESTestCase {
// add it back
document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
primaryEngine.index(new Engine.Index(newUid("1"), doc));
@@ -971,7 +971,7 @@ public class ShadowEngineTests extends ESTestCase {
// create a document
ParseContext.Document document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
pEngine.index(new Engine.Index(newUid("1"), doc));
pEngine.flush(true, true);
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingDisabledTests.java b/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingDisabledTests.java
index f9fb5e77b70..9a8815e9398 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingDisabledTests.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingDisabledTests.java
@@ -19,7 +19,6 @@
package org.elasticsearch.index.mapper;
-import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
@@ -116,7 +115,7 @@ public class DynamicMappingDisabledTests extends ESSingleNodeTestCase {
}
@Override
- public void onFailure(Throwable e) {
+ public void onFailure(Exception e) {
onFailureCalled.set(true);
assertThat(e, instanceOf(IndexNotFoundException.class));
assertEquals(e.getMessage(), "no such index");
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingIntegrationIT.java b/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingIT.java
similarity index 76%
rename from core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingIntegrationIT.java
rename to core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingIT.java
index 8afdea27451..70d7daef717 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingIntegrationIT.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/DynamicMappingIT.java
@@ -18,10 +18,13 @@
*/
package org.elasticsearch.index.mapper;
+import org.elasticsearch.action.admin.indices.get.GetIndexResponse;
import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;
+import org.elasticsearch.common.settings.Settings;
+import org.elasticsearch.indices.TypeMissingException;
import org.elasticsearch.test.ESIntegTestCase;
import java.io.IOException;
@@ -29,8 +32,9 @@ import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
-public class DynamicMappingIntegrationIT extends ESIntegTestCase {
+public class DynamicMappingIT extends ESIntegTestCase {
public void testConflictingDynamicMappings() {
// we don't use indexRandom because the order of requests is important here
@@ -96,8 +100,8 @@ public class DynamicMappingIntegrationIT extends ESIntegTestCase {
try {
startLatch.await();
assertTrue(client().prepareIndex("index", "type", id).setSource("field" + id, "bar").get().isCreated());
- } catch (Throwable t) {
- error.compareAndSet(null, t);
+ } catch (Exception e) {
+ error.compareAndSet(null, e);
}
}
});
@@ -120,4 +124,26 @@ public class DynamicMappingIntegrationIT extends ESIntegTestCase {
}
}
+ public void testAutoCreateWithDisabledDynamicMappings() throws Exception {
+ assertAcked(client().admin().indices().preparePutTemplate("my_template")
+ .setCreate(true)
+ .setTemplate("index_*")
+ .addMapping("foo", "field", "type=keyword")
+ .setSettings(Settings.builder().put("index.mapper.dynamic", false).build())
+ .get());
+
+ // succeeds since 'foo' has an explicit mapping in the template
+ indexRandom(true, false, client().prepareIndex("index_1", "foo", "1").setSource("field", "abc"));
+
+ // fails since 'bar' does not have an explicit mapping in the template and dynamic template creation is disabled
+ TypeMissingException e1 = expectThrows(TypeMissingException.class,
+ () -> client().prepareIndex("index_2", "bar", "1").setSource("field", "abc").get());
+ assertEquals("type[bar] missing", e1.getMessage());
+ assertEquals("trying to auto create mapping, but dynamic mapping is disabled", e1.getCause().getMessage());
+
+ // make sure no mappings were created for bar
+ GetIndexResponse getIndexResponse = client().admin().indices().prepareGetIndex().addIndices("index_2").get();
+ assertFalse(getIndexResponse.mappings().containsKey("bar"));
+ }
+
}
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/DynamicTemplateTests.java b/core/src/test/java/org/elasticsearch/index/mapper/DynamicTemplateTests.java
index 31b65e84aa0..0de3c5d4a30 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/DynamicTemplateTests.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/DynamicTemplateTests.java
@@ -24,6 +24,7 @@ import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.mapper.object.DynamicTemplate;
+import org.elasticsearch.index.mapper.object.DynamicTemplate.XContentFieldType;
import org.elasticsearch.test.ESTestCase;
import java.util.Collections;
@@ -49,6 +50,31 @@ public class DynamicTemplateTests extends ESTestCase {
assertEquals("{\"match_mapping_type\":\"string\",\"mapping\":{\"store\":true}}", builder.string());
}
+ public void testParseUnknownMatchType() {
+ Map templateDef = new HashMap<>();
+ templateDef.put("match_mapping_type", "short");
+ templateDef.put("mapping", Collections.singletonMap("store", true));
+ // if a wrong match type is specified, we ignore the template
+ assertNull(DynamicTemplate.parse("my_template", templateDef, Version.V_5_0_0_alpha5));
+ }
+
+ public void testMatchAllTemplate() {
+ Map templateDef = new HashMap<>();
+ templateDef.put("match_mapping_type", "*");
+ templateDef.put("mapping", Collections.singletonMap("store", true));
+ DynamicTemplate template = DynamicTemplate.parse("my_template", templateDef, Version.V_5_0_0_alpha5);
+ assertTrue(template.match("a.b", "b", randomFrom(XContentFieldType.values())));
+ }
+
+ public void testMatchTypeTemplate() {
+ Map templateDef = new HashMap<>();
+ templateDef.put("match_mapping_type", "string");
+ templateDef.put("mapping", Collections.singletonMap("store", true));
+ DynamicTemplate template = DynamicTemplate.parse("my_template", templateDef, Version.V_5_0_0_alpha5);
+ assertTrue(template.match("a.b", "b", XContentFieldType.STRING));
+ assertFalse(template.match("a.b", "b", XContentFieldType.BOOLEAN));
+ }
+
public void testSerialization() throws Exception {
// type-based template
Map templateDef = new HashMap<>();
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/FieldTypeTestCase.java b/core/src/test/java/org/elasticsearch/index/mapper/FieldTypeTestCase.java
index 68e59527982..37d0436c9db 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/FieldTypeTestCase.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/FieldTypeTestCase.java
@@ -32,7 +32,7 @@ import java.util.List;
public abstract class FieldTypeTestCase extends ESTestCase {
/** Abstraction for mutating a property of a MappedFieldType */
- public static abstract class Modifier {
+ public abstract static class Modifier {
/** The name of the property that is being modified. Used in test failure messages. */
public final String property;
/** true if this modifier only makes types incompatible in strict mode, false otherwise */
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/MapperServiceTests.java b/core/src/test/java/org/elasticsearch/index/mapper/MapperServiceTests.java
index c93c181f860..2afeb02499d 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/MapperServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/MapperServiceTests.java
@@ -103,7 +103,7 @@ public class MapperServiceTests extends ESSingleNodeTestCase {
// 2. already existing index
IndexService indexService = createIndex("index2");
- expectThrows(ExecutionException.class, () -> {
+ e = expectThrows(ExecutionException.class, () -> {
client().prepareIndex("index1", MapperService.DEFAULT_MAPPING, "2").setSource().execute().get();
});
throwable = ExceptionsHelper.unwrapCause(e.getCause());
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/all/SimpleAllMapperTests.java b/core/src/test/java/org/elasticsearch/index/mapper/all/SimpleAllMapperTests.java
index 165b49d3145..817dc6e50df 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/all/SimpleAllMapperTests.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/all/SimpleAllMapperTests.java
@@ -24,6 +24,7 @@ import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.elasticsearch.common.bytes.BytesArray;
+import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
@@ -292,17 +293,17 @@ public class SimpleAllMapperTests extends ESSingleNodeTestCase {
}
DocumentMapperParser parser = createIndex("test").mapperService().documentMapperParser();
- String mapping = mappingBuilder.endObject().endObject().bytes().toUtf8();
+ String mapping = mappingBuilder.endObject().endObject().bytes().utf8ToString();
logger.info("Mapping: {}", mapping);
DocumentMapper docMapper = parser.parse("test", new CompressedXContent(mapping));
String builtMapping = docMapper.mappingSource().string();
// reparse it
DocumentMapper builtDocMapper = parser.parse("test", new CompressedXContent(builtMapping));
- byte[] json = jsonBuilder().startObject()
+ byte[] json = BytesReference.toBytes(jsonBuilder().startObject()
.field("foo", "bar")
.field("foobar", "foobar")
- .endObject().bytes().toBytes();
+ .endObject().bytes());
Document doc = builtDocMapper.parse("test", "test", "1", new BytesArray(json)).rootDoc();
IndexableField[] fields = doc.getFields("_all");
if (enabled) {
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/binary/BinaryMappingTests.java b/core/src/test/java/org/elasticsearch/index/mapper/binary/BinaryMappingTests.java
index fc8e2ba1872..4bf1d0c68f7 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/binary/BinaryMappingTests.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/binary/BinaryMappingTests.java
@@ -21,6 +21,7 @@ package org.elasticsearch.index.mapper.binary;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.bytes.BytesArray;
+import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.compress.CompressorFactory;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
@@ -79,7 +80,7 @@ public class BinaryMappingTests extends ESSingleNodeTestCase {
try (StreamOutput compressed = CompressorFactory.COMPRESSOR.streamOutput(out)) {
new BytesArray(binaryValue1).writeTo(compressed);
}
- final byte[] binaryValue2 = out.bytes().toBytes();
+ final byte[] binaryValue2 = BytesReference.toBytes(out.bytes());
assertTrue(CompressorFactory.isCompressed(new BytesArray(binaryValue2)));
for (byte[] value : Arrays.asList(binaryValue1, binaryValue2)) {
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/core/ScaledFloatFieldMapperTests.java b/core/src/test/java/org/elasticsearch/index/mapper/core/ScaledFloatFieldMapperTests.java
new file mode 100644
index 00000000000..aa14fc3495c
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/index/mapper/core/ScaledFloatFieldMapperTests.java
@@ -0,0 +1,339 @@
+/*
+ * 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.index.mapper.core;
+
+import org.apache.lucene.index.DocValuesType;
+import org.apache.lucene.index.IndexableField;
+import org.elasticsearch.common.compress.CompressedXContent;
+import org.elasticsearch.common.xcontent.XContentFactory;
+import org.elasticsearch.index.IndexService;
+import org.elasticsearch.index.mapper.DocumentMapper;
+import org.elasticsearch.index.mapper.DocumentMapperParser;
+import org.elasticsearch.index.mapper.MapperParsingException;
+import org.elasticsearch.index.mapper.ParsedDocument;
+import org.elasticsearch.test.ESSingleNodeTestCase;
+import org.junit.Before;
+
+import java.io.IOException;
+
+import static org.hamcrest.Matchers.containsString;
+
+public class ScaledFloatFieldMapperTests extends ESSingleNodeTestCase {
+
+ IndexService indexService;
+ DocumentMapperParser parser;
+
+ @Before
+ public void before() {
+ indexService = createIndex("test");
+ parser = indexService.mapperService().documentMapperParser();
+ }
+
+ public void testDefaults() throws Exception {
+ String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject("properties").startObject("field").field("type", "scaled_float")
+ .field("scaling_factor", 10.0).endObject().endObject()
+ .endObject().endObject().string();
+
+ DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping));
+
+ assertEquals(mapping, mapper.mappingSource().toString());
+
+ ParsedDocument doc = mapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
+ .startObject()
+ .field("field", 123)
+ .endObject()
+ .bytes());
+
+ IndexableField[] fields = doc.rootDoc().getFields("field");
+ assertEquals(2, fields.length);
+ IndexableField pointField = fields[0];
+ assertEquals(1, pointField.fieldType().pointDimensionCount());
+ assertFalse(pointField.fieldType().stored());
+ assertEquals(1230, pointField.numericValue().longValue());
+ IndexableField dvField = fields[1];
+ assertEquals(DocValuesType.SORTED_NUMERIC, dvField.fieldType().docValuesType());
+ assertEquals(1230, dvField.numericValue().longValue());
+ assertFalse(dvField.fieldType().stored());
+ }
+
+ public void testMissingScalingFactor() throws IOException {
+ String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject("properties").startObject("field").field("type", "scaled_float").endObject().endObject()
+ .endObject().endObject().string();
+
+ IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
+ () -> parser.parse("type", new CompressedXContent(mapping)));
+ assertEquals("Field [field] misses required parameter [scaling_factor]", e.getMessage());
+ }
+
+ public void testIllegalScalingFactor() throws IOException {
+ String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject("properties").startObject("field").field("type", "scaled_float")
+ .field("scaling_factor", -1).endObject().endObject()
+ .endObject().endObject().string();
+
+ IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
+ () -> parser.parse("type", new CompressedXContent(mapping)));
+ assertEquals("[scaling_factor] must be a positive number, got [-1.0]", e.getMessage());
+ }
+
+ public void testNotIndexed() throws Exception {
+ String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject("properties").startObject("field").field("type", "scaled_float")
+ .field("index", false).field("scaling_factor", 10.0).endObject().endObject()
+ .endObject().endObject().string();
+
+ DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping));
+
+ assertEquals(mapping, mapper.mappingSource().toString());
+
+ ParsedDocument doc = mapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
+ .startObject()
+ .field("field", 123)
+ .endObject()
+ .bytes());
+
+ IndexableField[] fields = doc.rootDoc().getFields("field");
+ assertEquals(1, fields.length);
+ IndexableField dvField = fields[0];
+ assertEquals(DocValuesType.SORTED_NUMERIC, dvField.fieldType().docValuesType());
+ assertEquals(1230, dvField.numericValue().longValue());
+ }
+
+ public void testNoDocValues() throws Exception {
+ String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject("properties").startObject("field").field("type", "scaled_float")
+ .field("doc_values", false).field("scaling_factor", 10.0).endObject().endObject()
+ .endObject().endObject().string();
+
+ DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping));
+
+ assertEquals(mapping, mapper.mappingSource().toString());
+
+ ParsedDocument doc = mapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
+ .startObject()
+ .field("field", 123)
+ .endObject()
+ .bytes());
+
+ IndexableField[] fields = doc.rootDoc().getFields("field");
+ assertEquals(1, fields.length);
+ IndexableField pointField = fields[0];
+ assertEquals(1, pointField.fieldType().pointDimensionCount());
+ assertEquals(1230, pointField.numericValue().longValue());
+ }
+
+ public void testStore() throws Exception {
+ String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject("properties").startObject("field").field("type", "scaled_float")
+ .field("store", true).field("scaling_factor", 10.0).endObject().endObject()
+ .endObject().endObject().string();
+
+ DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping));
+
+ assertEquals(mapping, mapper.mappingSource().toString());
+
+ ParsedDocument doc = mapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
+ .startObject()
+ .field("field", 123)
+ .endObject()
+ .bytes());
+
+ IndexableField[] fields = doc.rootDoc().getFields("field");
+ assertEquals(3, fields.length);
+ IndexableField pointField = fields[0];
+ assertEquals(1, pointField.fieldType().pointDimensionCount());
+ assertEquals(1230, pointField.numericValue().doubleValue(), 0d);
+ IndexableField dvField = fields[1];
+ assertEquals(DocValuesType.SORTED_NUMERIC, dvField.fieldType().docValuesType());
+ IndexableField storedField = fields[2];
+ assertTrue(storedField.fieldType().stored());
+ assertEquals(1230, storedField.numericValue().longValue());
+ }
+
+ public void testCoerce() throws Exception {
+ String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject("properties").startObject("field").field("type", "scaled_float")
+ .field("scaling_factor", 10.0).endObject().endObject()
+ .endObject().endObject().string();
+
+ DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping));
+
+ assertEquals(mapping, mapper.mappingSource().toString());
+
+ ParsedDocument doc = mapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
+ .startObject()
+ .field("field", "123")
+ .endObject()
+ .bytes());
+
+ IndexableField[] fields = doc.rootDoc().getFields("field");
+ assertEquals(2, fields.length);
+ IndexableField pointField = fields[0];
+ assertEquals(1, pointField.fieldType().pointDimensionCount());
+ assertEquals(1230, pointField.numericValue().longValue());
+ IndexableField dvField = fields[1];
+ assertEquals(DocValuesType.SORTED_NUMERIC, dvField.fieldType().docValuesType());
+
+ mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject("properties").startObject("field").field("type", "scaled_float")
+ .field("scaling_factor", 10.0).field("coerce", false).endObject().endObject()
+ .endObject().endObject().string();
+
+ DocumentMapper mapper2 = parser.parse("type", new CompressedXContent(mapping));
+
+ assertEquals(mapping, mapper2.mappingSource().toString());
+
+ ThrowingRunnable runnable = () -> mapper2.parse("test", "type", "1", XContentFactory.jsonBuilder()
+ .startObject()
+ .field("field", "123")
+ .endObject()
+ .bytes());
+ MapperParsingException e = expectThrows(MapperParsingException.class, runnable);
+ assertThat(e.getCause().getMessage(), containsString("passed as String"));
+ }
+
+ public void testIgnoreMalformed() throws Exception {
+ String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject("properties").startObject("field").field("type", "scaled_float")
+ .field("scaling_factor", 10.0).endObject().endObject()
+ .endObject().endObject().string();
+
+ DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping));
+
+ assertEquals(mapping, mapper.mappingSource().toString());
+
+ ThrowingRunnable runnable = () -> mapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
+ .startObject()
+ .field("field", "a")
+ .endObject()
+ .bytes());
+ MapperParsingException e = expectThrows(MapperParsingException.class, runnable);
+ assertThat(e.getCause().getMessage(), containsString("For input string: \"a\""));
+
+ mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject("properties").startObject("field").field("type", "scaled_float")
+ .field("scaling_factor", 10.0).field("ignore_malformed", true).endObject().endObject()
+ .endObject().endObject().string();
+
+ DocumentMapper mapper2 = parser.parse("type", new CompressedXContent(mapping));
+
+ ParsedDocument doc = mapper2.parse("test", "type", "1", XContentFactory.jsonBuilder()
+ .startObject()
+ .field("field", "a")
+ .endObject()
+ .bytes());
+
+ IndexableField[] fields = doc.rootDoc().getFields("field");
+ assertEquals(0, fields.length);
+ }
+
+ public void testIncludeInAll() throws Exception {
+ String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject("properties").startObject("field").field("type", "scaled_float")
+ .field("scaling_factor", 10.0).endObject().endObject()
+ .endObject().endObject().string();
+
+ DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping));
+
+ assertEquals(mapping, mapper.mappingSource().toString());
+
+ ParsedDocument doc = mapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
+ .startObject()
+ .field("field", 123)
+ .endObject()
+ .bytes());
+
+ IndexableField[] fields = doc.rootDoc().getFields("_all");
+ assertEquals(1, fields.length);
+ assertEquals("123", fields[0].stringValue());
+
+ mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject("properties").startObject("field")
+ .field("type", "scaled_float").field("scaling_factor", 10.0)
+ .field("include_in_all", false).endObject().endObject()
+ .endObject().endObject().string();
+
+ mapper = parser.parse("type", new CompressedXContent(mapping));
+
+ assertEquals(mapping, mapper.mappingSource().toString());
+
+ doc = mapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
+ .startObject()
+ .field("field", 123)
+ .endObject()
+ .bytes());
+
+ fields = doc.rootDoc().getFields("_all");
+ assertEquals(0, fields.length);
+ }
+
+ public void testNullValue() throws IOException {
+ String mapping = XContentFactory.jsonBuilder().startObject()
+ .startObject("type")
+ .startObject("properties")
+ .startObject("field")
+ .field("type", "scaled_float")
+ .field("scaling_factor", 10.0)
+ .endObject()
+ .endObject()
+ .endObject().endObject().string();
+
+ DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping));
+ assertEquals(mapping, mapper.mappingSource().toString());
+
+ ParsedDocument doc = mapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
+ .startObject()
+ .nullField("field")
+ .endObject()
+ .bytes());
+ assertArrayEquals(new IndexableField[0], doc.rootDoc().getFields("field"));
+
+ mapping = XContentFactory.jsonBuilder().startObject()
+ .startObject("type")
+ .startObject("properties")
+ .startObject("field")
+ .field("type", "scaled_float")
+ .field("scaling_factor", 10.0)
+ .field("null_value", 2.5)
+ .endObject()
+ .endObject()
+ .endObject().endObject().string();
+
+ mapper = parser.parse("type", new CompressedXContent(mapping));
+ assertEquals(mapping, mapper.mappingSource().toString());
+
+ doc = mapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
+ .startObject()
+ .nullField("field")
+ .endObject()
+ .bytes());
+ IndexableField[] fields = doc.rootDoc().getFields("field");
+ assertEquals(2, fields.length);
+ IndexableField pointField = fields[0];
+ assertEquals(1, pointField.fieldType().pointDimensionCount());
+ assertFalse(pointField.fieldType().stored());
+ assertEquals(25, pointField.numericValue().longValue());
+ IndexableField dvField = fields[1];
+ assertEquals(DocValuesType.SORTED_NUMERIC, dvField.fieldType().docValuesType());
+ assertFalse(dvField.fieldType().stored());
+ }
+}
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/core/ScaledFloatFieldTypeTests.java b/core/src/test/java/org/elasticsearch/index/mapper/core/ScaledFloatFieldTypeTests.java
new file mode 100644
index 00000000000..2b05c4cc589
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/index/mapper/core/ScaledFloatFieldTypeTests.java
@@ -0,0 +1,205 @@
+/*
+ * 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.index.mapper.core;
+
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.DoublePoint;
+import org.apache.lucene.document.LongPoint;
+import org.apache.lucene.document.SortedNumericDocValuesField;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.util.IOUtils;
+import org.elasticsearch.Version;
+import org.elasticsearch.action.fieldstats.FieldStats;
+import org.elasticsearch.cluster.metadata.IndexMetaData;
+import org.elasticsearch.common.settings.Settings;
+import org.elasticsearch.index.IndexSettings;
+import org.elasticsearch.index.fielddata.AtomicNumericFieldData;
+import org.elasticsearch.index.fielddata.IndexNumericFieldData;
+import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;
+import org.elasticsearch.index.mapper.FieldTypeTestCase;
+import org.elasticsearch.index.mapper.MappedFieldType;
+import org.junit.Before;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+public class ScaledFloatFieldTypeTests extends FieldTypeTestCase {
+
+ @Override
+ protected MappedFieldType createDefaultFieldType() {
+ ScaledFloatFieldMapper.ScaledFloatFieldType ft = new ScaledFloatFieldMapper.ScaledFloatFieldType();
+ ft.setScalingFactor(100);
+ return ft;
+ }
+
+ @Before
+ public void setupProperties() {
+ addModifier(new Modifier("scaling_factor", false) {
+ @Override
+ public void modify(MappedFieldType ft) {
+ ScaledFloatFieldMapper.ScaledFloatFieldType tft = (ScaledFloatFieldMapper.ScaledFloatFieldType)ft;
+ tft.setScalingFactor(10);
+ }
+ @Override
+ public void normalizeOther(MappedFieldType other) {
+ super.normalizeOther(other);
+ ((ScaledFloatFieldMapper.ScaledFloatFieldType) other).setScalingFactor(100);
+ }
+ });
+ }
+
+ public void testTermQuery() {
+ ScaledFloatFieldMapper.ScaledFloatFieldType ft = new ScaledFloatFieldMapper.ScaledFloatFieldType();
+ ft.setName("scaled_float");
+ ft.setScalingFactor(0.1 + randomDouble() * 100);
+ double value = (randomDouble() * 2 - 1) * 10000;
+ long scaledValue = Math.round(value * ft.getScalingFactor());
+ assertEquals(LongPoint.newExactQuery("scaled_float", scaledValue), ft.termQuery(value, null));
+ }
+
+ public void testTermsQuery() {
+ ScaledFloatFieldMapper.ScaledFloatFieldType ft = new ScaledFloatFieldMapper.ScaledFloatFieldType();
+ ft.setName("scaled_float");
+ ft.setScalingFactor(0.1 + randomDouble() * 100);
+ double value1 = (randomDouble() * 2 - 1) * 10000;
+ long scaledValue1 = Math.round(value1 * ft.getScalingFactor());
+ double value2 = (randomDouble() * 2 - 1) * 10000;
+ long scaledValue2 = Math.round(value2 * ft.getScalingFactor());
+ assertEquals(
+ LongPoint.newSetQuery("scaled_float", scaledValue1, scaledValue2),
+ ft.termsQuery(Arrays.asList(value1, value2), null));
+ }
+
+ public void testRangeQuery() throws IOException {
+ // make sure the accuracy loss of scaled floats only occurs at index time
+ // this test checks that searching scaled floats yields the same results as
+ // searching doubles that are rounded to the closest half float
+ ScaledFloatFieldMapper.ScaledFloatFieldType ft = new ScaledFloatFieldMapper.ScaledFloatFieldType();
+ ft.setName("scaled_float");
+ ft.setScalingFactor(0.1 + randomDouble() * 100);
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(null));
+ final int numDocs = 1000;
+ for (int i = 0; i < numDocs; ++i) {
+ Document doc = new Document();
+ double value = (randomDouble() * 2 - 1) * 10000;
+ long scaledValue = Math.round(value * ft.getScalingFactor());
+ double rounded = scaledValue / ft.getScalingFactor();
+ doc.add(new LongPoint("scaled_float", scaledValue));
+ doc.add(new DoublePoint("double", rounded));
+ w.addDocument(doc);
+ }
+ final DirectoryReader reader = DirectoryReader.open(w);
+ w.close();
+ IndexSearcher searcher = newSearcher(reader);
+ final int numQueries = 1000;
+ for (int i = 0; i < numQueries; ++i) {
+ double l = (randomDouble() * 2 - 1) * 10000;
+ double u = (randomDouble() * 2 - 1) * 10000;
+ boolean includeLower = randomBoolean();
+ boolean includeUpper = randomBoolean();
+ Query doubleQ = NumberFieldMapper.NumberType.DOUBLE.rangeQuery("double", l, u, includeLower, includeUpper);
+ Query scaledFloatQ = ft.rangeQuery(l, u, includeLower, includeUpper);
+ assertEquals(searcher.count(doubleQ), searcher.count(scaledFloatQ));
+ }
+ IOUtils.close(reader, dir);
+ }
+
+ public void testValueForSearch() {
+ ScaledFloatFieldMapper.ScaledFloatFieldType ft = new ScaledFloatFieldMapper.ScaledFloatFieldType();
+ ft.setName("scaled_float");
+ ft.setScalingFactor(0.1 + randomDouble() * 100);
+ assertNull(ft.valueForSearch(null));
+ assertEquals(10/ft.getScalingFactor(), ft.valueForSearch(10L));
+ }
+
+ public void testStats() throws IOException {
+ ScaledFloatFieldMapper.ScaledFloatFieldType ft = new ScaledFloatFieldMapper.ScaledFloatFieldType();
+ ft.setName("scaled_float");
+ ft.setScalingFactor(0.1 + randomDouble() * 100);
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(null));
+ try (DirectoryReader reader = DirectoryReader.open(w)) {
+ assertNull(ft.stats(reader));
+ }
+ Document doc = new Document();
+ LongPoint point = new LongPoint("scaled_float", -1);
+ doc.add(point);
+ w.addDocument(doc);
+ point.setLongValue(10);
+ w.addDocument(doc);
+ try (DirectoryReader reader = DirectoryReader.open(w)) {
+ FieldStats> stats = ft.stats(reader);
+ assertEquals(-1/ft.getScalingFactor(), stats.getMinValue());
+ assertEquals(10/ft.getScalingFactor(), stats.getMaxValue());
+ assertEquals(2, stats.getMaxDoc());
+ }
+ w.deleteAll();
+ try (DirectoryReader reader = DirectoryReader.open(w)) {
+ assertNull(ft.stats(reader));
+ }
+ IOUtils.close(w, dir);
+ }
+
+ public void testFieldData() throws IOException {
+ ScaledFloatFieldMapper.ScaledFloatFieldType ft = new ScaledFloatFieldMapper.ScaledFloatFieldType();
+ ft.setScalingFactor(0.1 + randomDouble() * 100);
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(null));
+ Document doc = new Document();
+ doc.add(new SortedNumericDocValuesField("scaled_float1", 10));
+ doc.add(new SortedNumericDocValuesField("scaled_float2", 5));
+ doc.add(new SortedNumericDocValuesField("scaled_float2", 12));
+ w.addDocument(doc);
+ try (DirectoryReader reader = DirectoryReader.open(w)) {
+ IndexMetaData indexMetadata = new IndexMetaData.Builder("index").settings(
+ Settings.builder()
+ .put("index.version.created", Version.CURRENT)
+ .put("index.number_of_shards", 1)
+ .put("index.number_of_replicas", 0).build()).build();
+ IndexSettings indexSettings = new IndexSettings(indexMetadata, Settings.EMPTY);
+
+ // single-valued
+ ft.setName("scaled_float1");
+ IndexNumericFieldData fielddata = (IndexNumericFieldData) ft.fielddataBuilder().build(indexSettings, ft, null, null, null);
+ AtomicNumericFieldData leafFieldData = fielddata.load(reader.leaves().get(0));
+ SortedNumericDoubleValues values = leafFieldData.getDoubleValues();
+ values.setDocument(0);
+ assertEquals(1, values.count());
+ assertEquals(10/ft.getScalingFactor(), values.valueAt(0), 10e-5);
+
+ // multi-valued
+ ft.setName("scaled_float2");
+ fielddata = (IndexNumericFieldData) ft.fielddataBuilder().build(indexSettings, ft, null, null, null);
+ leafFieldData = fielddata.load(reader.leaves().get(0));
+ values = leafFieldData.getDoubleValues();
+ values.setDocument(0);
+ assertEquals(2, values.count());
+ assertEquals(5/ft.getScalingFactor(), values.valueAt(0), 10e-5);
+ assertEquals(12/ft.getScalingFactor(), values.valueAt(1), 10e-5);
+ }
+ IOUtils.close(w, dir);
+ }
+}
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/core/TextFieldMapperTests.java b/core/src/test/java/org/elasticsearch/index/mapper/core/TextFieldMapperTests.java
index 224d512cb53..6ef040233cc 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/core/TextFieldMapperTests.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/core/TextFieldMapperTests.java
@@ -44,6 +44,7 @@ import org.elasticsearch.test.ESSingleNodeTestCase;
import org.junit.Before;
import java.io.IOException;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@@ -474,4 +475,32 @@ public class TextFieldMapperTests extends ESSingleNodeTestCase {
Exception e = expectThrows(MapperParsingException.class, () -> parser.parse("type", new CompressedXContent(mapping)));
assertEquals("[analyzer] must not have a [null] value", e.getMessage());
}
+
+ public void testNotIndexedFieldPositionIncrement() throws IOException {
+ String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject("properties").startObject("field")
+ .field("type", "text")
+ .field("index", false)
+ .field("position_increment_gap", 10)
+ .endObject().endObject().endObject().endObject().string();
+
+ IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
+ () -> parser.parse("type", new CompressedXContent(mapping)));
+ assertEquals("Cannot set position_increment_gap on field [field] without positions enabled", e.getMessage());
+ }
+
+ public void testAnalyzedFieldPositionIncrementWithoutPositions() throws IOException {
+ for (String indexOptions : Arrays.asList("docs", "freqs")) {
+ String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
+ .startObject("properties").startObject("field")
+ .field("type", "text")
+ .field("index_options", indexOptions)
+ .field("position_increment_gap", 10)
+ .endObject().endObject().endObject().endObject().string();
+
+ IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
+ () -> parser.parse("type", new CompressedXContent(mapping)));
+ assertEquals("Cannot set position_increment_gap on field [field] without positions enabled", e.getMessage());
+ }
+ }
}
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/core/TokenCountFieldMapperIntegrationIT.java b/core/src/test/java/org/elasticsearch/index/mapper/core/TokenCountFieldMapperIntegrationIT.java
index 31e4e2d0923..da0c3d081af 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/core/TokenCountFieldMapperIntegrationIT.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/core/TokenCountFieldMapperIntegrationIT.java
@@ -166,9 +166,9 @@ public class TokenCountFieldMapperIntegrationIT extends ESIntegTestCase {
private SearchRequestBuilder prepareSearch() {
SearchRequestBuilder request = client().prepareSearch("test").setTypes("test");
- request.addField("foo.token_count");
+ request.addStoredField("foo.token_count");
if (loadCountedFields) {
- request.addField("foo");
+ request.addStoredField("foo");
}
return request;
}
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalValuesMapperIntegrationIT.java b/core/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalValuesMapperIntegrationIT.java
index 350cbc43f9a..99dcaebbc6f 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalValuesMapperIntegrationIT.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/externalvalues/ExternalValuesMapperIntegrationIT.java
@@ -46,7 +46,6 @@ public class ExternalValuesMapperIntegrationIT extends ESIntegTestCase {
.startObject("field").field("type", FakeStringFieldMapper.CONTENT_TYPE).endObject()
.endObject()
.endObject().endObject()).execute().get();
- ensureYellow("test-idx");
index("test-idx", "type", "1", XContentFactory.jsonBuilder()
.startObject()
@@ -96,7 +95,6 @@ public class ExternalValuesMapperIntegrationIT extends ESIntegTestCase {
.startObject("field").field("type", ExternalMapperPlugin.EXTERNAL).endObject()
.endObject()
.endObject().endObject()).execute().get();
- ensureYellow("test-idx");
index("test-idx", "type", "1", XContentFactory.jsonBuilder()
.startObject()
@@ -150,7 +148,6 @@ public class ExternalValuesMapperIntegrationIT extends ESIntegTestCase {
.endObject()
.endObject()
.endObject().endObject().endObject()).execute().get();
- ensureYellow("test-idx");
index("test-idx", "doc", "1", "f", "This is my text");
refresh();
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/geo/GeoPointFieldMapperTests.java b/core/src/test/java/org/elasticsearch/index/mapper/geo/GeoPointFieldMapperTests.java
index 202afd7a4b1..14dd370fbfd 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/geo/GeoPointFieldMapperTests.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/geo/GeoPointFieldMapperTests.java
@@ -816,7 +816,7 @@ public class GeoPointFieldMapperTests extends ESSingleNodeTestCase {
.field("lon", -74.0059731).endObject().endObject()).setRefreshPolicy(IMMEDIATE).get();
// match all search with geohash field
- SearchResponse searchResponse = client().prepareSearch().addField("location.geohash").setQuery(matchAllQuery()).execute().actionGet();
+ SearchResponse searchResponse = client().prepareSearch().addStoredField("location.geohash").setQuery(matchAllQuery()).execute().actionGet();
Map m = searchResponse.getHits().getAt(0).getFields();
// ensure single geohash was indexed
@@ -841,7 +841,7 @@ public class GeoPointFieldMapperTests extends ESSingleNodeTestCase {
.field("lon", -74.0059731).endObject().endObject()).setRefreshPolicy(IMMEDIATE).get();
// match all search with geohash field (includes prefixes)
- SearchResponse searchResponse = client().prepareSearch().addField("location.geohash").setQuery(matchAllQuery()).execute().actionGet();
+ SearchResponse searchResponse = client().prepareSearch().addStoredField("location.geohash").setQuery(matchAllQuery()).execute().actionGet();
Map m = searchResponse.getHits().getAt(0).getFields();
List