Skip to content

Commit 9dd155c

Browse files
authored
Convert most awaitBusy calls to assertBusy (#45794)
Closes #28450. Convert most `awaitBusy` calls to `assertBusy`, and use asserts where possible. Follows on from #28548 by @liketic. There were a small number of places where it didn't make sense to me to call `assertBusy`, so I kept the existing calls but renamed the method to `waitUntil`. This was partly to better reflect its usage, and partly so that anyone trying to add a new call to awaitBusy wouldn't be able to find it. I also didn't change the usage in `TransportStopRollupAction` as the comments state that the local awaitBusy method is a temporary copy-and-paste. Other changes: * Rework `waitForDocs` to scale its timeout. Instead of calling `assertBusy` in a loop, work out a reasonable overall timeout and await just once. * Some tests failed after switching to `assertBusy` and had to be fixed. * Correct the expect templates in AbstractUpgradeTestCase. The ES Security team confirmed that they don't use templates any more, so remove this from the expected templates. Also rewrite how the setup code checks for templates, in order to give more information. * Remove an expected ML template from XPackRestTestConstants The ML team advised that the ML tests shouldn't be waiting for any `.ml-notifications*` templates, since such checks should happen in the production code instead. * Also rework the template checking code in `XPackRestTestHelper` to give more helpful failure messages.
1 parent d6bf8e7 commit 9dd155c

File tree

56 files changed

+497
-513
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+497
-513
lines changed

client/rest-high-level/src/test/java/org/elasticsearch/client/MachineLearningIT.java

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -872,7 +872,7 @@ private String createExpiredData(String jobId) throws Exception {
872872
// b) is slightly more efficient since we may not need to wait an entire second for the timestamp to increment
873873
assertBusy(() -> {
874874
long timeNow = System.currentTimeMillis() / 1000;
875-
assertFalse(prevJobTimeStamp >= timeNow);
875+
assertThat(prevJobTimeStamp, lessThan(timeNow));
876876
});
877877

878878
// Update snapshot timestamp to force it out of snapshot retention window
@@ -890,7 +890,8 @@ private String createExpiredData(String jobId) throws Exception {
890890
waitForForecastToComplete(jobId, forecastJobResponse.getForecastId());
891891

892892
// Wait for the forecast to expire
893-
awaitBusy(() -> false, 1, TimeUnit.SECONDS);
893+
// FIXME: We should wait for something specific to change, rather than waiting for time to pass.
894+
waitUntil(() -> false, 1, TimeUnit.SECONDS);
894895

895896
// Run up to now
896897
startDatafeed(datafeedId, String.valueOf(0), String.valueOf(nowMillis));
@@ -934,7 +935,9 @@ public void testDeleteExpiredData() throws Exception {
934935

935936
assertTrue(response.getDeleted());
936937

937-
awaitBusy(() -> false, 1, TimeUnit.SECONDS);
938+
// Wait for the forecast to expire
939+
// FIXME: We should wait for something specific to change, rather than waiting for time to pass.
940+
waitUntil(() -> false, 1, TimeUnit.SECONDS);
938941

939942
GetModelSnapshotsRequest getModelSnapshotsRequest1 = new GetModelSnapshotsRequest(jobId);
940943
GetModelSnapshotsResponse getModelSnapshotsResponse1 = execute(getModelSnapshotsRequest1, machineLearningClient::getModelSnapshots,
@@ -2049,8 +2052,6 @@ private void updateModelSnapshotTimestamp(String jobId, String timestamp) throws
20492052
highLevelClient().update(updateSnapshotRequest, RequestOptions.DEFAULT);
20502053
}
20512054

2052-
2053-
20542055
private String createAndPutDatafeed(String jobId, String indexName) throws IOException {
20552056
String datafeedId = jobId + "-feed";
20562057
DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, jobId)

modules/reindex/src/test/java/org/elasticsearch/client/documentation/ReindexDocumentationIT.java

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ public void testUpdateByQuery() {
195195
}
196196
}
197197

198-
public void testTasks() throws InterruptedException {
198+
public void testTasks() throws Exception {
199199
final Client client = client();
200200
final ReindexRequestBuilder builder = reindexAndPartiallyBlock();
201201

@@ -279,7 +279,7 @@ public void onFailure(Exception e) {
279279
* Similar to what CancelTests does: blocks some operations to be able to catch some tasks in running state
280280
* @see CancelTests#testCancel(String, AbstractBulkByScrollRequestBuilder, CancelTests.CancelAssertion, Matcher)
281281
*/
282-
private ReindexRequestBuilder reindexAndPartiallyBlock() throws InterruptedException {
282+
private ReindexRequestBuilder reindexAndPartiallyBlock() throws Exception {
283283
final Client client = client();
284284
final int numDocs = randomIntBetween(10, 100);
285285
ALLOWED_OPERATIONS.release(numDocs);
@@ -305,9 +305,12 @@ private ReindexRequestBuilder reindexAndPartiallyBlock() throws InterruptedExcep
305305
builder.execute();
306306

307307
// 10 seconds is usually fine but on heavily loaded machines this can take a while
308-
assertTrue("updates blocked", awaitBusy(
309-
() -> ALLOWED_OPERATIONS.hasQueuedThreads() && ALLOWED_OPERATIONS.availablePermits() == 0,
310-
1, TimeUnit.MINUTES));
308+
assertBusy(
309+
() -> {
310+
assertTrue("Expected some queued threads", ALLOWED_OPERATIONS.hasQueuedThreads());
311+
assertEquals("Expected that no permits are available", 0, ALLOWED_OPERATIONS.availablePermits());
312+
},
313+
1, TimeUnit.MINUTES);
311314
return builder;
312315
}
313316

modules/reindex/src/test/java/org/elasticsearch/index/reindex/CancelTests.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,10 +117,9 @@ private void testCancel(String action, AbstractBulkByScrollRequestBuilder<?, ?>
117117
* exhausted their slice while others might have quite a bit left
118118
* to work on. We can't control that. */
119119
logger.debug("waiting for updates to be blocked");
120-
boolean blocked = awaitBusy(
121-
() -> ALLOWED_OPERATIONS.hasQueuedThreads() && ALLOWED_OPERATIONS.availablePermits() == 0,
120+
assertBusy(
121+
() -> assertTrue("updates blocked", ALLOWED_OPERATIONS.hasQueuedThreads() && ALLOWED_OPERATIONS.availablePermits() == 0),
122122
1, TimeUnit.MINUTES); // 10 seconds is usually fine but on heavily loaded machines this can take a while
123-
assertTrue("updates blocked", blocked);
124123

125124
// Status should show the task running
126125
TaskInfo mainTask = findTaskToCancel(action, builder.request().getSlices());

qa/smoke-test-http/src/test/java/org/elasticsearch/http/SearchRestCancellationIT.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ public Map<String, Function<Map<String, Object>, Object>> pluginScripts() {
240240
LogManager.getLogger(SearchRestCancellationIT.class).info("Blocking on the document {}", fieldsLookup.get("_id"));
241241
hits.incrementAndGet();
242242
try {
243-
awaitBusy(() -> shouldBlock.get() == false);
243+
waitUntil(() -> shouldBlock.get() == false);
244244
} catch (Exception e) {
245245
throw new RuntimeException(e);
246246
}

server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/CancellableTasksTests.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ protected NodeResponse nodeOperation(CancellableNodeRequest request, Task task)
167167
// Simulate a job that takes forever to finish
168168
// Using periodic checks method to identify that the task was cancelled
169169
try {
170-
awaitBusy(() -> {
170+
waitUntil(() -> {
171171
if (((CancellableTask) task).isCancelled()) {
172172
throw new TaskCancelledException("Cancelled");
173173
}

server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TestTaskPlugin.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@
7575
import java.util.Objects;
7676

7777
import static org.elasticsearch.action.admin.cluster.node.tasks.get.GetTaskAction.TASKS_ORIGIN;
78-
import static org.elasticsearch.test.ESTestCase.awaitBusy;
78+
import static org.elasticsearch.test.ESTestCase.waitUntil;
7979

8080
/**
8181
* A plugin that adds a cancellable blocking test task of integration testing of the task manager.
@@ -305,7 +305,7 @@ protected NodeResponse nodeOperation(NodeRequest request, Task task) {
305305
logger.info("Test task started on the node {}", clusterService.localNode());
306306
if (request.shouldBlock) {
307307
try {
308-
awaitBusy(() -> {
308+
waitUntil(() -> {
309309
if (((CancellableTask) task).isCancelled()) {
310310
throw new RuntimeException("Cancelled!");
311311
}

server/src/test/java/org/elasticsearch/cluster/MinimumMasterNodesIT.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,10 +128,11 @@ public void testTwoNodesNoMasterBlock() throws Exception {
128128
Settings masterDataPathSettings = internalCluster().dataPathSettings(masterNode);
129129
internalCluster().stopRandomNode(InternalTestCluster.nameFilter(masterNode));
130130

131-
awaitBusy(() -> {
131+
assertBusy(() -> {
132132
ClusterState clusterState = client().admin().cluster().prepareState().setLocal(true).execute().actionGet().getState();
133-
return clusterState.blocks().hasGlobalBlockWithId(NoMasterBlockService.NO_MASTER_BLOCK_ID);
133+
assertTrue(clusterState.blocks().hasGlobalBlockWithId(NoMasterBlockService.NO_MASTER_BLOCK_ID));
134134
});
135+
135136
state = client().admin().cluster().prepareState().setLocal(true).execute().actionGet().getState();
136137
assertThat(state.blocks().hasGlobalBlockWithId(NoMasterBlockService.NO_MASTER_BLOCK_ID), equalTo(true));
137138
// verify that both nodes are still in the cluster state but there is no master

server/src/test/java/org/elasticsearch/cluster/NoMasterNodeIT.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -219,11 +219,10 @@ public void testNoMasterActionsWriteMasterBlock() throws Exception {
219219

220220
final Client clientToMasterlessNode = client();
221221

222-
assertTrue(awaitBusy(() -> {
223-
ClusterState state = clientToMasterlessNode.admin().cluster().prepareState().setLocal(true).get().getState();
224-
return state.blocks().hasGlobalBlockWithId(NoMasterBlockService.NO_MASTER_BLOCK_ID);
225-
}
226-
));
222+
assertBusy(() -> {
223+
ClusterState state = clientToMasterlessNode.admin().cluster().prepareState().setLocal(true).get().getState();
224+
assertTrue(state.blocks().hasGlobalBlockWithId(NoMasterBlockService.NO_MASTER_BLOCK_ID));
225+
});
227226

228227
GetResponse getResponse = clientToMasterlessNode.prepareGet("test1", "1").get();
229228
assertExists(getResponse);

server/src/test/java/org/elasticsearch/cluster/allocation/AwarenessAllocationIT.java

Lines changed: 37 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,11 @@
3838
import java.util.Arrays;
3939
import java.util.List;
4040
import java.util.concurrent.TimeUnit;
41+
import java.util.stream.Collectors;
4142

4243
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
4344
import static org.hamcrest.Matchers.anyOf;
45+
import static org.hamcrest.Matchers.empty;
4446
import static org.hamcrest.Matchers.equalTo;
4547

4648
@ClusterScope(scope= ESIntegTestCase.Scope.TEST, numDataNodes =0, minNumDataNodes = 2)
@@ -78,40 +80,43 @@ public void testSimpleAwareness() throws Exception {
7880
final String node3 = internalCluster().startNode(Settings.builder().put(commonSettings).put("node.attr.rack_id", "rack_2").build());
7981

8082
// On slow machines the initial relocation might be delayed
81-
assertThat(awaitBusy(
82-
() -> {
83-
logger.info("--> waiting for no relocation");
84-
ClusterHealthResponse clusterHealth = client().admin().cluster().prepareHealth()
85-
.setIndices("test1", "test2")
86-
.setWaitForEvents(Priority.LANGUID)
87-
.setWaitForGreenStatus()
88-
.setWaitForNodes("3")
89-
.setWaitForNoRelocatingShards(true)
90-
.get();
91-
if (clusterHealth.isTimedOut()) {
92-
return false;
93-
}
94-
95-
logger.info("--> checking current state");
96-
ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
97-
// check that closed indices are effectively closed
98-
if (indicesToClose.stream().anyMatch(index -> clusterState.metaData().index(index).getState() != State.CLOSE)) {
99-
return false;
100-
}
101-
// verify that we have all the primaries on node3
102-
ObjectIntHashMap<String> counts = new ObjectIntHashMap<>();
103-
for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) {
104-
for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
105-
for (ShardRouting shardRouting : indexShardRoutingTable) {
106-
counts.addTo(clusterState.nodes().get(shardRouting.currentNodeId()).getName(), 1);
107-
}
83+
assertBusy(
84+
() -> {
85+
logger.info("--> waiting for no relocation");
86+
ClusterHealthResponse clusterHealth = client().admin().cluster().prepareHealth()
87+
.setIndices("test1", "test2")
88+
.setWaitForEvents(Priority.LANGUID)
89+
.setWaitForGreenStatus()
90+
.setWaitForNodes("3")
91+
.setWaitForNoRelocatingShards(true)
92+
.get();
93+
94+
assertThat("Cluster health request timed out", clusterHealth.isTimedOut(), equalTo(false));
95+
96+
logger.info("--> checking current state");
97+
ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
98+
99+
// check that closed indices are effectively closed
100+
final List<String> notClosedIndices =
101+
indicesToClose.stream()
102+
.filter(index -> clusterState.metaData().index(index).getState() != State.CLOSE)
103+
.collect(Collectors.toList());
104+
assertThat("Some indices not closed", notClosedIndices, empty());
105+
106+
// verify that we have all the primaries on node3
107+
ObjectIntHashMap<String> counts = new ObjectIntHashMap<>();
108+
for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) {
109+
for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
110+
for (ShardRouting shardRouting : indexShardRoutingTable) {
111+
counts.addTo(clusterState.nodes().get(shardRouting.currentNodeId()).getName(), 1);
108112
}
109113
}
110-
return counts.get(node3) == totalPrimaries;
111-
},
112-
10,
113-
TimeUnit.SECONDS
114-
), equalTo(true));
114+
}
115+
assertThat(counts.get(node3), equalTo(totalPrimaries));
116+
},
117+
10,
118+
TimeUnit.SECONDS
119+
);
115120
}
116121

117122
public void testAwarenessZones() {

server/src/test/java/org/elasticsearch/cluster/service/ClusterServiceIT.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -400,8 +400,8 @@ public void clusterStateProcessed(String source, ClusterState oldState, ClusterS
400400
block1.countDown();
401401
invoked2.await();
402402

403-
// whenever we test for no tasks, we need to awaitBusy since this is a live node
404-
assertTrue(awaitBusy(() -> clusterService.getMasterService().pendingTasks().isEmpty()));
403+
// whenever we test for no tasks, we need to wait since this is a live node
404+
assertBusy(() -> assertTrue("Pending tasks not empty", clusterService.getMasterService().pendingTasks().isEmpty()));
405405
waitNoPendingTasksOnAll();
406406

407407
final CountDownLatch block2 = new CountDownLatch(1);

0 commit comments

Comments
 (0)