-
Notifications
You must be signed in to change notification settings - Fork 24.7k
/
FullClusterRestartIT.java
1887 lines (1724 loc) · 87.2 KB
/
FullClusterRestartIT.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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.upgrades;
import io.netty.handler.codec.http.HttpMethod;
import com.carrotsearch.randomizedtesting.annotations.Name;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.Build;
import org.elasticsearch.action.admin.cluster.settings.RestClusterGetSettingsResponse;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.MetadataIndexStateService;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.time.DateUtils;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.core.Booleans;
import org.elasticsearch.core.CheckedFunction;
import org.elasticsearch.core.UpdateForV9;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.IndexVersion;
import org.elasticsearch.index.IndexVersions;
import org.elasticsearch.index.mapper.DateFieldMapper;
import org.elasticsearch.rest.action.admin.indices.RestPutIndexTemplateAction;
import org.elasticsearch.test.NotEqualMessageBuilder;
import org.elasticsearch.test.XContentTestUtils;
import org.elasticsearch.test.cluster.ElasticsearchCluster;
import org.elasticsearch.test.cluster.FeatureFlag;
import org.elasticsearch.test.cluster.local.LocalClusterConfigProvider;
import org.elasticsearch.test.cluster.local.distribution.DistributionType;
import org.elasticsearch.test.rest.ESRestTestCase;
import org.elasticsearch.test.rest.ObjectPath;
import org.elasticsearch.test.rest.RestTestLegacyFeatures;
import org.elasticsearch.transport.Compression;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentParser;
import org.elasticsearch.xcontent.XContentType;
import org.elasticsearch.xcontent.json.JsonXContent;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.rules.RuleChain;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.TestRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static java.util.stream.Collectors.toList;
import static org.elasticsearch.cluster.metadata.IndexNameExpressionResolver.SYSTEM_INDEX_ENFORCEMENT_INDEX_VERSION;
import static org.elasticsearch.cluster.routing.UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING;
import static org.elasticsearch.cluster.routing.allocation.decider.MaxRetryAllocationDecider.SETTING_ALLOCATION_MAX_RETRY;
import static org.elasticsearch.test.MapMatcher.assertMap;
import static org.elasticsearch.test.MapMatcher.matchesMap;
import static org.elasticsearch.transport.RemoteClusterService.REMOTE_CLUSTER_COMPRESS;
import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* Tests to run before and after a full cluster restart. This is run twice,
* one with {@code tests.is_old_cluster} set to {@code true} against a cluster
* of an older version. The cluster is shutdown and a cluster of the new
* version is started with the same data directories and then this is rerun
* with {@code tests.is_old_cluster} set to {@code false}.
*/
public class FullClusterRestartIT extends ParameterizedFullClusterRestartTestCase {
private static TemporaryFolder repoDirectory = new TemporaryFolder();
protected static LocalClusterConfigProvider clusterConfig = c -> {};
private static ElasticsearchCluster cluster = ElasticsearchCluster.local()
.distribution(DistributionType.DEFAULT)
.version(getOldClusterTestVersion())
.nodes(2)
.setting("path.repo", () -> repoDirectory.getRoot().getPath())
.setting("xpack.security.enabled", "false")
// some tests rely on the translog not being flushed
.setting("indices.memory.shard_inactive_time", "60m")
.apply(() -> clusterConfig)
.feature(FeatureFlag.TIME_SERIES_MODE)
.feature(FeatureFlag.FAILURE_STORE_ENABLED)
.build();
@ClassRule
public static TestRule ruleChain = RuleChain.outerRule(repoDirectory).around(cluster);
private String index;
public FullClusterRestartIT(@Name("cluster") FullClusterRestartUpgradeStatus upgradeStatus) {
super(upgradeStatus);
}
@Override
protected ElasticsearchCluster getUpgradeCluster() {
return cluster;
}
@Before
public void setIndex() {
index = getRootTestName();
}
public void testSearch() throws Exception {
int count;
if (isRunningAgainstOldCluster()) {
final var createIndex = newXContentRequest(HttpMethod.PUT, "/" + index, (mappingsAndSettings, params) -> {
mappingsAndSettings.startObject("settings");
mappingsAndSettings.field("number_of_shards", 1);
mappingsAndSettings.field("number_of_replicas", 0);
mappingsAndSettings.endObject();
mappingsAndSettings.startObject("mappings");
mappingsAndSettings.startObject("properties");
{
mappingsAndSettings.startObject("string");
mappingsAndSettings.field("type", "text");
mappingsAndSettings.endObject();
}
{
mappingsAndSettings.startObject("dots_in_field_names");
mappingsAndSettings.field("type", "text");
mappingsAndSettings.endObject();
}
{
mappingsAndSettings.startObject("binary");
mappingsAndSettings.field("type", "binary");
mappingsAndSettings.field("store", "true");
mappingsAndSettings.endObject();
}
mappingsAndSettings.endObject();
mappingsAndSettings.endObject();
return mappingsAndSettings;
});
client().performRequest(createIndex);
count = randomIntBetween(2000, 3000);
byte[] randomByteArray = new byte[16];
random().nextBytes(randomByteArray);
indexRandomDocuments(
count,
true,
true,
randomBoolean(),
i -> JsonXContent.contentBuilder()
.startObject()
.field("string", randomAlphaOfLength(10))
.field("int", randomInt(100))
.field("float", randomFloat())
// be sure to create a "proper" boolean (True, False) for the first document so that automapping is correct
.field("bool", i > 0 && randomBoolean())
.field("field.with.dots", randomAlphaOfLength(10))
.field("binary", Base64.getEncoder().encodeToString(randomByteArray))
.endObject()
);
refreshAllIndices();
} else {
count = countOfIndexedRandomDocuments();
}
ensureGreenLongWait(index);
assertBasicSearchWorks(count);
assertAllSearchWorks(count);
assertBasicAggregationWorks();
assertRealtimeGetWorks();
assertStoredBinaryFields(count);
}
public void testNewReplicas() throws Exception {
if (isRunningAgainstOldCluster()) {
final var createIndex = newXContentRequest(HttpMethod.PUT, "/" + index, (mappingsAndSettings, params) -> {
mappingsAndSettings.startObject("settings");
mappingsAndSettings.field("number_of_shards", 1);
mappingsAndSettings.field("number_of_replicas", 0);
mappingsAndSettings.endObject();
mappingsAndSettings.startObject("mappings");
mappingsAndSettings.startObject("properties");
{
mappingsAndSettings.startObject("field");
mappingsAndSettings.field("type", "text");
mappingsAndSettings.endObject();
}
mappingsAndSettings.endObject();
mappingsAndSettings.endObject();
return mappingsAndSettings;
});
client().performRequest(createIndex);
int numDocs = randomIntBetween(2000, 3000);
indexRandomDocuments(
numDocs,
true,
false,
randomBoolean(),
i -> JsonXContent.contentBuilder().startObject().field("field", "value").endObject()
);
logger.info("Refreshing [{}]", index);
client().performRequest(new Request("POST", "/" + index + "/_refresh"));
} else {
// The test runs with two nodes so this should still go green.
final int numReplicas = 1;
final long startTime = System.currentTimeMillis();
logger.debug("--> creating [{}] replicas for index [{}]", numReplicas, index);
Request setNumberOfReplicas = newXContentRequest(
HttpMethod.PUT,
"/" + index + "/_settings",
(builder, params) -> builder.startObject("index").field("number_of_replicas", numReplicas).endObject()
);
client().performRequest(setNumberOfReplicas);
ensureGreenLongWait(index);
logger.debug("--> index [{}] is green, took [{}] ms", index, (System.currentTimeMillis() - startTime));
Map<String, Object> recoverRsp = entityAsMap(client().performRequest(new Request("GET", "/" + index + "/_recovery")));
logger.debug("--> recovery status:\n{}", recoverRsp);
Set<Integer> counts = new HashSet<>();
for (String node : dataNodes(index, client())) {
Request search = new Request("GET", "/" + index + "/_search");
search.addParameter("preference", "_only_nodes:" + node);
Map<String, Object> responseBody = entityAsMap(client().performRequest(search));
assertNoFailures(responseBody);
int hits = extractTotalHits(responseBody);
counts.add(hits);
}
assertEquals("All nodes should have a consistent number of documents", 1, counts.size());
}
}
public void testSearchTimeSeriesMode() throws Exception {
assumeTrue("indexing time series indices changed in 8.2.0", oldClusterHasFeature(RestTestLegacyFeatures.TSDB_NEW_INDEX_FORMAT));
int numDocs;
if (isRunningAgainstOldCluster()) {
numDocs = createTimeSeriesModeIndex(1);
} else {
numDocs = countOfIndexedRandomDocuments();
}
assertCountAll(numDocs);
Request request = newXContentRequest(HttpMethod.GET, "/" + index + "/_search", (body, params) -> {
body.field("size", 0);
body.startObject("aggs").startObject("check").startObject("scripted_metric");
body.field("init_script", "state.timeSeries = new HashSet()");
body.field("map_script", "state.timeSeries.add(doc['dim'].value)");
body.field("combine_script", "return state.timeSeries");
body.field("reduce_script", """
Set timeSeries = new TreeSet();
for (s in states) {
for (ts in s) {
boolean newTs = timeSeries.add(ts);
if (false == newTs) {
throw new IllegalArgumentException(ts + ' appeared in two shards');
}
}
}
return timeSeries;""");
body.endObject().endObject().endObject();
return body;
});
Map<String, Object> response = entityAsMap(client().performRequest(request));
assertMap(
response,
matchesMap().extraOk()
.entry("hits", matchesMap().extraOk().entry("total", Map.of("value", numDocs, "relation", "eq")))
.entry("aggregations", Map.of("check", Map.of("value", IntStream.range(0, 10).mapToObj(i -> "dim" + i).collect(toList()))))
);
}
public void testNewReplicasTimeSeriesMode() throws Exception {
assumeTrue("indexing time series indices changed in 8.2.0", oldClusterHasFeature(RestTestLegacyFeatures.TSDB_NEW_INDEX_FORMAT));
if (isRunningAgainstOldCluster()) {
createTimeSeriesModeIndex(0);
} else {
// The test runs with two nodes so this should still go green.
final int numReplicas = 1;
final long startTime = System.currentTimeMillis();
logger.debug("--> creating [{}] replicas for index [{}]", numReplicas, index);
Request setNumberOfReplicas = newXContentRequest(
HttpMethod.PUT,
"/" + index + "/_settings",
(builder, params) -> builder.startObject("index").field("number_of_replicas", numReplicas).endObject()
);
client().performRequest(setNumberOfReplicas);
ensureGreenLongWait(index);
logger.debug("--> index [{}] is green, took [{}] ms", index, (System.currentTimeMillis() - startTime));
Map<String, Object> recoverRsp = entityAsMap(client().performRequest(new Request("GET", "/" + index + "/_recovery")));
logger.debug("--> recovery status:\n{}", recoverRsp);
Set<Integer> counts = new HashSet<>();
for (String node : dataNodes(index, client())) {
Request search = new Request("GET", "/" + index + "/_search");
search.addParameter("preference", "_only_nodes:" + node);
Map<String, Object> responseBody = entityAsMap(client().performRequest(search));
assertNoFailures(responseBody);
int hits = extractTotalHits(responseBody);
counts.add(hits);
}
assertEquals("All nodes should have a consistent number of documents", 1, counts.size());
}
}
private int createTimeSeriesModeIndex(int replicas) throws IOException {
final var createIndex = newXContentRequest(HttpMethod.PUT, "/" + index, (mappingsAndSettings, params) -> {
mappingsAndSettings.startObject("settings");
mappingsAndSettings.field("number_of_shards", 1);
mappingsAndSettings.field("number_of_replicas", replicas);
mappingsAndSettings.field("mode", "time_series");
mappingsAndSettings.field("routing_path", "dim");
mappingsAndSettings.field("time_series.start_time", 1L);
mappingsAndSettings.field("time_series.end_time", DateUtils.MAX_MILLIS_BEFORE_9999 - 1);
mappingsAndSettings.endObject();
mappingsAndSettings.startObject("mappings");
mappingsAndSettings.startObject("properties");
{
mappingsAndSettings.startObject("@timestamp").field("type", "date").endObject();
mappingsAndSettings.startObject("dim").field("type", "keyword").field("time_series_dimension", true).endObject();
}
mappingsAndSettings.endObject();
mappingsAndSettings.endObject();
return mappingsAndSettings;
});
client().performRequest(createIndex);
int numDocs = randomIntBetween(2000, 3000);
long basetime = DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.parseMillis("2021-01-01T00:00:00Z");
indexRandomDocuments(
numDocs,
true,
true,
false,
i -> JsonXContent.contentBuilder()
.startObject()
.field("@timestamp", basetime + TimeUnit.MINUTES.toMillis(i))
.field("dim", "dim" + (i % 10))
.endObject()
);
logger.info("Refreshing [{}]", index);
client().performRequest(new Request("POST", "/" + index + "/_refresh"));
return numDocs;
}
public void testClusterState() throws Exception {
if (isRunningAgainstOldCluster()) {
final Request createTemplate = newXContentRequest(HttpMethod.PUT, "/_template/template_1", (mappingsAndSettings, params) -> {
mappingsAndSettings.field("index_patterns", index);
mappingsAndSettings.field("order", "1000");
mappingsAndSettings.startObject("settings");
mappingsAndSettings.field("number_of_shards", 1);
mappingsAndSettings.field("number_of_replicas", 0);
mappingsAndSettings.endObject();
return mappingsAndSettings;
});
createTemplate.setOptions(expectWarnings(RestPutIndexTemplateAction.DEPRECATION_WARNING));
client().performRequest(createTemplate);
client().performRequest(new Request("PUT", "/" + index));
}
// verifying if we can still read some properties from cluster state api:
Map<String, Object> clusterState = entityAsMap(client().performRequest(new Request("GET", "/_cluster/state")));
// Check some global properties:
String numberOfShards = (String) XContentMapValues.extractValue(
"metadata.templates.template_1.settings.index.number_of_shards",
clusterState
);
assertEquals("1", numberOfShards);
String numberOfReplicas = (String) XContentMapValues.extractValue(
"metadata.templates.template_1.settings.index.number_of_replicas",
clusterState
);
assertEquals("0", numberOfReplicas);
// Check some index properties:
numberOfShards = (String) XContentMapValues.extractValue(
"metadata.indices." + index + ".settings.index.number_of_shards",
clusterState
);
assertEquals("1", numberOfShards);
numberOfReplicas = (String) XContentMapValues.extractValue(
"metadata.indices." + index + ".settings.index.number_of_replicas",
clusterState
);
assertEquals("0", numberOfReplicas);
IndexVersion version = IndexVersion.fromId(
Integer.valueOf(
(String) XContentMapValues.extractValue("metadata.indices." + index + ".settings.index.version.created", clusterState)
)
);
assertEquals(getOldClusterIndexVersion(), version);
}
public void testShrink() throws IOException {
String shrunkenIndex = index + "_shrunk";
int numDocs;
if (isRunningAgainstOldCluster()) {
final var createIndex = newXContentRequest(HttpMethod.PUT, "/" + index, (mappingsAndSettings, params) -> {
mappingsAndSettings.startObject("mappings");
{
mappingsAndSettings.startObject("properties");
{
mappingsAndSettings.startObject("field");
{
mappingsAndSettings.field("type", "text");
}
mappingsAndSettings.endObject();
}
mappingsAndSettings.endObject();
}
mappingsAndSettings.endObject();
mappingsAndSettings.startObject("settings");
{
mappingsAndSettings.field("index.number_of_shards", 5);
}
mappingsAndSettings.endObject();
return mappingsAndSettings;
});
client().performRequest(createIndex);
numDocs = randomIntBetween(512, 1024);
indexRandomDocuments(
numDocs,
true,
true,
randomBoolean(),
i -> JsonXContent.contentBuilder().startObject().field("field", "value").endObject()
);
ensureGreen(index); // wait for source index to be available on both nodes before starting shrink
client().performRequest(
newXContentRequest(
HttpMethod.PUT,
"/" + index + "/_settings",
(builder, params) -> builder.startObject("settings").field("index.blocks.write", true).endObject()
)
);
client().performRequest(
newXContentRequest(
HttpMethod.PUT,
"/" + index + "/_shrink/" + shrunkenIndex,
(builder, params) -> builder.startObject("settings").field("index.number_of_shards", 1).endObject()
)
);
refreshAllIndices();
} else {
numDocs = countOfIndexedRandomDocuments();
}
Map<?, ?> response = entityAsMap(client().performRequest(new Request("GET", "/" + index + "/_search")));
assertNoFailures(response);
int totalShards = (int) XContentMapValues.extractValue("_shards.total", response);
assertThat(totalShards, greaterThan(1));
int successfulShards = (int) XContentMapValues.extractValue("_shards.successful", response);
assertEquals(totalShards, successfulShards);
int totalHits = extractTotalHits(response);
assertEquals(numDocs, totalHits);
response = entityAsMap(client().performRequest(new Request("GET", "/" + shrunkenIndex + "/_search")));
assertNoFailures(response);
totalShards = (int) XContentMapValues.extractValue("_shards.total", response);
assertEquals(1, totalShards);
successfulShards = (int) XContentMapValues.extractValue("_shards.successful", response);
assertEquals(1, successfulShards);
totalHits = extractTotalHits(response);
assertEquals(numDocs, totalHits);
}
public void testShrinkAfterUpgrade() throws IOException {
String shrunkenIndex = index + "_shrunk";
int numDocs;
if (isRunningAgainstOldCluster()) {
final var createIndex = newXContentRequest(HttpMethod.PUT, "/" + index, (mappingsAndSettings, params) -> {
mappingsAndSettings.startObject("mappings");
{
mappingsAndSettings.startObject("properties");
{
mappingsAndSettings.startObject("field");
{
mappingsAndSettings.field("type", "text");
}
mappingsAndSettings.endObject();
}
mappingsAndSettings.endObject();
}
mappingsAndSettings.endObject();
// the default number of shards is now one so we have to set the number of shards to be more than one explicitly
mappingsAndSettings.startObject("settings");
mappingsAndSettings.field("index.number_of_shards", 5);
mappingsAndSettings.endObject();
return mappingsAndSettings;
});
client().performRequest(createIndex);
numDocs = randomIntBetween(512, 1024);
indexRandomDocuments(
numDocs,
true,
true,
randomBoolean(),
i -> JsonXContent.contentBuilder().startObject().field("field", "value").endObject()
);
} else {
ensureGreen(index); // wait for source index to be available on both nodes before starting shrink
client().performRequest(
newXContentRequest(
HttpMethod.PUT,
"/" + index + "/_settings",
(builder, params) -> builder.startObject("settings").field("index.blocks.write", true).endObject()
)
);
client().performRequest(
newXContentRequest(
HttpMethod.PUT,
"/" + index + "/_shrink/" + shrunkenIndex,
(builder, params) -> builder.startObject("settings").field("index.number_of_shards", 1).endObject()
)
);
numDocs = countOfIndexedRandomDocuments();
}
refreshAllIndices();
Map<?, ?> response = entityAsMap(client().performRequest(new Request("GET", "/" + index + "/_search")));
assertNoFailures(response);
int totalShards = (int) XContentMapValues.extractValue("_shards.total", response);
assertThat(totalShards, greaterThan(1));
int successfulShards = (int) XContentMapValues.extractValue("_shards.successful", response);
assertEquals(totalShards, successfulShards);
int totalHits = extractTotalHits(response);
assertEquals(numDocs, totalHits);
if (isRunningAgainstOldCluster() == false) {
response = entityAsMap(client().performRequest(new Request("GET", "/" + shrunkenIndex + "/_search")));
assertNoFailures(response);
totalShards = (int) XContentMapValues.extractValue("_shards.total", response);
assertEquals(1, totalShards);
successfulShards = (int) XContentMapValues.extractValue("_shards.successful", response);
assertEquals(1, successfulShards);
totalHits = extractTotalHits(response);
assertEquals(numDocs, totalHits);
}
}
/**
* Test upgrading after a rollover. Specifically:
* <ol>
* <li>Create an index with a write alias
* <li>Write some documents to the write alias
* <li>Roll over the index
* <li>Make sure the document count is correct
* <li>Upgrade
* <li>Write some more documents to the write alias
* <li>Make sure the document count is correct
* </ol>
*/
public void testRollover() throws Exception {
if (isRunningAgainstOldCluster()) {
client().performRequest(
newXContentRequest(
HttpMethod.PUT,
"/" + index + "-000001",
(builder, params) -> builder.startObject("aliases").startObject(index + "_write").endObject().endObject()
)
);
}
int bulkCount = 10;
String bulk = """
{"index":{}}
{"test":"test"}
""".repeat(bulkCount);
Request bulkRequest = new Request("POST", "/" + index + "_write/_bulk");
bulkRequest.setJsonEntity(bulk);
bulkRequest.addParameter("refresh", "");
assertThat(EntityUtils.toString(client().performRequest(bulkRequest).getEntity()), containsString("\"errors\":false"));
if (isRunningAgainstOldCluster()) {
client().performRequest(
newXContentRequest(
HttpMethod.POST,
"/" + index + "_write/_rollover",
(builder, params) -> builder.startObject("conditions").field("max_docs", 5).endObject()
)
);
// assertBusy to work around https://github.com/elastic/elasticsearch/issues/104371
assertBusy(
() -> assertThat(
EntityUtils.toString(client().performRequest(new Request("GET", "/_cat/indices?v&error_trace")).getEntity()),
containsString("testrollover-000002")
)
);
}
Request countRequest = new Request("POST", "/" + index + "-*/_search");
countRequest.addParameter("size", "0");
Map<String, Object> count = entityAsMap(client().performRequest(countRequest));
assertNoFailures(count);
int expectedCount = bulkCount + (isRunningAgainstOldCluster() ? 0 : bulkCount);
assertEquals(expectedCount, extractTotalHits(count));
}
void assertCountAll(int count) throws IOException {
Map<String, Object> response = entityAsMap(client().performRequest(new Request("GET", "/" + index + "/_search")));
assertNoFailures(response);
int numDocs = extractTotalHits(response);
logger.info("Found {} in old index", numDocs);
assertEquals(count, numDocs);
}
void assertBasicSearchWorks(int count) throws IOException {
logger.info("--> testing basic search");
{
assertCountAll(count);
}
logger.info("--> testing basic search with sort");
{
Map<String, Object> response = entityAsMap(
client().performRequest(
newXContentRequest(
HttpMethod.GET,
"/" + index + "/_search",
(builder, params) -> builder.startArray("sort").startObject().field("int", "asc").endObject().endArray()
)
)
);
assertNoFailures(response);
assertTotalHits(count, response);
}
logger.info("--> testing exists filter");
{
Map<String, Object> response = entityAsMap(
client().performRequest(
newXContentRequest(
HttpMethod.GET,
"/" + index + "/_search",
(builder, params) -> builder.startObject("query")
.startObject("exists")
.field("field", "string")
.endObject()
.endObject()
)
)
);
assertNoFailures(response);
assertTotalHits(count, response);
}
logger.info("--> testing field with dots in the name");
{
Map<String, Object> response = entityAsMap(
client().performRequest(
newXContentRequest(
HttpMethod.GET,
"/" + index + "/_search",
(builder, params) -> builder.startObject("query")
.startObject("exists")
.field("field", "field.with.dots")
.endObject()
.endObject()
)
)
);
assertNoFailures(response);
assertTotalHits(count, response);
}
}
void assertAllSearchWorks(int count) throws IOException {
logger.info("--> testing _all search");
Map<String, Object> response = entityAsMap(client().performRequest(new Request("GET", "/" + index + "/_search")));
assertNoFailures(response);
assertTotalHits(count, response);
Map<?, ?> bestHit = (Map<?, ?>) ((List<?>) (XContentMapValues.extractValue("hits.hits", response))).get(0);
// Make sure there are payloads and they are taken into account for the score
// the 'string' field has a boost of 4 in the mappings so it should get a payload boost
String stringValue = (String) XContentMapValues.extractValue("_source.string", bestHit);
assertNotNull(stringValue);
String id = (String) bestHit.get("_id");
String explanation = toStr(
client().performRequest(
newXContentRequest(
HttpMethod.GET,
"/" + index + "/_explain/" + id,
(builder, params) -> builder.startObject("query").startObject("match_all").endObject().endObject()
)
)
);
assertFalse("Could not find payload boost in explanation\n" + explanation, explanation.contains("payloadBoost"));
// Make sure the query can run on the whole index
Request searchRequest = newXContentRequest(
HttpMethod.GET,
"/" + index + "/_search",
(builder, params) -> builder.startObject("query").startObject("match_all").endObject().endObject()
);
searchRequest.addParameter("explain", "true");
Map<?, ?> matchAllResponse = entityAsMap(client().performRequest(searchRequest));
assertNoFailures(matchAllResponse);
assertTotalHits(count, matchAllResponse);
}
void assertBasicAggregationWorks() throws IOException {
// histogram on a long
Map<?, ?> longHistogram = entityAsMap(
client().performRequest(
newXContentRequest(
HttpMethod.GET,
"/" + index + "/_search",
(builder, params) -> builder.startObject("aggs")
.startObject("histo")
.startObject("histogram")
.field("field", "int")
.field("interval", 10)
.endObject()
.endObject()
.endObject()
)
)
);
assertNoFailures(longHistogram);
List<?> histoBuckets = (List<?>) XContentMapValues.extractValue("aggregations.histo.buckets", longHistogram);
int histoCount = 0;
for (Object entry : histoBuckets) {
Map<?, ?> bucket = (Map<?, ?>) entry;
histoCount += (Integer) bucket.get("doc_count");
}
assertTotalHits(histoCount, longHistogram);
// terms on a boolean
Map<?, ?> boolTerms = entityAsMap(
client().performRequest(
newXContentRequest(
HttpMethod.GET,
"/" + index + "/_search",
(builder, params) -> builder.startObject("aggs")
.startObject("bool_terms")
.startObject("terms")
.field("field", "bool")
.endObject()
.endObject()
.endObject()
)
)
);
List<?> termsBuckets = (List<?>) XContentMapValues.extractValue("aggregations.bool_terms.buckets", boolTerms);
int termsCount = 0;
for (Object entry : termsBuckets) {
Map<?, ?> bucket = (Map<?, ?>) entry;
termsCount += (Integer) bucket.get("doc_count");
}
assertTotalHits(termsCount, boolTerms);
}
void assertRealtimeGetWorks() throws IOException {
client().performRequest(
newXContentRequest(
HttpMethod.PUT,
"/" + index + "/_settings",
(builder, params) -> builder.startObject("index").field("refresh_interval", -1).endObject()
)
);
Map<?, ?> searchResponse = entityAsMap(
client().performRequest(
newXContentRequest(
HttpMethod.GET,
"/" + index + "/_search",
(builder, params) -> builder.startObject("query").startObject("match_all").endObject().endObject()
)
)
);
Map<?, ?> hit = (Map<?, ?>) ((List<?>) (XContentMapValues.extractValue("hits.hits", searchResponse))).get(0);
String docId = (String) hit.get("_id");
client().performRequest(
newXContentRequest(
HttpMethod.POST,
"/" + index + "/_update/" + docId,
(builder, params) -> builder.startObject("doc").field("foo", "bar").endObject()
)
);
Request getRequest = new Request("GET", "/" + index + "/_doc/" + docId);
Map<String, Object> getRsp = entityAsMap(client().performRequest(getRequest));
Map<?, ?> source = (Map<?, ?>) getRsp.get("_source");
assertTrue("doc does not contain 'foo' key: " + source, source.containsKey("foo"));
client().performRequest(
newXContentRequest(
HttpMethod.PUT,
"/" + index + "/_settings",
(builder, params) -> builder.startObject("index").field("refresh_interval", "1s").endObject()
)
);
}
void assertStoredBinaryFields(int count) throws Exception {
final var restResponse = client().performRequest(
newXContentRequest(
HttpMethod.GET,
"/" + index + "/_search",
(builder, params) -> builder.startObject("query")
.startObject("match_all")
.endObject()
.endObject()
.field("size", 100)
.field("stored_fields", "binary")
)
);
Map<String, Object> rsp = entityAsMap(restResponse);
assertTotalHits(count, rsp);
List<?> hits = (List<?>) XContentMapValues.extractValue("hits.hits", rsp);
assertEquals(100, hits.size());
for (Object hit : hits) {
Map<?, ?> hitRsp = (Map<?, ?>) hit;
List<?> values = (List<?>) XContentMapValues.extractValue("fields.binary", hitRsp);
assertEquals(1, values.size());
byte[] binaryValue = switch (XContentType.fromMediaType(restResponse.getEntity().getContentType().getValue())) {
case JSON, VND_JSON -> Base64.getDecoder().decode((String) values.get(0));
case SMILE, CBOR, YAML, VND_SMILE, VND_CBOR, VND_YAML -> (byte[]) values.get(0);
};
assertEquals("Unexpected binary length [" + Base64.getEncoder().encodeToString(binaryValue) + "]", 16, binaryValue.length);
}
}
static String toStr(Response response) throws IOException {
return EntityUtils.toString(response.getEntity());
}
static void assertNoFailures(Map<?, ?> response) {
int failed = (int) XContentMapValues.extractValue("_shards.failed", response);
assertEquals(0, failed);
}
void assertTotalHits(int expectedTotalHits, Map<?, ?> response) {
int actualTotalHits = extractTotalHits(response);
assertEquals(response.toString(), expectedTotalHits, actualTotalHits);
}
static int extractTotalHits(Map<?, ?> response) {
return (Integer) XContentMapValues.extractValue("hits.total.value", response);
}
/**
* Tests that a single document survives. Super basic smoke test.
*/
public void testSingleDoc() throws IOException {
String docLocation = "/" + index + "/_doc/1";
String doc = "{\"test\": \"test\"}";
if (isRunningAgainstOldCluster()) {
Request createDoc = new Request("PUT", docLocation);
createDoc.setJsonEntity(doc);
client().performRequest(createDoc);
}
Request request = new Request("GET", docLocation);
assertThat(toStr(client().performRequest(request)), containsString(doc));
}
/**
* Tests that a single empty shard index is correctly recovered. Empty shards are often an edge case.
*/
public void testEmptyShard() throws IOException {
final String indexName = "test_empty_shard";
if (isRunningAgainstOldCluster()) {
Settings.Builder settings = Settings.builder()
.put(IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 1)
.put(IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 1)
// if the node with the replica is the first to be restarted, while a replica is still recovering
// then delayed allocation will kick in. When the node comes back, the master will search for a copy
// but the recovering copy will be seen as invalid and the cluster health won't return to GREEN
// before timing out
.put(INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING.getKey(), "100ms")
.put(SETTING_ALLOCATION_MAX_RETRY.getKey(), "0"); // fail faster
createIndex(indexName, settings.build());
}
ensureGreen(indexName);
}
/**
* Tests recovery of an index.
*/
public void testRecovery() throws Exception {
int count;
if (isRunningAgainstOldCluster()) {
count = between(200, 300);
Settings.Builder settings = Settings.builder();
if (minimumIndexVersion().before(IndexVersions.V_8_0_0) && randomBoolean()) {
settings.put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), randomBoolean());
}
final String mappings = randomBoolean() ? "\"_source\": { \"enabled\": false}" : null;
createIndex(index, settings.build(), mappings);
indexRandomDocuments(count, true, true, true, i -> jsonBuilder().startObject().field("field", "value").endObject());
// make sure all recoveries are done
ensureGreen(index);
// Force flush so we're sure that all translog are committed
Request flushRequest = new Request("POST", "/" + index + "/_flush");
flushRequest.addParameter("force", "true");
flushRequest.addParameter("wait_if_ongoing", "true");
assertOK(client().performRequest(flushRequest));
} else {
count = countOfIndexedRandomDocuments();
}
// Count the documents in the index to make sure we have as many as we put there
Request countRequest = new Request("GET", "/" + index + "/_search");
countRequest.addParameter("size", "0");
refreshAllIndices();
Map<String, Object> countResponse = entityAsMap(client().performRequest(countRequest));
assertTotalHits(count, countResponse);
if (false == isRunningAgainstOldCluster()) {
boolean foundPrimary = false;
Request recoveryRequest = new Request("GET", "/_cat/recovery/" + index);
recoveryRequest.addParameter("h", "index,shard,type,stage,translog_ops_recovered");
recoveryRequest.addParameter("s", "index,shard,type");
String recoveryResponse = toStr(client().performRequest(recoveryRequest));
foundPrimary = recoveryResponse.split("\n").length > 0;
assertTrue("expected to find a primary but didn't\n" + recoveryResponse, foundPrimary);
}
}
/**
* Tests snapshot/restore by creating a snapshot and restoring it. It takes
* a snapshot on the old cluster and restores it on the old cluster as a
* sanity check and on the new cluster as an upgrade test. It also takes a
* snapshot on the new cluster and restores that on the new cluster as a
* test that the repository is ok with containing snapshot from both the
* old and new versions. All of the snapshots include an index, a template,
* and some routing configuration.
*/
public void testSnapshotRestore() throws IOException {
int count;
if (isRunningAgainstOldCluster()) {
// Create the index
count = between(200, 300);
Settings.Builder settings = Settings.builder();
if (minimumIndexVersion().before(IndexVersions.V_8_0_0) && randomBoolean()) {
settings.put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), randomBoolean());
}
createIndex(index, settings.build());