forked from elastic/elasticsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TransportDeleteByQueryActionTests.java
501 lines (416 loc) · 21.3 KB
/
TransportDeleteByQueryActionTests.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/*
* 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.deletebyquery;
import com.google.common.base.Predicate;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ShardOperationFailedException;
import org.elasticsearch.action.admin.cluster.node.stats.NodeStats;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.search.ClearScrollResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.support.QuerySourceBuilder;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.text.StringText;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.CollectionUtils;
import org.elasticsearch.common.util.concurrent.CountDown;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.internal.InternalSearchHit;
import org.elasticsearch.test.ESSingleNodeTestCase;
import org.junit.Test;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.hamcrest.Matchers.equalTo;
public class TransportDeleteByQueryActionTests extends ESSingleNodeTestCase {
@Test
public void testExecuteScanFailsOnMissingIndex() {
DeleteByQueryRequest delete = new DeleteByQueryRequest().indices("none");
TestActionListener listener = new TestActionListener();
newAsyncAction(delete, listener).executeScan();
waitForCompletion("scan request should fail on missing index", listener);
assertFailure(listener, "no such index");
assertSearchContextsClosed();
}
@Test
public void testExecuteScanFailsOnMalformedQuery() {
createIndex("test");
DeleteByQueryRequest delete = new DeleteByQueryRequest().indices("test").source("{...}");
TestActionListener listener = new TestActionListener();
newAsyncAction(delete, listener).executeScan();
waitForCompletion("scan request should fail on malformed query", listener);
assertFailure(listener, "all shards failed");
assertSearchContextsClosed();
}
@Test
public void testExecuteScan() {
createIndex("test");
final int numDocs = randomIntBetween(1, 200);
for (int i = 1; i <= numDocs; i++) {
client().prepareIndex("test", "type").setSource("num", i).get();
}
client().admin().indices().prepareRefresh("test").get();
assertHitCount(client().prepareCount("test").get(), numDocs);
final long limit = randomIntBetween(0, numDocs);
DeleteByQueryRequest delete = new DeleteByQueryRequest().indices("test").source(new QuerySourceBuilder().setQuery(boolQuery().must(rangeQuery("num").lte(limit))));
TestActionListener listener = new TestActionListener();
newAsyncAction(delete, listener).executeScan();
waitForCompletion("scan request should return the exact number of documents", listener);
assertNoFailures(listener);
DeleteByQueryResponse response = listener.getResponse();
assertNotNull(response);
assertThat(response.getTotalFound(), equalTo(limit));
assertThat(response.getTotalDeleted(), equalTo(limit));
assertSearchContextsClosed();
}
@Test
public void testExecuteScrollFailsOnMissingScrollId() {
DeleteByQueryRequest delete = new DeleteByQueryRequest();
TestActionListener listener = new TestActionListener();
newAsyncAction(delete, listener).executeScroll(null);
waitForCompletion("scroll request should fail on missing scroll id", listener);
assertFailure(listener, "scrollId is missing");
assertSearchContextsClosed();
}
@Test
public void testExecuteScrollFailsOnMalformedScrollId() {
DeleteByQueryRequest delete = new DeleteByQueryRequest();
TestActionListener listener = new TestActionListener();
newAsyncAction(delete, listener).executeScroll("123");
waitForCompletion("scroll request should fail on malformed scroll id", listener);
assertFailure(listener, "Failed to decode scrollId");
assertSearchContextsClosed();
}
@Test
public void testExecuteScrollFailsOnExpiredScrollId() {
final long numDocs = randomIntBetween(1, 100);
for (int i = 1; i <= numDocs; i++) {
client().prepareIndex("test", "type").setSource("num", i).get();
}
client().admin().indices().prepareRefresh("test").get();
assertHitCount(client().prepareCount("test").get(), numDocs);
SearchResponse searchResponse = client().prepareSearch("test").setSearchType(SearchType.SCAN).setScroll(TimeValue.timeValueSeconds(10)).get();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(numDocs));
String scrollId = searchResponse.getScrollId();
assertTrue(Strings.hasText(scrollId));
ClearScrollResponse clearScrollResponse = client().prepareClearScroll().addScrollId(scrollId).get();
assertTrue(clearScrollResponse.isSucceeded());
DeleteByQueryRequest delete = new DeleteByQueryRequest().indices("test");
TestActionListener listener = new TestActionListener();
newAsyncAction(delete, listener).executeScroll(searchResponse.getScrollId());
waitForCompletion("scroll request returns zero documents on expired scroll id", listener);
assertNull(listener.getError());
assertShardFailuresContains(listener.getResponse().getShardFailures(), "No search context found");
assertSearchContextsClosed();
}
@Test
public void testExecuteScrollTimedOut() throws InterruptedException {
client().prepareIndex("test", "type").setSource("num", "1").setRefresh(true).get();
SearchResponse searchResponse = client().prepareSearch("test").setSearchType(SearchType.SCAN).setScroll(TimeValue.timeValueSeconds(10)).get();
String scrollId = searchResponse.getScrollId();
assertTrue(Strings.hasText(scrollId));
DeleteByQueryRequest delete = new DeleteByQueryRequest().indices("test").timeout(TimeValue.timeValueSeconds(1));
TestActionListener listener = new TestActionListener();
final TransportDeleteByQueryAction.AsyncDeleteByQueryAction async = newAsyncAction(delete, listener);
awaitBusy(new Predicate<Object>() {
@Override
public boolean apply(Object input) {
// Wait until the action timed out
return async.hasTimedOut();
}
});
async.executeScroll(searchResponse.getScrollId());
waitForCompletion("scroll request returns zero documents on expired scroll id", listener);
assertNull(listener.getError());
assertTrue(listener.getResponse().isTimedOut());
assertThat(listener.getResponse().getTotalDeleted(), equalTo(0L));
assertSearchContextsClosed();
}
@Test
public void testExecuteScrollNoDocuments() {
createIndex("test");
SearchResponse searchResponse = client().prepareSearch("test").setSearchType(SearchType.SCAN).setScroll(TimeValue.timeValueSeconds(10)).get();
String scrollId = searchResponse.getScrollId();
assertTrue(Strings.hasText(scrollId));
DeleteByQueryRequest delete = new DeleteByQueryRequest().indices("test");
TestActionListener listener = new TestActionListener();
newAsyncAction(delete, listener).executeScroll(searchResponse.getScrollId());
waitForCompletion("scroll request returns zero documents", listener);
assertNull(listener.getError());
assertFalse(listener.getResponse().isTimedOut());
assertThat(listener.getResponse().getTotalFound(), equalTo(0L));
assertThat(listener.getResponse().getTotalDeleted(), equalTo(0L));
assertSearchContextsClosed();
}
@Test
public void testExecuteScroll() {
final int numDocs = randomIntBetween(1, 100);
for (int i = 1; i <= numDocs; i++) {
client().prepareIndex("test", "type").setSource("num", i).get();
}
client().admin().indices().prepareRefresh("test").get();
assertHitCount(client().prepareCount("test").get(), numDocs);
final long limit = randomIntBetween(0, numDocs);
SearchResponse searchResponse = client().prepareSearch("test").setSearchType(SearchType.SCAN)
.setScroll(TimeValue.timeValueSeconds(10))
.setQuery(boolQuery().must(rangeQuery("num").lte(limit)))
.addFields("_routing", "_parent")
.setFetchSource(false)
.setVersion(true)
.get();
String scrollId = searchResponse.getScrollId();
assertTrue(Strings.hasText(scrollId));
assertThat(searchResponse.getHits().getTotalHits(), equalTo(limit));
DeleteByQueryRequest delete = new DeleteByQueryRequest().indices("test").size(100).source(boolQuery().must(rangeQuery("num").lte(limit)).buildAsBytes());
TestActionListener listener = new TestActionListener();
newAsyncAction(delete, listener).executeScroll(searchResponse.getScrollId());
waitForCompletion("scroll request should return all documents", listener);
assertNull(listener.getError());
assertFalse(listener.getResponse().isTimedOut());
assertThat(listener.getResponse().getTotalDeleted(), equalTo(limit));
assertSearchContextsClosed();
}
@Test
public void testOnBulkResponse() {
final int nbItems = randomIntBetween(0, 20);
long deleted = 0;
long missing = 0;
long failed = 0;
BulkItemResponse[] items = new BulkItemResponse[nbItems];
for (int i = 0; i < nbItems; i++) {
if (randomBoolean()) {
boolean delete = true;
if (rarely()) {
delete = false;
missing++;
} else {
deleted++;
}
items[i] = new BulkItemResponse(i, "delete", new DeleteResponse("test", "type", String.valueOf(i), 1, delete));
} else {
items[i] = new BulkItemResponse(i, "delete", new BulkItemResponse.Failure("test", "type", String.valueOf(i), new Throwable("item failed")));
failed++;
}
}
// We just need a valid scroll id
createIndex("test");
SearchResponse searchResponse = client().prepareSearch().setSearchType(SearchType.SCAN).setScroll(TimeValue.timeValueSeconds(10)).get();
String scrollId = searchResponse.getScrollId();
assertTrue(Strings.hasText(scrollId));
try {
DeleteByQueryRequest delete = new DeleteByQueryRequest();
TestActionListener listener = new TestActionListener();
newAsyncAction(delete, listener).onBulkResponse(scrollId, new BulkResponse(items, 0L));
waitForCompletion("waiting for bulk response to complete", listener);
assertNoFailures(listener);
assertThat(listener.getResponse().getTotalDeleted(), equalTo(deleted));
assertThat(listener.getResponse().getTotalFailed(), equalTo(failed));
assertThat(listener.getResponse().getTotalMissing(), equalTo(missing));
} finally {
client().prepareClearScroll().addScrollId(scrollId).get();
}
}
@Test
public void testOnBulkResponseMultipleIndices() {
final int nbIndices = randomIntBetween(2, 5);
// Holds counters for the total + all indices
final long[] found = new long[1 + nbIndices];
final long[] deleted = new long[1 + nbIndices];
final long[] missing = new long[1 + nbIndices];
final long[] failed = new long[1 + nbIndices];
final int nbItems = randomIntBetween(0, 100);
found[0] = nbItems;
BulkItemResponse[] items = new BulkItemResponse[nbItems];
for (int i = 0; i < nbItems; i++) {
int index = randomIntBetween(1, nbIndices);
found[index] = found[index] + 1;
if (randomBoolean()) {
boolean delete = true;
if (rarely()) {
delete = false;
missing[0] = missing[0] + 1;
missing[index] = missing[index] + 1;
} else {
deleted[0] = deleted[0] + 1;
deleted[index] = deleted[index] + 1;
}
items[i] = new BulkItemResponse(i, "delete", new DeleteResponse("test-" + index, "type", String.valueOf(i), 1, delete));
} else {
items[i] = new BulkItemResponse(i, "delete", new BulkItemResponse.Failure("test-" + index, "type", String.valueOf(i), new Throwable("item failed")));
failed[0] = failed[0] + 1;
failed[index] = failed[index] + 1;
}
}
// We just need a valid scroll id
createIndex("test");
SearchResponse searchResponse = client().prepareSearch().setSearchType(SearchType.SCAN).setScroll(TimeValue.timeValueSeconds(10)).get();
String scrollId = searchResponse.getScrollId();
assertTrue(Strings.hasText(scrollId));
try {
DeleteByQueryRequest delete = new DeleteByQueryRequest();
TestActionListener listener = new TestActionListener();
newAsyncAction(delete, listener).onBulkResponse(scrollId, new BulkResponse(items, 0L));
waitForCompletion("waiting for bulk response to complete", listener);
assertNoFailures(listener);
assertThat(listener.getResponse().getTotalDeleted(), equalTo(deleted[0]));
assertThat(listener.getResponse().getTotalFailed(), equalTo(failed[0]));
assertThat(listener.getResponse().getTotalMissing(), equalTo(missing[0]));
for (int i = 1; i <= nbIndices; i++) {
IndexDeleteByQueryResponse indexResponse = listener.getResponse().getIndex("test-" + i);
if (found[i] >= 1) {
assertNotNull(indexResponse);
assertThat(indexResponse.getFound(), equalTo(found[i]));
assertThat(indexResponse.getDeleted(), equalTo(deleted[i]));
assertThat(indexResponse.getFailed(), equalTo(failed[i]));
assertThat(indexResponse.getMissing(), equalTo(missing[i]));
} else {
assertNull(indexResponse);
}
}
} finally {
client().prepareClearScroll().addScrollId(scrollId).get();
}
}
@Test
public void testOnBulkFailureNoDocuments() {
DeleteByQueryRequest delete = new DeleteByQueryRequest();
TestActionListener listener = new TestActionListener();
newAsyncAction(delete, listener).onBulkFailure(null, new SearchHit[0], new Throwable("This is a bulk failure"));
waitForCompletion("waiting for bulk failure to complete", listener);
assertFailure(listener, "This is a bulk failure");
}
@Test
public void testOnBulkFailure() {
final int nbDocs = randomIntBetween(0, 20);
SearchHit[] docs = new SearchHit[nbDocs];
for (int i = 0; i < nbDocs; i++) {
InternalSearchHit doc = new InternalSearchHit(randomInt(), String.valueOf(i), new StringText("type"), null);
doc.shard(new SearchShardTarget("node", "test", randomInt()));
docs[i] = doc;
}
DeleteByQueryRequest delete = new DeleteByQueryRequest();
TestActionListener listener = new TestActionListener();
TransportDeleteByQueryAction.AsyncDeleteByQueryAction async = newAsyncAction(delete, listener);
async.onBulkFailure(null, docs, new Throwable("This is a bulk failure"));
waitForCompletion("waiting for bulk failure to complete", listener);
assertFailure(listener, "This is a bulk failure");
DeleteByQueryResponse response = async.buildResponse();
assertThat(response.getTotalFailed(), equalTo((long) nbDocs));
assertThat(response.getTotalDeleted(), equalTo(0L));
}
@Test
public void testFinishHim() {
TestActionListener listener = new TestActionListener();
newAsyncAction(new DeleteByQueryRequest(), listener).finishHim(null, false, null);
waitForCompletion("waiting for finishHim to complete with success", listener);
assertNoFailures(listener);
assertNotNull(listener.getResponse());
assertFalse(listener.getResponse().isTimedOut());
listener = new TestActionListener();
newAsyncAction(new DeleteByQueryRequest(), listener).finishHim(null, true, null);
waitForCompletion("waiting for finishHim to complete with timed out = true", listener);
assertNoFailures(listener);
assertNotNull(listener.getResponse());
assertTrue(listener.getResponse().isTimedOut());
listener = new TestActionListener();
newAsyncAction(new DeleteByQueryRequest(), listener).finishHim(null, false, new Throwable("Fake error"));
waitForCompletion("waiting for finishHim to complete with error", listener);
assertFailure(listener, "Fake error");
assertNull(listener.getResponse());
}
private TransportDeleteByQueryAction.AsyncDeleteByQueryAction newAsyncAction(DeleteByQueryRequest request, TestActionListener listener) {
TransportDeleteByQueryAction action = getInstanceFromNode(TransportDeleteByQueryAction.class);
assertNotNull(action);
return action.new AsyncDeleteByQueryAction(request, listener);
}
private void waitForCompletion(String testName, final TestActionListener listener) {
logger.info(" --> waiting for delete-by-query [{}] to complete", testName);
try {
awaitBusy(new Predicate<Object>() {
@Override
public boolean apply(Object input) {
return listener.isTerminated();
}
});
} catch (InterruptedException e) {
fail("exception when waiting for delete-by-query [" + testName + "] to complete: " + e.getMessage());
logger.error("exception when waiting for delete-by-query [{}] to complete", e, testName);
}
}
private void assertFailure(TestActionListener listener, String expectedMessage) {
Throwable t = listener.getError();
assertNotNull(t);
assertTrue(Strings.hasText(expectedMessage));
assertTrue("error message should contain [" + expectedMessage + "] but got [" + t.getMessage() + "]", t.getMessage().contains(expectedMessage));
}
private void assertNoFailures(TestActionListener listener) {
assertNull(listener.getError());
assertTrue(CollectionUtils.isEmpty(listener.getResponse().getShardFailures()));
}
private void assertSearchContextsClosed() {
NodesStatsResponse nodesStats = client().admin().cluster().prepareNodesStats().setIndices(true).get();
for (NodeStats nodeStat : nodesStats.getNodes()){
assertThat(nodeStat.getIndices().getSearch().getOpenContexts(), equalTo(0L));
}
}
private void assertShardFailuresContains(ShardOperationFailedException[] shardFailures, String expectedFailure) {
assertNotNull(shardFailures);
for (ShardOperationFailedException failure : shardFailures) {
if (failure.reason().contains(expectedFailure)) {
return;
}
}
fail("failed to find shard failure [" + expectedFailure + "]");
}
private class TestActionListener implements ActionListener<DeleteByQueryResponse> {
private final CountDown count = new CountDown(1);
private DeleteByQueryResponse response;
private Throwable error;
@Override
public void onResponse(DeleteByQueryResponse response) {
try {
this.response = response;
} finally {
count.countDown();
}
}
@Override
public void onFailure(Throwable e) {
try {
this.error = e;
} finally {
count.countDown();
}
}
public boolean isTerminated() {
return count.isCountedDown();
}
public DeleteByQueryResponse getResponse() {
return response;
}
public Throwable getError() {
return error;
}
}
}