forked from elastic/elasticsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TimeSeriesLifecycleActionsIT.java
1357 lines (1188 loc) · 69.1 KB
/
TimeSeriesLifecycleActionsIT.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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.ilm;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.cluster.metadata.DataStream;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.common.CheckedRunnable;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.engine.EngineConfig;
import org.elasticsearch.snapshots.SnapshotState;
import org.elasticsearch.test.rest.ESRestTestCase;
import org.elasticsearch.xpack.core.ilm.AllocateAction;
import org.elasticsearch.xpack.core.ilm.DeleteAction;
import org.elasticsearch.xpack.core.ilm.ForceMergeAction;
import org.elasticsearch.xpack.core.ilm.FreezeAction;
import org.elasticsearch.xpack.core.ilm.LifecycleAction;
import org.elasticsearch.xpack.core.ilm.LifecyclePolicy;
import org.elasticsearch.xpack.core.ilm.LifecycleSettings;
import org.elasticsearch.xpack.core.ilm.Phase;
import org.elasticsearch.xpack.core.ilm.PhaseCompleteStep;
import org.elasticsearch.xpack.core.ilm.ReadOnlyAction;
import org.elasticsearch.xpack.core.ilm.RolloverAction;
import org.elasticsearch.xpack.core.ilm.SearchableSnapshotAction;
import org.elasticsearch.xpack.core.ilm.SetPriorityAction;
import org.elasticsearch.xpack.core.ilm.ShrinkAction;
import org.elasticsearch.xpack.core.ilm.Step;
import org.elasticsearch.xpack.core.ilm.WaitForActiveShardsStep;
import org.elasticsearch.xpack.core.ilm.WaitForRolloverReadyStep;
import org.elasticsearch.xpack.core.ilm.WaitForSnapshotAction;
import org.hamcrest.Matchers;
import org.junit.Before;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static java.util.Collections.singletonMap;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.xpack.TimeSeriesRestDriver.createFullPolicy;
import static org.elasticsearch.xpack.TimeSeriesRestDriver.createIndexWithSettings;
import static org.elasticsearch.xpack.TimeSeriesRestDriver.createNewSingletonPolicy;
import static org.elasticsearch.xpack.TimeSeriesRestDriver.createSnapshotRepo;
import static org.elasticsearch.xpack.TimeSeriesRestDriver.explainIndex;
import static org.elasticsearch.xpack.TimeSeriesRestDriver.getNumberOfSegments;
import static org.elasticsearch.xpack.TimeSeriesRestDriver.getOnlyIndexSettings;
import static org.elasticsearch.xpack.TimeSeriesRestDriver.getSnapshotState;
import static org.elasticsearch.xpack.TimeSeriesRestDriver.getStepKeyForIndex;
import static org.elasticsearch.xpack.TimeSeriesRestDriver.index;
import static org.elasticsearch.xpack.TimeSeriesRestDriver.indexDocument;
import static org.elasticsearch.xpack.TimeSeriesRestDriver.rolloverMaxOneDocCondition;
import static org.elasticsearch.xpack.TimeSeriesRestDriver.updatePolicy;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
public class TimeSeriesLifecycleActionsIT extends ESRestTestCase {
private static final Logger logger = LogManager.getLogger(TimeSeriesLifecycleActionsIT.class);
private static final String FAILED_STEP_RETRY_COUNT_FIELD = "failed_step_retry_count";
private String index;
private String policy;
private String alias;
@Before
public void refreshIndex() {
index = "index-" + randomAlphaOfLength(10).toLowerCase(Locale.ROOT);
policy = "policy-" + randomAlphaOfLength(5);
alias = "alias-" + randomAlphaOfLength(5);
}
public void testFullPolicy() throws Exception {
String originalIndex = index + "-000001";
String shrunkenOriginalIndex = ShrinkAction.SHRUNKEN_INDEX_PREFIX + originalIndex;
String secondIndex = index + "-000002";
createIndexWithSettings(client(), originalIndex, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 2)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
.put("index.routing.allocation.include._name", "javaRestTest-0")
.put(RolloverAction.LIFECYCLE_ROLLOVER_ALIAS, alias));
// create policy
createFullPolicy(client(), policy, TimeValue.ZERO);
// update policy on index
updatePolicy(client(), originalIndex, policy);
// index document {"foo": "bar"} to trigger rollover
index(client(), originalIndex, "_id", "foo", "bar");
/*
* These asserts are in the order that they should be satisfied in, in
* order to maximize the time for all operations to complete.
* An "out of order" assert here may result in this test occasionally
* timing out and failing inappropriately.
*/
// asserts that rollover was called
assertBusy(() -> assertTrue(indexExists(secondIndex)));
// asserts that shrink deleted the original index
assertBusy(() -> assertFalse(indexExists(originalIndex)), 60, TimeUnit.SECONDS);
// asserts that the delete phase completed for the managed shrunken index
assertBusy(() -> assertFalse(indexExists(shrunkenOriginalIndex)));
}
public void testRetryFailedDeleteAction() throws Exception {
createNewSingletonPolicy(client(), policy, "delete", new DeleteAction());
createIndexWithSettings(client(), index, alias, Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
.put(IndexMetadata.SETTING_READ_ONLY, true)
.put("index.lifecycle.name", policy));
assertBusy(() -> assertThat((Integer) explainIndex(client(), index).get(FAILED_STEP_RETRY_COUNT_FIELD), greaterThanOrEqualTo(1)),
30, TimeUnit.SECONDS);
assertTrue(indexExists(index));
Request request = new Request("PUT", index + "/_settings");
request.setJsonEntity("{\"index.blocks.read_only\":false}");
assertOK(client().performRequest(request));
assertBusy(() -> assertFalse(indexExists(index)));
}
public void testRetryFreezeDeleteAction() throws Exception {
createNewSingletonPolicy(client(), policy, "cold", new FreezeAction());
createIndexWithSettings(client(), index, alias, Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
.put(IndexMetadata.SETTING_READ_ONLY, true)
.put("index.lifecycle.name", policy));
assertBusy(() -> assertThat((Integer) explainIndex(client(), index).get(FAILED_STEP_RETRY_COUNT_FIELD), greaterThanOrEqualTo(1)),
30, TimeUnit.SECONDS);
assertFalse(getOnlyIndexSettings(client(), index).containsKey("index.frozen"));
Request request = new Request("PUT", index + "/_settings");
request.setJsonEntity("{\"index.blocks.read_only\":false}");
assertOK(client().performRequest(request));
assertBusy(() -> assertThat(getOnlyIndexSettings(client(), index).get("index.frozen"), equalTo("true")));
}
public void testRolloverAction() throws Exception {
String originalIndex = index + "-000001";
String secondIndex = index + "-000002";
createIndexWithSettings(client(), originalIndex, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
.put(RolloverAction.LIFECYCLE_ROLLOVER_ALIAS, alias));
// create policy
createNewSingletonPolicy(client(), policy, "hot", new RolloverAction(null, null, 1L));
// update policy on index
updatePolicy(client(), originalIndex, policy);
// index document {"foo": "bar"} to trigger rollover
index(client(), originalIndex, "_id", "foo", "bar");
assertBusy(() -> assertTrue(indexExists(secondIndex)));
assertBusy(() -> assertTrue(indexExists(originalIndex)));
assertBusy(() -> assertEquals("true",
getOnlyIndexSettings(client(), originalIndex).get(LifecycleSettings.LIFECYCLE_INDEXING_COMPLETE)));
}
public void testRolloverActionWithIndexingComplete() throws Exception {
String originalIndex = index + "-000001";
String secondIndex = index + "-000002";
createIndexWithSettings(client(), originalIndex, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
.put(RolloverAction.LIFECYCLE_ROLLOVER_ALIAS, alias));
Request updateSettingsRequest = new Request("PUT", "/" + originalIndex + "/_settings");
updateSettingsRequest.setJsonEntity("{\n" +
" \"settings\": {\n" +
" \"" + LifecycleSettings.LIFECYCLE_INDEXING_COMPLETE + "\": true\n" +
" }\n" +
"}");
client().performRequest(updateSettingsRequest);
Request updateAliasRequest = new Request("POST", "/_aliases");
updateAliasRequest.setJsonEntity("{\n" +
" \"actions\": [\n" +
" {\n" +
" \"add\": {\n" +
" \"index\": \"" + originalIndex + "\",\n" +
" \"alias\": \"" + alias + "\",\n" +
" \"is_write_index\": false\n" +
" }\n" +
" }\n" +
" ]\n" +
"}");
client().performRequest(updateAliasRequest);
// create policy
createNewSingletonPolicy(client(), policy, "hot", new RolloverAction(null, null, 1L));
// update policy on index
updatePolicy(client(), originalIndex, policy);
// index document {"foo": "bar"} to trigger rollover
index(client(), originalIndex, "_id", "foo", "bar");
assertBusy(() -> assertThat(getStepKeyForIndex(client(), originalIndex), equalTo(PhaseCompleteStep.finalStep("hot").getKey())));
assertBusy(() -> assertTrue(indexExists(originalIndex)));
assertBusy(() -> assertFalse(indexExists(secondIndex)));
assertBusy(() -> assertEquals("true",
getOnlyIndexSettings(client(), originalIndex).get(LifecycleSettings.LIFECYCLE_INDEXING_COMPLETE)));
}
public void testAllocateOnlyAllocation() throws Exception {
createIndexWithSettings(client(), index, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 2)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0));
String allocateNodeName = "javaRestTest-" + randomFrom(0, 1);
AllocateAction allocateAction = new AllocateAction(null, null, null, singletonMap("_name", allocateNodeName));
String endPhase = randomFrom("warm", "cold");
createNewSingletonPolicy(client(), policy, endPhase, allocateAction);
updatePolicy(client(), index, policy);
assertBusy(() -> {
assertThat(getStepKeyForIndex(client(), index), equalTo(PhaseCompleteStep.finalStep(endPhase).getKey()));
});
ensureGreen(index);
}
public void testAllocateActionOnlyReplicas() throws Exception {
int numShards = randomFrom(1, 5);
int numReplicas = randomFrom(0, 1);
int finalNumReplicas = (numReplicas + 1) % 2;
createIndexWithSettings(client(), index, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, numShards)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, numReplicas));
AllocateAction allocateAction = new AllocateAction(finalNumReplicas, null, null, null);
String endPhase = randomFrom("warm", "cold");
createNewSingletonPolicy(client(), policy, endPhase, allocateAction);
updatePolicy(client(), index, policy);
assertBusy(() -> {
Map<String, Object> settings = getOnlyIndexSettings(client(), index);
assertThat(getStepKeyForIndex(client(), index), equalTo(PhaseCompleteStep.finalStep(endPhase).getKey()));
assertThat(settings.get(IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey()), equalTo(String.valueOf(finalNumReplicas)));
});
}
public void testWaitForSnapshot() throws Exception {
createIndexWithSettings(client(), index, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0));
String slmPolicy = randomAlphaOfLengthBetween(4, 10);
createNewSingletonPolicy(client(), policy, "delete", new WaitForSnapshotAction(slmPolicy));
updatePolicy(client(), index, policy);
assertBusy( () -> {
Map<String, Object> indexILMState = explainIndex(client(), index);
assertThat(indexILMState.get("action"), is("wait_for_snapshot"));
assertThat(indexILMState.get("failed_step"), is("wait-for-snapshot"));
}, slmPolicy);
String snapshotRepo = randomAlphaOfLengthBetween(4, 10);
createSnapshotRepo(client(), snapshotRepo, randomBoolean());
createSlmPolicy(slmPolicy, snapshotRepo);
assertBusy( () -> {
Map<String, Object> indexILMState = explainIndex(client(), index);
//wait for step to notice that the slm policy is created and to get out of error
assertThat(indexILMState.get("failed_step"), nullValue());
assertThat(indexILMState.get("action"), is("wait_for_snapshot"));
assertThat(indexILMState.get("step"), is("wait-for-snapshot"));
}, slmPolicy);
Request request = new Request("PUT", "/_slm/policy/" + slmPolicy + "/_execute");
assertOK(client().performRequest(request));
assertBusy(() -> assertThat(getStepKeyForIndex(client(), index).getAction(), equalTo("complete")), slmPolicy);
}
public void testWaitForSnapshotSlmExecutedBefore() throws Exception {
createIndexWithSettings(client(), index, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0));
String slmPolicy = randomAlphaOfLengthBetween(4, 10);
createNewSingletonPolicy(client(), policy, "delete", new WaitForSnapshotAction(slmPolicy));
String snapshotRepo = randomAlphaOfLengthBetween(4, 10);
createSnapshotRepo(client(), snapshotRepo, randomBoolean());
createSlmPolicy(slmPolicy, snapshotRepo);
Request request = new Request("PUT", "/_slm/policy/" + slmPolicy + "/_execute");
assertOK(client().performRequest(request));
//wait for slm to finish execution
assertBusy(() -> {
Response response = client().performRequest(new Request("GET", "/_slm/policy/" + slmPolicy));
try (InputStream is = response.getEntity().getContent()) {
Map<String, Object> responseMap = XContentHelper.convertToMap(XContentType.JSON.xContent(), is, true);
assertEquals(1, ((Map<?, ?>) ((Map<?, ?>) responseMap.get(slmPolicy)).get("stats")).get("snapshots_taken"));
}
}, slmPolicy);
updatePolicy(client(), index, policy);
assertBusy( () -> {
Map<String, Object> indexILMState = explainIndex(client(), index);
assertThat(indexILMState.get("failed_step"), nullValue());
assertThat(indexILMState.get("action"), is("wait_for_snapshot"));
assertThat(indexILMState.get("step"), is("wait-for-snapshot"));
}, slmPolicy);
request = new Request("PUT", "/_slm/policy/" + slmPolicy + "/_execute");
assertOK(client().performRequest(request));
//wait for slm to finish execution
assertBusy(() -> {
Response response = client().performRequest(new Request("GET", "/_slm/policy/" + slmPolicy));
try (InputStream is = response.getEntity().getContent()) {
Map<String, Object> responseMap = XContentHelper.convertToMap(XContentType.JSON.xContent(), is, true);
assertEquals(2, ((Map<?, ?>) ((Map<?, ?>) responseMap.get(slmPolicy)).get("stats")).get("snapshots_taken"));
}
}, slmPolicy);
assertBusy(() -> assertThat(getStepKeyForIndex(client(), index).getAction(), equalTo("complete")), slmPolicy);
}
public void testDelete() throws Exception {
createIndexWithSettings(client(), index, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0));
createNewSingletonPolicy(client(), policy, "delete", new DeleteAction());
updatePolicy(client(), index, policy);
assertBusy(() -> assertFalse(indexExists(index)));
}
public void testDeleteOnlyShouldNotMakeIndexReadonly() throws Exception {
createIndexWithSettings(client(), index, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0));
createNewSingletonPolicy(client(), policy, "delete", new DeleteAction(), TimeValue.timeValueHours(1));
updatePolicy(client(), index, policy);
assertBusy(() -> {
assertThat(getStepKeyForIndex(client(), index).getAction(), equalTo("complete"));
Map<String, Object> settings = getOnlyIndexSettings(client(), index);
assertThat(settings.get(IndexMetadata.INDEX_BLOCKS_WRITE_SETTING.getKey()), not("true"));
});
indexDocument(client(), index);
}
public void testDeleteDuringSnapshot() throws Exception {
// Create the repository before taking the snapshot.
Request request = new Request("PUT", "/_snapshot/repo");
request.setJsonEntity(Strings
.toString(JsonXContent.contentBuilder()
.startObject()
.field("type", "fs")
.startObject("settings")
.field("compress", randomBoolean())
.field("location", System.getProperty("tests.path.repo"))
.field("max_snapshot_bytes_per_sec", "256b")
.endObject()
.endObject()));
assertOK(client().performRequest(request));
// create delete policy
createNewSingletonPolicy(client(), policy, "delete", new DeleteAction(), TimeValue.timeValueMillis(0));
// create index without policy
createIndexWithSettings(client(), index, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0));
// index document so snapshot actually does something
indexDocument(client(), index);
// start snapshot
String snapName = "snapshot-" + randomAlphaOfLength(6).toLowerCase(Locale.ROOT);
request = new Request("PUT", "/_snapshot/repo/" + snapName);
request.addParameter("wait_for_completion", "false");
request.setJsonEntity("{\"indices\": \"" + index + "\"}");
assertOK(client().performRequest(request));
// add policy and expect it to trigger delete immediately (while snapshot in progress)
updatePolicy(client(), index, policy);
// assert that index was deleted
assertBusy(() -> assertFalse(indexExists(index)), 2, TimeUnit.MINUTES);
// assert that snapshot is still in progress and clean up
assertThat(getSnapshotState(client(), snapName), equalTo("SUCCESS"));
assertOK(client().performRequest(new Request("DELETE", "/_snapshot/repo/" + snapName)));
}
public void testReadOnly() throws Exception {
createIndexWithSettings(client(), index, alias, Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0));
createNewSingletonPolicy(client(), policy, "warm", new ReadOnlyAction());
updatePolicy(client(), index, policy);
assertBusy(() -> {
Map<String, Object> settings = getOnlyIndexSettings(client(), index);
assertThat(getStepKeyForIndex(client(), index), equalTo(PhaseCompleteStep.finalStep("warm").getKey()));
assertThat(settings.get(IndexMetadata.INDEX_BLOCKS_WRITE_SETTING.getKey()), equalTo("true"));
assertThat(settings.get(IndexMetadata.INDEX_BLOCKS_METADATA_SETTING.getKey()), nullValue());
});
}
public void testReadOnlyInTheHotPhase() throws Exception {
String originalIndex = index + "-000001";
// add a policy
Map<String, LifecycleAction> hotActions = Map.of(
RolloverAction.NAME, new RolloverAction(null, null, 1L),
ReadOnlyAction.NAME, new ReadOnlyAction());
Map<String, Phase> phases = Map.of(
"hot", new Phase("hot", TimeValue.ZERO, hotActions));
LifecyclePolicy lifecyclePolicy = new LifecyclePolicy(policy, phases);
Request createPolicyRequest = new Request("PUT", "_ilm/policy/" + policy);
createPolicyRequest.setJsonEntity("{ \"policy\":" + Strings.toString(lifecyclePolicy) + "}");
client().performRequest(createPolicyRequest);
// then create the index and index a document to trigger rollover
createIndexWithSettings(client(), originalIndex, alias, Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
.put("index.lifecycle.rollover_alias", alias)
.put("index.lifecycle.name", policy));
index(client(), originalIndex, "_id", "foo", "bar");
assertBusy(() -> {
Map<String, Object> settings = getOnlyIndexSettings(client(), originalIndex);
assertThat(getStepKeyForIndex(client(), originalIndex), equalTo(PhaseCompleteStep.finalStep("hot").getKey()));
assertThat(settings.get(IndexMetadata.INDEX_BLOCKS_WRITE_SETTING.getKey()), equalTo("true"));
});
}
public void forceMergeActionWithCodec(String codec) throws Exception {
createIndexWithSettings(client(), index, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0));
for (int i = 0; i < randomIntBetween(2, 10); i++) {
Request request = new Request("PUT", index + "/_doc/" + i);
request.addParameter("refresh", "true");
request.setEntity(new StringEntity("{\"a\": \"test\"}", ContentType.APPLICATION_JSON));
client().performRequest(request);
}
assertThat(getNumberOfSegments(client(), index), greaterThanOrEqualTo(1));
createNewSingletonPolicy(client(), policy, "warm", new ForceMergeAction(1, codec));
updatePolicy(client(), index, policy);
assertBusy(() -> {
assertThat(getStepKeyForIndex(client(), index), equalTo(PhaseCompleteStep.finalStep("warm").getKey()));
Map<String, Object> settings = getOnlyIndexSettings(client(), index);
assertThat(settings.get(EngineConfig.INDEX_CODEC_SETTING.getKey()), equalTo(codec));
assertThat(settings.get(IndexMetadata.INDEX_BLOCKS_WRITE_SETTING.getKey()), equalTo("true"));
}, 30, TimeUnit.SECONDS);
expectThrows(ResponseException.class, () -> indexDocument(client(), index));
}
public void testForceMergeAction() throws Exception {
forceMergeActionWithCodec(null);
}
public void testForceMergeActionWithCompressionCodec() throws Exception {
forceMergeActionWithCodec("best_compression");
}
public void testFreezeAction() throws Exception {
createIndexWithSettings(client(), index, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0));
createNewSingletonPolicy(client(), policy, "cold", new FreezeAction());
updatePolicy(client(), index, policy);
assertBusy(() -> {
Map<String, Object> settings = getOnlyIndexSettings(client(), index);
assertThat(getStepKeyForIndex(client(), index), equalTo(PhaseCompleteStep.finalStep("cold").getKey()));
assertThat(settings.get(IndexMetadata.INDEX_BLOCKS_WRITE_SETTING.getKey()), equalTo("true"));
assertThat(settings.get(IndexSettings.INDEX_SEARCH_THROTTLED.getKey()), equalTo("true"));
assertThat(settings.get("index.frozen"), equalTo("true"));
});
}
public void testFreezeDuringSnapshot() throws Exception {
// Create the repository before taking the snapshot.
Request request = new Request("PUT", "/_snapshot/repo");
request.setJsonEntity(Strings
.toString(JsonXContent.contentBuilder()
.startObject()
.field("type", "fs")
.startObject("settings")
.field("compress", randomBoolean())
.field("location", System.getProperty("tests.path.repo"))
.field("max_snapshot_bytes_per_sec", "256b")
.endObject()
.endObject()));
assertOK(client().performRequest(request));
// create delete policy
createNewSingletonPolicy(client(), policy, "cold", new FreezeAction(), TimeValue.timeValueMillis(0));
// create index without policy
createIndexWithSettings(client(), index, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0));
// index document so snapshot actually does something
indexDocument(client(), index);
// start snapshot
request = new Request("PUT", "/_snapshot/repo/snapshot");
request.addParameter("wait_for_completion", "false");
request.setJsonEntity("{\"indices\": \"" + index + "\"}");
assertOK(client().performRequest(request));
// add policy and expect it to trigger delete immediately (while snapshot in progress)
updatePolicy(client(), index, policy);
// assert that the index froze
assertBusy(() -> {
Map<String, Object> settings = getOnlyIndexSettings(client(), index);
assertThat(getStepKeyForIndex(client(), index), equalTo(PhaseCompleteStep.finalStep("cold").getKey()));
assertThat(settings.get(IndexMetadata.INDEX_BLOCKS_WRITE_SETTING.getKey()), equalTo("true"));
assertThat(settings.get(IndexSettings.INDEX_SEARCH_THROTTLED.getKey()), equalTo("true"));
assertThat(settings.get("index.frozen"), equalTo("true"));
}, 2, TimeUnit.MINUTES);
// assert that snapshot is still in progress and clean up
assertThat(getSnapshotState(client(), "snapshot"), equalTo("SUCCESS"));
assertOK(client().performRequest(new Request("DELETE", "/_snapshot/repo/snapshot")));
}
public void testSetPriority() throws Exception {
createIndexWithSettings(client(), index, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0).put(IndexMetadata.INDEX_PRIORITY_SETTING.getKey(), 100));
int priority = randomIntBetween(0, 99);
createNewSingletonPolicy(client(), policy, "warm", new SetPriorityAction(priority));
updatePolicy(client(), index, policy);
assertBusy(() -> {
Map<String, Object> settings = getOnlyIndexSettings(client(), index);
assertThat(getStepKeyForIndex(client(), index), equalTo(PhaseCompleteStep.finalStep("warm").getKey()));
assertThat(settings.get(IndexMetadata.INDEX_PRIORITY_SETTING.getKey()), equalTo(String.valueOf(priority)));
});
}
public void testSetNullPriority() throws Exception {
createIndexWithSettings(client(), index, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0).put(IndexMetadata.INDEX_PRIORITY_SETTING.getKey(), 100));
createNewSingletonPolicy(client(), policy, "warm", new SetPriorityAction((Integer) null));
updatePolicy(client(), index, policy);
assertBusy(() -> {
Map<String, Object> settings = getOnlyIndexSettings(client(), index);
assertThat(getStepKeyForIndex(client(), index), equalTo(PhaseCompleteStep.finalStep("warm").getKey()));
assertNull(settings.get(IndexMetadata.INDEX_PRIORITY_SETTING.getKey()));
});
}
@SuppressWarnings("unchecked")
public void testNonexistentPolicy() throws Exception {
String indexPrefix = randomAlphaOfLengthBetween(5,15).toLowerCase(Locale.ROOT);
final StringEntity template = new StringEntity("{\n" +
" \"index_patterns\": \"" + indexPrefix + "*\",\n" +
" \"settings\": {\n" +
" \"index\": {\n" +
" \"lifecycle\": {\n" +
" \"name\": \"does_not_exist\",\n" +
" \"rollover_alias\": \"test_alias\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}", ContentType.APPLICATION_JSON);
Request templateRequest = new Request("PUT", "_template/test");
templateRequest.setEntity(template);
client().performRequest(templateRequest);
policy = randomAlphaOfLengthBetween(5,20);
createNewSingletonPolicy(client(), policy, "hot", new RolloverAction(null, null, 1L));
index = indexPrefix + "-000001";
final StringEntity putIndex = new StringEntity("{\n" +
" \"aliases\": {\n" +
" \"test_alias\": {\n" +
" \"is_write_index\": true\n" +
" }\n" +
" }\n" +
"}", ContentType.APPLICATION_JSON);
Request putIndexRequest = new Request("PUT", index);
putIndexRequest.setEntity(putIndex);
client().performRequest(putIndexRequest);
indexDocument(client(), index);
assertBusy(() -> {
Request explainRequest = new Request("GET", index + "/_ilm/explain");
Response response = client().performRequest(explainRequest);
Map<String, Object> responseMap;
try (InputStream is = response.getEntity().getContent()) {
responseMap = XContentHelper.convertToMap(XContentType.JSON.xContent(), is, true);
}
logger.info(responseMap);
Map<String, Object> indexStatus = (Map<String, Object>)((Map<String, Object>) responseMap.get("indices")).get(index);
assertNull(indexStatus.get("phase"));
assertNull(indexStatus.get("action"));
assertNull(indexStatus.get("step"));
Map<String, String> stepInfo = (Map<String, String>) indexStatus.get("step_info");
assertNotNull(stepInfo);
assertEquals("policy [does_not_exist] does not exist", stepInfo.get("reason"));
assertEquals("illegal_argument_exception", stepInfo.get("type"));
});
}
public void testInvalidPolicyNames() {
ResponseException ex;
policy = randomAlphaOfLengthBetween(0,10) + "," + randomAlphaOfLengthBetween(0,10);
ex = expectThrows(ResponseException.class, () -> createNewSingletonPolicy(client(), policy, "delete", new DeleteAction()));
assertThat(ex.getMessage(), containsString("invalid policy name"));
policy = randomAlphaOfLengthBetween(0,10) + "%20" + randomAlphaOfLengthBetween(0,10);
ex = expectThrows(ResponseException.class, () -> createNewSingletonPolicy(client(), policy, "delete", new DeleteAction()));
assertThat(ex.getMessage(), containsString("invalid policy name"));
policy = "_" + randomAlphaOfLengthBetween(1, 20);
ex = expectThrows(ResponseException.class, () -> createNewSingletonPolicy(client(), policy, "delete", new DeleteAction()));
assertThat(ex.getMessage(), containsString("invalid policy name"));
policy = randomAlphaOfLengthBetween(256, 1000);
ex = expectThrows(ResponseException.class, () -> createNewSingletonPolicy(client(), policy, "delete", new DeleteAction()));
assertThat(ex.getMessage(), containsString("invalid policy name"));
}
public void testDeletePolicyInUse() throws IOException {
String managedIndex1 = randomAlphaOfLength(7).toLowerCase(Locale.ROOT);
String managedIndex2 = randomAlphaOfLength(8).toLowerCase(Locale.ROOT);
String unmanagedIndex = randomAlphaOfLength(9).toLowerCase(Locale.ROOT);
String managedByOtherPolicyIndex = randomAlphaOfLength(10).toLowerCase(Locale.ROOT);
createNewSingletonPolicy(client(), policy, "delete", new DeleteAction(), TimeValue.timeValueHours(12));
String originalPolicy = policy;
String otherPolicy = randomValueOtherThan(policy, () -> randomAlphaOfLength(5));
policy = otherPolicy;
createNewSingletonPolicy(client(), policy, "delete", new DeleteAction(), TimeValue.timeValueHours(13));
createIndexWithSettings(client(), managedIndex1, Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, randomIntBetween(1, 10))
.put(LifecycleSettings.LIFECYCLE_NAME_SETTING.getKey(), originalPolicy));
createIndexWithSettings(client(), managedIndex2, Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, randomIntBetween(1, 10))
.put(LifecycleSettings.LIFECYCLE_NAME_SETTING.getKey(), originalPolicy));
createIndexWithSettings(client(), unmanagedIndex, Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, randomIntBetween(1, 10)));
createIndexWithSettings(client(), managedByOtherPolicyIndex, Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, randomIntBetween(1, 10))
.put(LifecycleSettings.LIFECYCLE_NAME_SETTING.getKey(), otherPolicy));
Request deleteRequest = new Request("DELETE", "_ilm/policy/" + originalPolicy);
ResponseException ex = expectThrows(ResponseException.class, () -> client().performRequest(deleteRequest));
assertThat(ex.getMessage(),
Matchers.allOf(
containsString("Cannot delete policy [" + originalPolicy + "]. It is in use by one or more indices: ["),
containsString(managedIndex1),
containsString(managedIndex2),
not(containsString(unmanagedIndex)),
not(containsString(managedByOtherPolicyIndex))));
}
public void testRemoveAndReaddPolicy() throws Exception {
String originalIndex = index + "-000001";
String secondIndex = index + "-000002";
// Set up a policy with rollover
createNewSingletonPolicy(client(), policy, "hot", new RolloverAction(null, null, 1L));
createIndexWithSettings(
client(),
originalIndex,
alias,
Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
.put(LifecycleSettings.LIFECYCLE_NAME, policy)
.put(RolloverAction.LIFECYCLE_ROLLOVER_ALIAS, alias));
// Index a document
index(client(), originalIndex, "_id", "foo", "bar");
// Wait for rollover to happen
assertBusy(() -> assertTrue(indexExists(secondIndex)));
// Remove the policy from the original index
Request removeRequest = new Request("POST", "/" + originalIndex + "/_ilm/remove");
removeRequest.setJsonEntity("");
client().performRequest(removeRequest);
// Add the policy again
Request addPolicyRequest = new Request("PUT", "/" + originalIndex + "/_settings");
addPolicyRequest.setJsonEntity("{\n" +
" \"settings\": {\n" +
" \"index.lifecycle.name\": \"" + policy + "\",\n" +
" \"index.lifecycle.rollover_alias\": \"" + alias + "\"\n" +
" }\n" +
"}");
client().performRequest(addPolicyRequest);
assertBusy(() -> assertTrue((boolean) explainIndex(client(), originalIndex).getOrDefault("managed", false)));
// Wait for everything to be copacetic
assertBusy(() -> assertThat(getStepKeyForIndex(client(), originalIndex), equalTo(PhaseCompleteStep.finalStep("hot").getKey())));
}
public void testCanStopILMWithPolicyUsingNonexistentPolicy() throws Exception {
createIndexWithSettings(client(), index, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
.put(LifecycleSettings.LIFECYCLE_NAME_SETTING.getKey(), randomAlphaOfLengthBetween(5,15)));
Request stopILMRequest = new Request("POST", "_ilm/stop");
assertOK(client().performRequest(stopILMRequest));
Request statusRequest = new Request("GET", "_ilm/status");
assertBusy(() -> {
Response statusResponse = client().performRequest(statusRequest);
assertOK(statusResponse);
Map<String, Object> statusResponseMap = entityAsMap(statusResponse);
String status = (String) statusResponseMap.get("operation_mode");
assertEquals("STOPPED", status);
});
// Re-start ILM so that subsequent tests don't fail
Request startILMReqest = new Request("POST", "_ilm/start");
assertOK(client().performRequest(startILMReqest));
}
public void testILMRolloverRetriesOnReadOnlyBlock() throws Exception {
String firstIndex = index + "-000001";
createNewSingletonPolicy(client(), policy, "hot", new RolloverAction(null, TimeValue.timeValueSeconds(1), null));
// create the index as readonly and associate the ILM policy to it
createIndexWithSettings(
client(),
firstIndex,
alias,
Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
.put(LifecycleSettings.LIFECYCLE_NAME, policy)
.put(RolloverAction.LIFECYCLE_ROLLOVER_ALIAS, alias)
.put("index.blocks.read_only", true),
true
);
// wait for ILM to start retrying the step
assertBusy(() -> assertThat((Integer) explainIndex(client(), firstIndex).get(FAILED_STEP_RETRY_COUNT_FIELD),
greaterThanOrEqualTo(1)));
// remove the read only block
Request allowWritesOnIndexSettingUpdate = new Request("PUT", firstIndex + "/_settings");
allowWritesOnIndexSettingUpdate.setJsonEntity("{" +
" \"index\": {\n" +
" \"blocks.read_only\" : \"false\" \n" +
" }\n" +
"}");
client().performRequest(allowWritesOnIndexSettingUpdate);
// index is not readonly so the ILM should complete successfully
assertBusy(() -> assertThat(getStepKeyForIndex(client(), firstIndex), equalTo(PhaseCompleteStep.finalStep("hot").getKey())));
}
public void testILMRolloverOnManuallyRolledIndex() throws Exception {
String originalIndex = index + "-000001";
String secondIndex = index + "-000002";
String thirdIndex = index + "-000003";
// Set up a policy with rollover
createNewSingletonPolicy(client(), policy, "hot", new RolloverAction(null, null, 2L));
Request createIndexTemplate = new Request("PUT", "_template/rolling_indexes");
createIndexTemplate.setJsonEntity("{" +
"\"index_patterns\": [\"" + index + "-*\"], \n" +
" \"settings\": {\n" +
" \"number_of_shards\": 1,\n" +
" \"number_of_replicas\": 0,\n" +
" \"index.lifecycle.name\": \"" + policy + "\", \n" +
" \"index.lifecycle.rollover_alias\": \"" + alias + "\"\n" +
" }\n" +
"}");
client().performRequest(createIndexTemplate);
createIndexWithSettings(
client(),
originalIndex,
alias,
Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0),
true
);
// Index a document
index(client(), originalIndex, "1", "foo", "bar");
Request refreshOriginalIndex = new Request("POST", "/" + originalIndex + "/_refresh");
client().performRequest(refreshOriginalIndex);
// Manual rollover
rolloverMaxOneDocCondition(client(), alias);
assertBusy(() -> assertTrue(indexExists(secondIndex)));
// Index another document into the original index so the ILM rollover policy condition is met
index(client(), originalIndex, "2", "foo", "bar");
client().performRequest(refreshOriginalIndex);
// Wait for the rollover policy to execute
assertBusy(() -> assertThat(getStepKeyForIndex(client(), originalIndex), equalTo(PhaseCompleteStep.finalStep("hot").getKey())));
// ILM should manage the second index after attempting (and skipping) rolling the original index
assertBusy(() -> assertTrue((boolean) explainIndex(client(), secondIndex).getOrDefault("managed", true)));
// index some documents to trigger an ILM rollover
index(client(), alias, "1", "foo", "bar");
index(client(), alias, "2", "foo", "bar");
index(client(), alias, "3", "foo", "bar");
Request refreshSecondIndex = new Request("POST", "/" + secondIndex + "/_refresh");
client().performRequest(refreshSecondIndex).getStatusLine();
// ILM should rollover the second index even though it skipped the first one
assertBusy(() -> assertThat(getStepKeyForIndex(client(), secondIndex), equalTo(PhaseCompleteStep.finalStep("hot").getKey())));
assertBusy(() -> assertTrue(indexExists(thirdIndex)));
}
public void testRolloverStepRetriesUntilRolledOverIndexIsDeleted() throws Exception {
String index = this.index + "-000001";
String rolledIndex = this.index + "-000002";
createNewSingletonPolicy(client(), policy, "hot", new RolloverAction(null, TimeValue.timeValueSeconds(1), null));
// create the rolled index so the rollover of the first index fails
createIndexWithSettings(
client(),
rolledIndex,
alias,
Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
.put(RolloverAction.LIFECYCLE_ROLLOVER_ALIAS, alias),
false
);
createIndexWithSettings(
client(),
index,
alias,
Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
.put(LifecycleSettings.LIFECYCLE_NAME, policy)
.put(RolloverAction.LIFECYCLE_ROLLOVER_ALIAS, alias),
true
);
assertBusy(() -> assertThat((Integer) explainIndex(client(), index).get(FAILED_STEP_RETRY_COUNT_FIELD), greaterThanOrEqualTo(1)),
30,
TimeUnit.SECONDS);
Request moveToStepRequest = new Request("POST", "_ilm/move/" + index);
moveToStepRequest.setJsonEntity("{\n" +
" \"current_step\": {\n" +
" \"phase\": \"hot\",\n" +
" \"action\": \"rollover\",\n" +
" \"name\": \"check-rollover-ready\"\n" +
" },\n" +
" \"next_step\": {\n" +
" \"phase\": \"hot\",\n" +
" \"action\": \"rollover\",\n" +
" \"name\": \"attempt-rollover\"\n" +
" }\n" +
"}");
// Using {@link #waitUntil} here as ILM moves back and forth between the {@link WaitForRolloverReadyStep} step and
// {@link org.elasticsearch.xpack.core.ilm.ErrorStep} in order to retry the failing step. As {@link #assertBusy}
// increases the wait time between calls exponentially, we might miss the window where the policy is on
// {@link WaitForRolloverReadyStep} and the move to `attempt-rollover` request will not be successful.
assertTrue(waitUntil(() -> {
try {
return client().performRequest(moveToStepRequest).getStatusLine().getStatusCode() == 200;
} catch (IOException e) {
return false;
}
}, 30, TimeUnit.SECONDS));
// Similar to above, using {@link #waitUntil} as we want to make sure the `attempt-rollover` step started failing and is being
// retried (which means ILM moves back and forth between the `attempt-rollover` step and the `error` step)
assertTrue("ILM did not start retrying the attempt-rollover step", waitUntil(() -> {
try {
Map<String, Object> explainIndexResponse = explainIndex(client(), index);
String failedStep = (String) explainIndexResponse.get("failed_step");
Integer retryCount = (Integer) explainIndexResponse.get(FAILED_STEP_RETRY_COUNT_FIELD);
return failedStep != null && failedStep.equals("attempt-rollover") && retryCount != null && retryCount >= 1;
} catch (IOException e) {
return false;
}
}, 30, TimeUnit.SECONDS));
deleteIndex(rolledIndex);
// the rollover step should eventually succeed
assertBusy(() -> assertThat(indexExists(rolledIndex), is(true)));
assertBusy(() -> assertThat(getStepKeyForIndex(client(), index), equalTo(PhaseCompleteStep.finalStep("hot").getKey())));
}
public void testUpdateRolloverLifecycleDateStepRetriesWhenRolloverInfoIsMissing() throws Exception {
String index = this.index + "-000001";
createNewSingletonPolicy(client(), policy, "hot", new RolloverAction(null, null, 1L));
createIndexWithSettings(
client(),
index,
alias,
Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
.put(LifecycleSettings.LIFECYCLE_NAME, policy)
.put(RolloverAction.LIFECYCLE_ROLLOVER_ALIAS, alias),
true
);
assertBusy(() -> assertThat(getStepKeyForIndex(client(), index).getName(), is(WaitForRolloverReadyStep.NAME)));
// moving ILM to the "update-rollover-lifecycle-date" without having gone through the actual rollover step
// the "update-rollover-lifecycle-date" step will fail as the index has no rollover information
Request moveToStepRequest = new Request("POST", "_ilm/move/" + index);
moveToStepRequest.setJsonEntity("{\n" +
" \"current_step\": {\n" +
" \"phase\": \"hot\",\n" +
" \"action\": \"rollover\",\n" +
" \"name\": \"check-rollover-ready\"\n" +
" },\n" +
" \"next_step\": {\n" +
" \"phase\": \"hot\",\n" +
" \"action\": \"rollover\",\n" +
" \"name\": \"update-rollover-lifecycle-date\"\n" +
" }\n" +
"}");
client().performRequest(moveToStepRequest);
assertBusy(() -> assertThat((Integer) explainIndex(client(), index).get(FAILED_STEP_RETRY_COUNT_FIELD), greaterThanOrEqualTo(1)),
30, TimeUnit.SECONDS);
index(client(), index, "1", "foo", "bar");
Request refreshIndex = new Request("POST", "/" + index + "/_refresh");
client().performRequest(refreshIndex);
// manual rollover the index so the "update-rollover-lifecycle-date" ILM step can continue and finish successfully as the index
// will have rollover information now
rolloverMaxOneDocCondition(client(), alias);
assertBusy(() -> assertThat(getStepKeyForIndex(client(), index), equalTo(PhaseCompleteStep.finalStep("hot").getKey())));
}
public void testWaitForActiveShardsStep() throws Exception {
String originalIndex = index + "-000001";
String secondIndex = index + "-000002";
createIndexWithSettings(client(), originalIndex, alias, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
.put(RolloverAction.LIFECYCLE_ROLLOVER_ALIAS, alias),
true);
// create policy
createNewSingletonPolicy(client(), policy, "hot", new RolloverAction(null, null, 1L));
// update policy on index
updatePolicy(client(), originalIndex, policy);
Request createIndexTemplate = new Request("PUT", "_template/rolling_indexes");
createIndexTemplate.setJsonEntity("{" +
"\"index_patterns\": [\""+ index + "-*\"], \n" +
" \"settings\": {\n" +
" \"number_of_shards\": 1,\n" +
" \"number_of_replicas\": 142,\n" +
" \"index.write.wait_for_active_shards\": \"all\"\n" +
" }\n" +
"}");
client().performRequest(createIndexTemplate);
// index document to trigger rollover
index(client(), originalIndex, "_id", "foo", "bar");
assertBusy(() -> assertTrue(indexExists(secondIndex)));
assertBusy(() -> assertThat(getStepKeyForIndex(client(), originalIndex).getName(), equalTo(WaitForActiveShardsStep.NAME)));
// reset the number of replicas to 0 so that the second index wait for active shard condition can be met
updateIndexSettings(secondIndex, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0));
assertBusy(() -> assertThat(getStepKeyForIndex(client(), originalIndex), equalTo(PhaseCompleteStep.finalStep("hot").getKey())));
}
public void testHistoryIsWrittenWithSuccess() throws Exception {
createNewSingletonPolicy(client(), policy, "hot", new RolloverAction(null, null, 1L));
Request createIndexTemplate = new Request("PUT", "_template/rolling_indexes");
createIndexTemplate.setJsonEntity("{" +
"\"index_patterns\": [\""+ index + "-*\"], \n" +
" \"settings\": {\n" +
" \"number_of_shards\": 1,\n" +
" \"number_of_replicas\": 0,\n" +
" \"index.lifecycle.name\": \"" + policy+ "\",\n" +
" \"index.lifecycle.rollover_alias\": \"" + alias + "\"\n" +
" }\n" +
"}");
client().performRequest(createIndexTemplate);
createIndexWithSettings(client(), index + "-1", alias, Settings.builder(), true);
// Index a document
index(client(), index + "-1", "1", "foo", "bar");
Request refreshIndex = new Request("POST", "/" + index + "-1/_refresh");
client().performRequest(refreshIndex);
assertBusy(() -> assertThat(getStepKeyForIndex(client(), index + "-1"), equalTo(PhaseCompleteStep.finalStep("hot").getKey())));
assertBusy(() -> assertHistoryIsPresent(policy, index + "-1", true, "check-rollover-ready"), 30, TimeUnit.SECONDS);
assertBusy(() -> assertHistoryIsPresent(policy, index + "-1", true, "attempt-rollover"), 30, TimeUnit.SECONDS);
assertBusy(() -> assertHistoryIsPresent(policy, index + "-1", true, "set-indexing-complete"), 30, TimeUnit.SECONDS);
assertBusy(() -> assertHistoryIsPresent(policy, index + "-1", true, "complete"), 30, TimeUnit.SECONDS);
assertBusy(() -> assertHistoryIsPresent(policy, index + "-000002", true, "check-rollover-ready"), 30, TimeUnit.SECONDS);
}