-
Notifications
You must be signed in to change notification settings - Fork 24.3k
/
CcrRetentionLeaseIT.java
1203 lines (1089 loc) · 65 KB
/
CcrRetentionLeaseIT.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.ccr;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest;
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.action.admin.indices.close.CloseIndexRequest;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsRequest;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.admin.indices.stats.ShardStats;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.action.support.broadcast.BroadcastResponse;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.seqno.RetentionLease;
import org.elasticsearch.index.seqno.RetentionLeaseActions;
import org.elasticsearch.index.seqno.RetentionLeaseNotFoundException;
import org.elasticsearch.index.seqno.RetentionLeaseUtils;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.IndexShardClosedException;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.snapshots.RestoreInfo;
import org.elasticsearch.snapshots.RestoreService;
import org.elasticsearch.test.transport.MockTransportService;
import org.elasticsearch.transport.ConnectTransportException;
import org.elasticsearch.transport.RemoteTransportException;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.TransportActionProxy;
import org.elasticsearch.transport.TransportMessageListener;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.xcontent.XContentType;
import org.elasticsearch.xpack.CcrIntegTestCase;
import org.elasticsearch.xpack.ccr.action.repositories.ClearCcrRestoreSessionAction;
import org.elasticsearch.xpack.ccr.repository.CcrRepository;
import org.elasticsearch.xpack.core.ccr.action.ForgetFollowerAction;
import org.elasticsearch.xpack.core.ccr.action.PutFollowAction;
import org.elasticsearch.xpack.core.ccr.action.ResumeFollowAction;
import org.elasticsearch.xpack.core.ccr.action.UnfollowAction;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
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.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.xpack.ccr.CcrRetentionLeases.retentionLeaseId;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize;
public class CcrRetentionLeaseIT extends CcrIntegTestCase {
public static final class RetentionLeaseRenewIntervalSettingPlugin extends Plugin {
@Override
public List<Setting<?>> getSettings() {
return Collections.singletonList(CcrRetentionLeases.RETENTION_LEASE_RENEW_INTERVAL_SETTING);
}
}
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Stream.concat(super.nodePlugins().stream(), Stream.of(RetentionLeaseRenewIntervalSettingPlugin.class))
.collect(Collectors.toList());
}
@Override
protected Settings followerClusterSettings() {
return Settings.builder()
.put(super.followerClusterSettings())
.put(CcrRetentionLeases.RETENTION_LEASE_RENEW_INTERVAL_SETTING.getKey(), TimeValue.timeValueMillis(200))
.build();
}
private final IndicesOptions indicesOptions = IndicesOptions.strictSingleIndexNoExpandForbidClosed();
private RestoreSnapshotRequest setUpRestoreSnapshotRequest(
final String leaderIndex,
final int numberOfShards,
final int numberOfReplicas,
final String followerIndex,
final int numberOfDocuments
) throws IOException {
final ClusterUpdateSettingsRequest settingsRequest = new ClusterUpdateSettingsRequest().masterNodeTimeout(TimeValue.MAX_VALUE);
final String chunkSize = new ByteSizeValue(randomFrom(4, 128, 1024), ByteSizeUnit.KB).getStringRep();
settingsRequest.persistentSettings(Settings.builder().put(CcrSettings.RECOVERY_CHUNK_SIZE.getKey(), chunkSize));
assertAcked(followerClient().admin().cluster().updateSettings(settingsRequest).actionGet());
final String leaderClusterRepoName = CcrRepository.NAME_PREFIX + "leader_cluster";
final Map<String, String> additionalSettings = new HashMap<>();
additionalSettings.put(IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING.getKey(), TimeValue.timeValueMillis(200).getStringRep());
final String leaderIndexSettings = getIndexSettings(numberOfShards, numberOfReplicas, additionalSettings);
assertAcked(
leaderClient().admin()
.indices()
.prepareCreate(leaderIndex)
.setMasterNodeTimeout(TimeValue.MAX_VALUE)
.setSource(leaderIndexSettings, XContentType.JSON)
);
ensureLeaderGreen(leaderIndex);
logger.info("indexing [{}] docs", numberOfDocuments);
for (int i = 0; i < numberOfDocuments; i++) {
final String source = Strings.format("{\"f\":%d}", i);
leaderClient().prepareIndex(leaderIndex).setId(Integer.toString(i)).setSource(source, XContentType.JSON).get();
if (rarely()) {
leaderClient().admin().indices().prepareFlush(leaderIndex).setForce(true).setWaitIfOngoing(true).get();
}
}
leaderClient().admin().indices().prepareFlush(leaderIndex).setForce(true).setWaitIfOngoing(true).get();
final Settings.Builder settingsBuilder = Settings.builder()
.put(IndexMetadata.SETTING_INDEX_PROVIDED_NAME, followerIndex)
.put(CcrSettings.CCR_FOLLOWING_INDEX_SETTING.getKey(), true);
return new RestoreSnapshotRequest(leaderClusterRepoName, CcrRepository.LATEST).indexSettings(settingsBuilder)
.indices(leaderIndex)
.indicesOptions(indicesOptions)
.renamePattern("^(.*)$")
.renameReplacement(followerIndex)
.masterNodeTimeout(TimeValue.MAX_VALUE)
.quiet(true);
}
public void testRetentionLeaseIsTakenAtTheStartOfRecovery() throws Exception {
final String leaderIndex = "leader";
final int numberOfShards = randomIntBetween(1, 3);
final int numberOfReplicas = between(0, 1);
final String followerIndex = "follower";
final int numberOfDocuments = scaledRandomIntBetween(1, 8192);
final RestoreSnapshotRequest restoreRequest = setUpRestoreSnapshotRequest(
leaderIndex,
numberOfShards,
numberOfReplicas,
followerIndex,
numberOfDocuments
);
final RestoreService restoreService = getFollowerCluster().getCurrentMasterNodeInstance(RestoreService.class);
final ClusterService clusterService = getFollowerCluster().getCurrentMasterNodeInstance(ClusterService.class);
final PlainActionFuture<RestoreInfo> future = PlainActionFuture.newFuture();
restoreService.restoreSnapshot(restoreRequest, waitForRestore(clusterService, future));
// ensure that a retention lease has been put in place on each shard
assertBusy(() -> {
final IndicesStatsResponse stats = leaderClient().admin()
.indices()
.stats(new IndicesStatsRequest().clear().indices(leaderIndex))
.actionGet();
assertNotNull(stats.getShards());
assertThat(stats.getShards(), arrayWithSize(numberOfShards * (1 + numberOfReplicas)));
final List<ShardStats> shardsStats = getShardsStats(stats);
for (int i = 0; i < numberOfShards * (1 + numberOfReplicas); i++) {
assertNotNull(shardsStats.get(i).getRetentionLeaseStats());
final Map<String, RetentionLease> currentRetentionLeases = RetentionLeaseUtils.toMapExcludingPeerRecoveryRetentionLeases(
shardsStats.get(i).getRetentionLeaseStats().retentionLeases()
);
assertThat(Strings.toString(shardsStats.get(i)), currentRetentionLeases.values(), hasSize(1));
final RetentionLease retentionLease = currentRetentionLeases.values().iterator().next();
assertThat(retentionLease.id(), equalTo(getRetentionLeaseId(followerIndex, leaderIndex)));
}
});
final RestoreInfo restoreInfo = future.actionGet();
assertEquals(restoreInfo.totalShards(), restoreInfo.successfulShards());
assertEquals(0, restoreInfo.failedShards());
for (int i = 0; i < numberOfDocuments; ++i) {
assertExpectedDocument(followerIndex, i);
}
}
public void testRetentionLeaseIsRenewedDuringRecovery() throws Exception {
final String leaderIndex = "leader";
final int numberOfShards = randomIntBetween(1, 3);
final int numberOfReplicas = between(0, 1);
final String followerIndex = "follower";
final int numberOfDocuments = scaledRandomIntBetween(1, 8192);
final RestoreSnapshotRequest restoreRequest = setUpRestoreSnapshotRequest(
leaderIndex,
numberOfShards,
numberOfReplicas,
followerIndex,
numberOfDocuments
);
final RestoreService restoreService = getFollowerCluster().getCurrentMasterNodeInstance(RestoreService.class);
final ClusterService clusterService = getFollowerCluster().getCurrentMasterNodeInstance(ClusterService.class);
final CountDownLatch latch = new CountDownLatch(1);
// block the recovery from completing; this ensures the background sync is still running
final ClusterStateResponse followerClusterState = followerClient().admin().cluster().prepareState().clear().setNodes(true).get();
for (final DiscoveryNode senderNode : followerClusterState.getState().nodes()) {
final MockTransportService senderTransportService = (MockTransportService) getFollowerCluster().getInstance(
TransportService.class,
senderNode.getName()
);
senderTransportService.addSendBehavior((connection, requestId, action, request, options) -> {
if (ClearCcrRestoreSessionAction.INTERNAL_NAME.equals(action)
|| TransportActionProxy.getProxyAction(ClearCcrRestoreSessionAction.INTERNAL_NAME).equals(action)) {
try {
latch.await();
} catch (final InterruptedException e) {
fail(e.toString());
}
}
connection.sendRequest(requestId, action, request, options);
});
}
final PlainActionFuture<RestoreInfo> future = PlainActionFuture.newFuture();
restoreService.restoreSnapshot(restoreRequest, waitForRestore(clusterService, future));
try {
assertRetentionLeaseRenewal(numberOfShards, numberOfReplicas, followerIndex, leaderIndex);
latch.countDown();
} finally {
for (final DiscoveryNode senderNode : followerClusterState.getState().nodes()) {
final MockTransportService senderTransportService = (MockTransportService) getFollowerCluster().getInstance(
TransportService.class,
senderNode.getName()
);
senderTransportService.clearAllRules();
}
}
final RestoreInfo restoreInfo = future.actionGet();
assertEquals(restoreInfo.totalShards(), restoreInfo.
successfulShards());
assertEquals(0, restoreInfo.failedShards());
for (int i = 0; i < numberOfDocuments; i++) {
assertExpectedDocument(followerIndex, i);
}
}
public void testRetentionLeasesAreNotBeingRenewedAfterRecoveryCompletes() throws Exception {
final String leaderIndex = "leader";
final int numberOfShards = randomIntBetween(1, 3);
final int numberOfReplicas = between(0, 1);
final String followerIndex = "follower";
final int numberOfDocuments = scaledRandomIntBetween(1, 8192);
final RestoreSnapshotRequest restoreRequest = setUpRestoreSnapshotRequest(
leaderIndex,
numberOfShards,
numberOfReplicas,
followerIndex,
numberOfDocuments
);
final RestoreService restoreService = getFollowerCluster().getCurrentMasterNodeInstance(RestoreService.class);
final ClusterService clusterService = getFollowerCluster().getCurrentMasterNodeInstance(ClusterService.class);
final PlainActionFuture<RestoreInfo> future = PlainActionFuture.newFuture();
restoreService.restoreSnapshot(restoreRequest, waitForRestore(clusterService, future));
final RestoreInfo restoreInfo = future.actionGet();
final long start = System.nanoTime();
/*
* We want to ensure that the retention leases have been synced to all shard copies, as otherwise they might sync between the two
* times that we sample the retention leases, which would cause our check to fail.
*/
final TimeValue syncIntervalSetting = IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING.get(
leaderClient().admin().indices().prepareGetSettings(leaderIndex).get().getIndexToSettings().get(leaderIndex)
);
final long syncEnd = System.nanoTime();
Thread.sleep(Math.max(0, randomIntBetween(2, 4) * syncIntervalSetting.millis() - TimeUnit.NANOSECONDS.toMillis(syncEnd - start)));
final ClusterStateResponse leaderIndexClusterState = leaderClient().admin()
.cluster()
.prepareState()
.clear()
.setMetadata(true)
.setIndices(leaderIndex)
.get();
final String leaderUUID = leaderIndexClusterState.getState().metadata().index(leaderIndex).getIndexUUID();
/*
* We want to ensure that the background renewal is cancelled at the end of recovery. To do this, we will sleep a small multiple
* of the renew interval. If the renews are not cancelled, we expect that a renewal would have been sent while we were sleeping.
* After we wake up, it should be the case that the retention leases are the same (same timestamp) as that indicates that they were
* not renewed while we were sleeping.
*/
assertBusy(() -> {
// sample the leases after recovery
final List<Map<String, RetentionLease>> retentionLeases = new ArrayList<>();
assertBusy(() -> {
retentionLeases.clear();
final IndicesStatsResponse stats = leaderClient().admin()
.indices()
.stats(new IndicesStatsRequest().clear().indices(leaderIndex))
.actionGet();
assertNotNull(stats.getShards());
assertThat(stats.getShards(), arrayWithSize(numberOfShards * (1 + numberOfReplicas)));
final List<ShardStats> shardsStats = getShardsStats(stats);
for (int i = 0; i < numberOfShards * (1 + numberOfReplicas); i++) {
assertNotNull(shardsStats.get(i).getRetentionLeaseStats());
final Map<String, RetentionLease> currentRetentionLeases = RetentionLeaseUtils
.toMapExcludingPeerRecoveryRetentionLeases(shardsStats.get(i).getRetentionLeaseStats().retentionLeases());
assertThat(Strings.toString(shardsStats.get(i)), currentRetentionLeases.values(), hasSize(1));
final ClusterStateResponse followerIndexClusterState = followerClient().admin()
.cluster()
.prepareState()
.clear()
.setMetadata(true)
.setIndices(followerIndex)
.get();
final String followerUUID = followerIndexClusterState.getState().metadata().index(followerIndex).getIndexUUID();
final RetentionLease retentionLease = currentRetentionLeases.values().iterator().next();
final String expectedRetentionLeaseId = retentionLeaseId(
getFollowerCluster().getClusterName(),
new Index(followerIndex, followerUUID),
getLeaderCluster().getClusterName(),
new Index(leaderIndex, leaderUUID)
);
assertThat(retentionLease.id(), equalTo(expectedRetentionLeaseId));
retentionLeases.add(currentRetentionLeases);
}
});
// sleep a small multiple of the renew interval
final TimeValue renewIntervalSetting = CcrRetentionLeases.RETENTION_LEASE_RENEW_INTERVAL_SETTING.get(followerClusterSettings());
final long renewEnd = System.nanoTime();
Thread.sleep(
Math.max(0, randomIntBetween(2, 4) * renewIntervalSetting.millis() - TimeUnit.NANOSECONDS.toMillis(renewEnd - start))
);
// now ensure that the retention leases are the same
final IndicesStatsResponse stats = leaderClient().admin()
.indices()
.stats(new IndicesStatsRequest().clear().indices(leaderIndex))
.actionGet();
assertNotNull(stats.getShards());
assertThat(stats.getShards(), arrayWithSize(numberOfShards * (1 + numberOfReplicas)));
final List<ShardStats> shardsStats = getShardsStats(stats);
for (int i = 0; i < numberOfShards * (1 + numberOfReplicas); i++) {
if (shardsStats.get(i).getShardRouting().primary() == false) {
continue;
}
assertNotNull(shardsStats.get(i).getRetentionLeaseStats());
final Map<String, RetentionLease> currentRetentionLeases = RetentionLeaseUtils.toMapExcludingPeerRecoveryRetentionLeases(
shardsStats.get(i).getRetentionLeaseStats().retentionLeases()
);
assertThat(Strings.toString(shardsStats.get(i)), currentRetentionLeases.values(), hasSize(1));
final ClusterStateResponse followerIndexClusterState = followerClient().admin()
.cluster()
.prepareState()
.clear()
.setMetadata(true)
.setIndices(followerIndex)
.get();
final String followerUUID = followerIndexClusterState.getState().metadata().index(followerIndex).getIndexUUID();
final RetentionLease retentionLease = currentRetentionLeases.values().iterator().next();
assertThat(retentionLease.id(), equalTo(getRetentionLeaseId(followerIndex, followerUUID, leaderIndex, leaderUUID)));
// we assert that retention leases are being renewed by an increase in the timestamp
assertThat(retentionLease.timestamp(), equalTo(retentionLeases.get(i).values().iterator().next().timestamp()));
}
});
assertEquals(restoreInfo.totalShards(), restoreInfo.successfulShards());
assertEquals(0, restoreInfo.failedShards());
for (int i = 0; i < numberOfDocuments; ++i) {
assertExpectedDocument(followerIndex, i);
}
}
public void testUnfollowRemovesRetentionLeases() throws Exception {
final String leaderIndex = "leader";
final String followerIndex = "follower";
final int numberOfShards = randomIntBetween(1, 4);
final String leaderIndexSettings = getIndexSettings(numberOfShards, 0);
assertAcked(leaderClient().admin().indices().prepareCreate(leaderIndex).setSource(leaderIndexSettings, XContentType.JSON).get());
ensureLeaderYellow(leaderIndex);
final PutFollowAction.Request followRequest = putFollow(leaderIndex, followerIndex);
followerClient().execute(PutFollowAction.INSTANCE, followRequest).get();
ensureFollowerGreen(true, followerIndex);
final String retentionLeaseId = getRetentionLeaseId(followerIndex, leaderIndex);
final IndicesStatsResponse stats = leaderClient().admin()
.indices()
.stats(new IndicesStatsRequest().clear().indices(leaderIndex))
.actionGet();
final List<ShardStats> shardsStats = getShardsStats(stats);
for (final ShardStats shardStats : shardsStats) {
final Map<String, RetentionLease> retentionLeases = RetentionLeaseUtils.toMapExcludingPeerRecoveryRetentionLeases(
shardStats.getRetentionLeaseStats().retentionLeases()
);
assertThat(Strings.toString(shardStats), retentionLeases.values(), hasSize(1));
assertThat(retentionLeases.values().iterator().next().id(), equalTo(retentionLeaseId));
}
// we will sometimes fake that some of the retention leases are already removed on the leader shard
final Set<Integer> shardIds = new HashSet<>(
randomSubsetOf(randomIntBetween(0, numberOfShards), IntStream.range(0, numberOfShards).boxed().collect(Collectors.toSet()))
);
final ClusterStateResponse followerClusterState = followerClient().admin().cluster().prepareState().clear().setNodes(true).get();
try {
for (final DiscoveryNode senderNode : followerClusterState.getState().nodes()) {
final MockTransportService senderTransportService = (MockTransportService) getFollowerCluster().getInstance(
TransportService.class,
senderNode.getName()
);
senderTransportService.addSendBehavior((connection, requestId, action, request, options) -> {
if (RetentionLeaseActions.Remove.ACTION_NAME.equals(action)
|| TransportActionProxy.getProxyAction(RetentionLeaseActions.Remove.ACTION_NAME).equals(action)) {
final RetentionLeaseActions.RemoveRequest removeRequest = (RetentionLeaseActions.RemoveRequest) request;
if (shardIds.contains(removeRequest.getShardId().id())) {
final String primaryShardNodeId = getLeaderCluster().clusterService()
.state()
.routingTable()
.index(leaderIndex)
.shard(removeRequest.getShardId().id())
.primaryShard()
.currentNodeId();
final String primaryShardNodeName = getLeaderCluster().clusterService()
.state()
.nodes()
.get(primaryShardNodeId)
.getName();
final IndexShard primary = getLeaderCluster().getInstance(IndicesService.class, primaryShardNodeName)
.getShardOrNull(removeRequest.getShardId());
final CountDownLatch latch = new CountDownLatch(1);
primary.removeRetentionLease(
retentionLeaseId,
ActionListener.wrap(r -> latch.countDown(), e -> fail(e.toString()))
);
try {
latch.await();
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
fail(e.toString());
}
}
}
connection.sendRequest(requestId, action, request, options);
});
}
pauseFollow(followerIndex);
assertAcked(followerClient().admin().indices().close(new CloseIndexRequest(followerIndex)).actionGet());
assertAcked(followerClient().execute(UnfollowAction.INSTANCE, new UnfollowAction.Request(followerIndex)).actionGet());
final IndicesStatsResponse afterUnfollowStats = leaderClient().admin()
.indices()
.stats(new IndicesStatsRequest().clear().indices(leaderIndex))
.actionGet();
final List<ShardStats> afterUnfollowShardsStats = getShardsStats(afterUnfollowStats);
for (final ShardStats shardStats : afterUnfollowShardsStats) {
assertThat(
Strings.toString(shardStats),
RetentionLeaseUtils.toMapExcludingPeerRecoveryRetentionLeases(shardStats.getRetentionLeaseStats().retentionLeases())
.values(),
empty()
);
}
} finally {
for (final DiscoveryNode senderNode : followerClusterState.getState().nodes()) {
final MockTransportService senderTransportService = (MockTransportService) getFollowerCluster().getInstance(
TransportService.class,
senderNode.getName()
);
senderTransportService.clearAllRules();
}
}
}
public void testUnfollowFailsToRemoveRetentionLeases() throws Exception {
final String leaderIndex = "leader";
final String followerIndex = "follower";
final int numberOfShards = randomIntBetween(1, 4);
final String leaderIndexSettings = getIndexSettings(numberOfShards, 0);
assertAcked(leaderClient().admin().indices().prepareCreate(leaderIndex).setSource(leaderIndexSettings, XContentType.JSON).get());
ensureLeaderYellow(leaderIndex);
final PutFollowAction.Request followRequest = putFollow(leaderIndex, followerIndex);
followerClient().execute(PutFollowAction.INSTANCE, followRequest).get();
ensureFollowerGreen(true, followerIndex);
pauseFollow(followerIndex);
followerClient().admin().indices().close(new CloseIndexRequest(followerIndex).masterNodeTimeout(TimeValue.MAX_VALUE)).actionGet();
// we will disrupt requests to remove retention leases for these random shards
final Set<Integer> shardIds = new HashSet<>(
randomSubsetOf(randomIntBetween(1, numberOfShards), IntStream.range(0, numberOfShards).boxed().collect(Collectors.toSet()))
);
final ClusterStateResponse followerClusterState = followerClient().admin().cluster().prepareState().clear().setNodes(true).get();
try {
for (final DiscoveryNode senderNode : followerClusterState.getState().nodes()) {
final MockTransportService senderTransportService = (MockTransportService) getFollowerCluster().getInstance(
TransportService.class,
senderNode.getName()
);
senderTransportService.addSendBehavior((connection, requestId, action, request, options) -> {
if (RetentionLeaseActions.Remove.ACTION_NAME.equals(action)
|| TransportActionProxy.getProxyAction(RetentionLeaseActions.Remove.ACTION_NAME).equals(action)) {
final RetentionLeaseActions.RemoveRequest removeRequest = (RetentionLeaseActions.RemoveRequest) request;
if (shardIds.contains(removeRequest.getShardId().id())) {
throw randomBoolean()
? new ConnectTransportException(connection.getNode(), "connection failed")
: new IndexShardClosedException(removeRequest.getShardId());
}
}
connection.sendRequest(requestId, action, request, options);
});
}
final ElasticsearchException e = expectThrows(
ElasticsearchException.class,
() -> followerClient().execute(UnfollowAction.INSTANCE, new UnfollowAction.Request(followerIndex)).actionGet()
);
final ClusterStateResponse followerIndexClusterState = followerClient().admin()
.cluster()
.prepareState()
.clear()
.setMetadata(true)
.setIndices(followerIndex)
.get();
final String followerUUID = followerIndexClusterState.getState().metadata().index(followerIndex).getIndexUUID();
final ClusterStateResponse leaderIndexClusterState = leaderClient().admin()
.cluster()
.prepareState()
.clear()
.setMetadata(true)
.setIndices(leaderIndex)
.get();
final String leaderUUID = leaderIndexClusterState.getState().metadata().index(leaderIndex).getIndexUUID();
assertThat(
e.getMetadata("es.failed_to_remove_retention_leases"),
contains(
retentionLeaseId(
getFollowerCluster().getClusterName(),
new Index(followerIndex, followerUUID),
getLeaderCluster().getClusterName(),
new Index(leaderIndex, leaderUUID)
)
)
);
} finally {
for (final DiscoveryNode senderNode : followerClusterState.getState().nodes()) {
final MockTransportService senderTransportService = (MockTransportService) getFollowerCluster().getInstance(
TransportService.class,
senderNode.getName()
);
senderTransportService.clearAllRules();
}
}
}
public void testRetentionLeaseRenewedWhileFollowing() throws Exception {
final String leaderIndex = "leader";
final String followerIndex = "follower";
final int numberOfShards = randomIntBetween(1, 4);
final int numberOfReplicas = randomIntBetween(0, 1);
final Map<String, String> additionalIndexSettings = new HashMap<>();
additionalIndexSettings.put(
IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING.getKey(),
TimeValue.timeValueMillis(200).getStringRep()
);
final String leaderIndexSettings = getIndexSettings(numberOfShards, numberOfReplicas, additionalIndexSettings);
assertAcked(leaderClient().admin().indices().prepareCreate(leaderIndex).setSource(leaderIndexSettings, XContentType.JSON).get());
ensureLeaderYellow(leaderIndex);
final PutFollowAction.Request followRequest = putFollow(leaderIndex, followerIndex);
followerClient().execute(PutFollowAction.INSTANCE, followRequest).get();
ensureFollowerGreen(true, followerIndex);
assertRetentionLeaseRenewal(numberOfShards, numberOfReplicas, followerIndex, leaderIndex);
}
public void testRetentionLeaseAdvancesWhileFollowing() throws Exception {
final String leaderIndex = "leader";
final String followerIndex = "follower";
final int numberOfShards = randomIntBetween(1, 4);
final int numberOfReplicas = randomIntBetween(0, 1);
final Map<String, String> additionalIndexSettings = new HashMap<>();
additionalIndexSettings.put(
IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING.getKey(),
TimeValue.timeValueMillis(200).getStringRep()
);
final String leaderIndexSettings = getIndexSettings(numberOfShards, numberOfReplicas, additionalIndexSettings);
assertAcked(leaderClient().admin().indices().prepareCreate(leaderIndex).setSource(leaderIndexSettings, XContentType.JSON).get());
ensureLeaderYellow(leaderIndex);
final PutFollowAction.Request followRequest = putFollow(leaderIndex, followerIndex);
followerClient().execute(PutFollowAction.INSTANCE, followRequest).get();
ensureFollowerGreen(true, followerIndex);
final int numberOfDocuments = randomIntBetween(128, 2048);
logger.debug("indexing [{}] docs", numberOfDocuments);
for (int i = 0; i < numberOfDocuments; i++) {
final String source = Strings.format("{\"f\":%d}", i);
leaderClient().prepareIndex(leaderIndex).setId(Integer.toString(i)).setSource(source, XContentType.JSON).get();
if (rarely()) {
leaderClient().admin().indices().prepareFlush(leaderIndex).setForce(true).setWaitIfOngoing(true).get();
}
}
// wait until the follower global checkpoints have caught up to the leader
assertIndexFullyReplicatedToFollower(leaderIndex, followerIndex);
final List<ShardStats> leaderShardsStats = getShardsStats(leaderClient().admin().indices().prepareStats(leaderIndex).get());
final Map<Integer, Long> leaderGlobalCheckpoints = new HashMap<>();
for (final ShardStats leaderShardStats : leaderShardsStats) {
final ShardRouting routing = leaderShardStats.getShardRouting();
if (routing.primary() == false) {
continue;
}
leaderGlobalCheckpoints.put(routing.id(), leaderShardStats.getSeqNoStats().getGlobalCheckpoint());
}
// now assert that the retention leases have advanced to the global checkpoints
assertBusy(() -> {
final IndicesStatsResponse stats = leaderClient().admin()
.indices()
.stats(new IndicesStatsRequest().clear().indices(leaderIndex))
.actionGet();
assertNotNull(stats.getShards());
assertThat(stats.getShards(), arrayWithSize(numberOfShards * (1 + numberOfReplicas)));
final List<ShardStats> shardsStats = getShardsStats(stats);
for (int i = 0; i < numberOfShards * (1 + numberOfReplicas); i++) {
assertNotNull(shardsStats.get(i).getRetentionLeaseStats());
final Map<String, RetentionLease> currentRetentionLeases = RetentionLeaseUtils.toMapExcludingPeerRecoveryRetentionLeases(
shardsStats.get(i).getRetentionLeaseStats().retentionLeases()
);
assertThat(Strings.toString(shardsStats.get(i)), currentRetentionLeases.values(), hasSize(1));
final RetentionLease retentionLease = currentRetentionLeases.values().iterator().next();
assertThat(retentionLease.id(), equalTo(getRetentionLeaseId(followerIndex, leaderIndex)));
// we assert that retention leases are being advanced
assertThat(
retentionLease.retainingSequenceNumber(),
equalTo(leaderGlobalCheckpoints.get(shardsStats.get(i).getShardRouting().id()) + 1)
);
}
});
}
public void testRetentionLeaseRenewalIsCancelledWhenFollowingIsPaused() throws Exception {
final String leaderIndex = "leader";
final String followerIndex = "follower";
final int numberOfShards = randomIntBetween(1, 4);
final int numberOfReplicas = randomIntBetween(0, 1);
final Map<String, String> additionalIndexSettings = new HashMap<>();
additionalIndexSettings.put(
IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING.getKey(),
TimeValue.timeValueMillis(200).getStringRep()
);
final String leaderIndexSettings = getIndexSettings(numberOfShards, numberOfReplicas, additionalIndexSettings);
assertAcked(leaderClient().admin().indices().prepareCreate(leaderIndex).setSource(leaderIndexSettings, XContentType.JSON).get());
ensureLeaderYellow(leaderIndex);
final PutFollowAction.Request followRequest = putFollow(leaderIndex, followerIndex);
followerClient().execute(PutFollowAction.INSTANCE, followRequest).get();
ensureFollowerGreen(true, followerIndex);
final long start = System.nanoTime();
pauseFollow(followerIndex);
/*
* We want to ensure that the retention leases have been synced to all shard copies, as otherwise they might sync between the two
* times that we sample the retention leases, which would cause our check to fail.
*/
final TimeValue syncIntervalSetting = IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING.get(
leaderClient().admin().indices().prepareGetSettings(leaderIndex).get().getIndexToSettings().get(leaderIndex)
);
final long syncEnd = System.nanoTime();
Thread.sleep(Math.max(0, randomIntBetween(2, 4) * syncIntervalSetting.millis() - TimeUnit.NANOSECONDS.toMillis(syncEnd - start)));
final ClusterStateResponse leaderIndexClusterState = leaderClient().admin()
.cluster()
.prepareState()
.clear()
.setMetadata(true)
.setIndices(leaderIndex)
.get();
final String leaderUUID = leaderIndexClusterState.getState().metadata().index(leaderIndex).getIndexUUID();
/*
* We want to ensure that the background renewal is cancelled after pausing. To do this, we will sleep a small multiple of the renew
* interval. If the renews are not cancelled, we expect that a renewal would have been sent while we were sleeping. After we wake
* up, it should be the case that the retention leases are the same (same timestamp) as that indicates that they were not renewed
* while we were sleeping.
*/
assertBusy(() -> {
// sample the leases after pausing
final List<Map<String, RetentionLease>> retentionLeases = new ArrayList<>();
assertBusy(() -> {
retentionLeases.clear();
final IndicesStatsResponse stats = leaderClient().admin()
.indices()
.stats(new IndicesStatsRequest().clear().indices(leaderIndex))
.actionGet();
assertNotNull(stats.getShards());
assertThat(stats.getShards(), arrayWithSize(numberOfShards * (1 + numberOfReplicas)));
final List<ShardStats> shardsStats = getShardsStats(stats);
for (int i = 0; i < numberOfShards * (1 + numberOfReplicas); i++) {
assertNotNull(shardsStats.get(i).getRetentionLeaseStats());
final Map<String, RetentionLease> currentRetentionLeases = RetentionLeaseUtils
.toMapExcludingPeerRecoveryRetentionLeases(shardsStats.get(i).getRetentionLeaseStats().retentionLeases());
assertThat(Strings.toString(shardsStats.get(i)), currentRetentionLeases.values(), hasSize(1));
final ClusterStateResponse followerIndexClusterState = followerClient().admin()
.cluster()
.prepareState()
.clear()
.setMetadata(true)
.setIndices(followerIndex)
.get();
final String followerUUID = followerIndexClusterState.getState().metadata().index(followerIndex).getIndexUUID();
final RetentionLease retentionLease = currentRetentionLeases.values().iterator().next();
final String expectedRetentionLeaseId = retentionLeaseId(
getFollowerCluster().getClusterName(),
new Index(followerIndex, followerUUID),
getLeaderCluster().getClusterName(),
new Index(leaderIndex, leaderUUID)
);
assertThat(retentionLease.id(), equalTo(expectedRetentionLeaseId));
retentionLeases.add(currentRetentionLeases);
}
});
// sleep a small multiple of the renew interval
final TimeValue renewIntervalSetting = CcrRetentionLeases.RETENTION_LEASE_RENEW_INTERVAL_SETTING.get(followerClusterSettings());
final long renewEnd = System.nanoTime();
Thread.sleep(
Math.max(0, randomIntBetween(2, 4) * renewIntervalSetting.millis() - TimeUnit.NANOSECONDS.toMillis(renewEnd - start))
);
// now ensure that the retention leases are the same
final IndicesStatsResponse stats = leaderClient().admin()
.indices()
.stats(new IndicesStatsRequest().clear().indices(leaderIndex))
.actionGet();
assertNotNull(stats.getShards());
assertThat(stats.getShards(), arrayWithSize(numberOfShards * (1 + numberOfReplicas)));
final List<ShardStats> shardsStats = getShardsStats(stats);
for (int i = 0; i < numberOfShards * (1 + numberOfReplicas); i++) {
if (shardsStats.get(i).getShardRouting().primary() == false) {
continue;
}
assertNotNull(shardsStats.get(i).getRetentionLeaseStats());
final Map<String, RetentionLease> currentRetentionLeases = RetentionLeaseUtils.toMapExcludingPeerRecoveryRetentionLeases(
shardsStats.get(i).getRetentionLeaseStats().retentionLeases()
);
assertThat(Strings.toString(shardsStats.get(i)), currentRetentionLeases.values(), hasSize(1));
final ClusterStateResponse followerIndexClusterState = followerClient().admin()
.cluster()
.prepareState()
.clear()
.setMetadata(true)
.setIndices(followerIndex)
.get();
final String followerUUID = followerIndexClusterState.getState().metadata().index(followerIndex).getIndexUUID();
final RetentionLease retentionLease = currentRetentionLeases.values().iterator().next();
assertThat(retentionLease.id(), equalTo(getRetentionLeaseId(followerIndex, followerUUID, leaderIndex, leaderUUID)));
// we assert that retention leases are not being renewed by an unchanged timestamp
assertThat(retentionLease.timestamp(), equalTo(retentionLeases.get(i).values().iterator().next().timestamp()));
}
});
}
public void testRetentionLeaseRenewalIsResumedWhenFollowingIsResumed() throws Exception {
final String leaderIndex = "leader";
final String followerIndex = "follower";
final int numberOfShards = randomIntBetween(1, 4);
final int numberOfReplicas = randomIntBetween(0, 1);
final Map<String, String> additionalIndexSettings = new HashMap<>();
additionalIndexSettings.put(
IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING.getKey(),
TimeValue.timeValueMillis(200).getStringRep()
);
final String leaderIndexSettings = getIndexSettings(numberOfShards, numberOfReplicas, additionalIndexSettings);
assertAcked(leaderClient().admin().indices().prepareCreate(leaderIndex).setSource(leaderIndexSettings, XContentType.JSON).get());
ensureLeaderYellow(leaderIndex);
final PutFollowAction.Request followRequest = putFollow(leaderIndex, followerIndex);
followerClient().execute(PutFollowAction.INSTANCE, followRequest).get();
ensureFollowerGreen(true, followerIndex);
pauseFollow(followerIndex);
followerClient().execute(ResumeFollowAction.INSTANCE, resumeFollow(followerIndex)).actionGet();
ensureFollowerGreen(true, followerIndex);
assertRetentionLeaseRenewal(numberOfShards, numberOfReplicas, followerIndex, leaderIndex);
}
public void testRetentionLeaseIsAddedIfItDisappearsWhileFollowing() throws Exception {
final String leaderIndex = "leader";
final String followerIndex = "follower";
final int numberOfShards = 1;
final int numberOfReplicas = 1;
final Map<String, String> additionalIndexSettings = new HashMap<>();
additionalIndexSettings.put(
IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING.getKey(),
TimeValue.timeValueMillis(200).getStringRep()
);
final String leaderIndexSettings = getIndexSettings(numberOfShards, numberOfReplicas, additionalIndexSettings);
assertAcked(leaderClient().admin().indices().prepareCreate(leaderIndex).setSource(leaderIndexSettings, XContentType.JSON).get());
ensureLeaderYellow(leaderIndex);
final PutFollowAction.Request followRequest = putFollow(leaderIndex, followerIndex);
followerClient().execute(PutFollowAction.INSTANCE, followRequest).get();
ensureFollowerGreen(true, followerIndex);
final CountDownLatch latch = new CountDownLatch(1);
final ClusterStateResponse followerClusterState = followerClient().admin().cluster().prepareState().clear().setNodes(true).get();
try {
for (final DiscoveryNode senderNode : followerClusterState.getState().nodes()) {
final MockTransportService senderTransportService = (MockTransportService) getFollowerCluster().getInstance(
TransportService.class,
senderNode.getName()
);
senderTransportService.addSendBehavior((connection, requestId, action, request, options) -> {
if (RetentionLeaseActions.Renew.ACTION_NAME.equals(action)
|| TransportActionProxy.getProxyAction(RetentionLeaseActions.Renew.ACTION_NAME).equals(action)) {
final RetentionLeaseActions.RenewRequest renewRequest = (RetentionLeaseActions.RenewRequest) request;
final String retentionLeaseId = getRetentionLeaseId(followerIndex, leaderIndex);
if (retentionLeaseId.equals(renewRequest.getId())) {
logger.info("--> intercepting renewal request for retention lease [{}]", retentionLeaseId);
senderTransportService.clearAllRules();
final String primaryShardNodeId = getLeaderCluster().clusterService()
.state()
.routingTable()
.index(leaderIndex)
.shard(renewRequest.getShardId().id())
.primaryShard()
.currentNodeId();
final String primaryShardNodeName = getLeaderCluster().clusterService()
.state()
.nodes()
.get(primaryShardNodeId)
.getName();
final IndexShard primary = getLeaderCluster().getInstance(IndicesService.class, primaryShardNodeName)
.getShardOrNull(renewRequest.getShardId());
final CountDownLatch innerLatch = new CountDownLatch(1);
try {
// this forces the background renewal from following to face a retention lease not found exception
logger.info("--> removing retention lease [{}] on the leader", retentionLeaseId);
primary.removeRetentionLease(
retentionLeaseId,
ActionListener.wrap(r -> innerLatch.countDown(), e -> fail(e.toString()))
);
logger.info(
"--> waiting for the removed retention lease [{}] to be synced on the leader",
retentionLeaseId
);
innerLatch.await();
logger.info("--> removed retention lease [{}] on the leader", retentionLeaseId);
} catch (final Exception e) {
throw new AssertionError("failed to remove retention lease [" + retentionLeaseId + "] on the leader");
} finally {
latch.countDown();
}
}
}
connection.sendRequest(requestId, action, request, options);
});
}
latch.await();
assertRetentionLeaseRenewal(numberOfShards, numberOfReplicas, followerIndex, leaderIndex);
} finally {
for (final DiscoveryNode senderNode : followerClusterState.getState().nodes()) {
final MockTransportService senderTransportService = (MockTransportService) getFollowerCluster().getInstance(
TransportService.class,
senderNode.getName()
);
senderTransportService.clearAllRules();
}
}
}
/**
* This test is fairly evil. This test is to ensure that we are protected against a race condition when unfollowing and a background
* renewal fires. The action of unfollowing will remove retention leases from the leader. If a background renewal is firing at that
* time, it means that we will be met with a retention lease not found exception. That will in turn trigger behavior to attempt to
* re-add the retention lease, which means we are left in a situation where we have unfollowed, but the retention lease still remains
* on the leader. However, we have a guard against this in the callback after the retention lease not found exception is thrown, which
* checks if the shard follow node task is cancelled or completed.
*
* To test this this behavior is correct, we capture the call to renew the retention lease. Then, we will step in between and execute
* an unfollow request. This will remove the retention lease on the leader. At this point, we can unlatch the renew call, which will
* now be met with a retention lease not found exception. We will cheat and wait for that response to come back, and then synchronously
* trigger the listener which will check to see if the shard follow node task is cancelled or completed, and if not, add the retention
* lease back. After that listener returns, we can check to see if a retention lease exists on the leader.
*
* Note, this done mean that listener will fire twice, once in our onResponseReceived hook, and once after our onResponseReceived
* callback returns. 🤷♀️
*
* @throws Exception if an exception occurs in the main test thread
*/
public void testPeriodicRenewalDoesNotAddRetentionLeaseAfterUnfollow() throws Exception {
final String leaderIndex = "leader";
final String followerIndex = "follower";
final int numberOfShards = 1;
final int numberOfReplicas = 1;
final Map<String, String> additionalIndexSettings = new HashMap<>();
additionalIndexSettings.put(
IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING.getKey(),
TimeValue.timeValueMillis(200).getStringRep()
);
final String leaderIndexSettings = getIndexSettings(numberOfShards, numberOfReplicas, additionalIndexSettings);
assertAcked(leaderClient().admin().indices().prepareCreate(leaderIndex).setSource(leaderIndexSettings, XContentType.JSON).get());
ensureLeaderYellow(leaderIndex);
final PutFollowAction.Request followRequest = putFollow(leaderIndex, followerIndex);
followerClient().execute(PutFollowAction.INSTANCE, followRequest).get();
ensureFollowerGreen(true, followerIndex);
final CountDownLatch removeLeaseLatch = new CountDownLatch(1);
final CountDownLatch unfollowLatch = new CountDownLatch(1);
final CountDownLatch responseLatch = new CountDownLatch(1);
final ClusterStateResponse followerClusterState = followerClient().admin().cluster().prepareState().clear().setNodes(true).get();
try {
for (final DiscoveryNode senderNode : followerClusterState.getState().nodes()) {
final MockTransportService senderTransportService = (MockTransportService) getFollowerCluster().getInstance(
TransportService.class,
senderNode.getName()
);
senderTransportService.addSendBehavior((connection, requestId, action, request, options) -> {
if (RetentionLeaseActions.Renew.ACTION_NAME.equals(action)
|| TransportActionProxy.getProxyAction(RetentionLeaseActions.Renew.ACTION_NAME).equals(action)) {
final String retentionLeaseId = getRetentionLeaseId(followerIndex, leaderIndex);
logger.info("--> blocking renewal request for retention lease [{}] until unfollowed", retentionLeaseId);
try {
removeLeaseLatch.countDown();
unfollowLatch.await();
senderTransportService.addMessageListener(new TransportMessageListener() {
@SuppressWarnings("rawtypes")
@Override
public void onResponseReceived(final long responseRequestId, final Transport.ResponseContext context) {
if (requestId == responseRequestId) {
final RetentionLeaseNotFoundException e = new RetentionLeaseNotFoundException(retentionLeaseId);
context.handler().handleException(new RemoteTransportException(e.getMessage(), e));
responseLatch.countDown();
senderTransportService.removeMessageListener(this);
}
}
});
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
fail(e.toString());
}
}
connection.sendRequest(requestId, action, request, options);
});
}