c9f1e43a12ef85f732e25b0a35073e5857a86904
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / DistributedDataStoreRemotingIntegrationTest.java
1 /*
2  * Copyright (c) 2015, 2017 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.datastore;
9
10 import static org.awaitility.Awaitility.await;
11 import static org.hamcrest.CoreMatchers.instanceOf;
12 import static org.hamcrest.MatcherAssert.assertThat;
13 import static org.hamcrest.Matchers.equalTo;
14 import static org.junit.Assert.assertEquals;
15 import static org.junit.Assert.assertNotNull;
16 import static org.junit.Assert.assertThrows;
17 import static org.junit.Assert.assertTrue;
18 import static org.junit.Assume.assumeTrue;
19 import static org.mockito.ArgumentMatchers.any;
20 import static org.mockito.ArgumentMatchers.anyString;
21 import static org.mockito.ArgumentMatchers.eq;
22 import static org.mockito.Mockito.doAnswer;
23 import static org.mockito.Mockito.mock;
24 import static org.mockito.Mockito.timeout;
25 import static org.mockito.Mockito.verify;
26
27 import akka.actor.ActorRef;
28 import akka.actor.ActorSelection;
29 import akka.actor.ActorSystem;
30 import akka.actor.Address;
31 import akka.actor.AddressFromURIString;
32 import akka.cluster.Cluster;
33 import akka.cluster.Member;
34 import akka.dispatch.Futures;
35 import akka.pattern.Patterns;
36 import akka.testkit.javadsl.TestKit;
37 import com.google.common.base.Stopwatch;
38 import com.google.common.base.Throwables;
39 import com.google.common.collect.ImmutableMap;
40 import com.google.common.primitives.UnsignedLong;
41 import com.google.common.util.concurrent.ListenableFuture;
42 import com.google.common.util.concurrent.MoreExecutors;
43 import com.google.common.util.concurrent.Uninterruptibles;
44 import com.typesafe.config.ConfigFactory;
45 import java.util.Arrays;
46 import java.util.Collection;
47 import java.util.Collections;
48 import java.util.LinkedList;
49 import java.util.List;
50 import java.util.Optional;
51 import java.util.concurrent.ExecutionException;
52 import java.util.concurrent.ExecutorService;
53 import java.util.concurrent.Executors;
54 import java.util.concurrent.TimeUnit;
55 import java.util.concurrent.atomic.AtomicBoolean;
56 import java.util.concurrent.atomic.AtomicLong;
57 import org.junit.After;
58 import org.junit.Before;
59 import org.junit.Test;
60 import org.junit.runner.RunWith;
61 import org.junit.runners.Parameterized;
62 import org.junit.runners.Parameterized.Parameter;
63 import org.junit.runners.Parameterized.Parameters;
64 import org.mockito.stubbing.Answer;
65 import org.opendaylight.controller.cluster.access.client.RequestTimeoutException;
66 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
67 import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
68 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
69 import org.opendaylight.controller.cluster.databroker.TestClientBackedDataStore;
70 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
71 import org.opendaylight.controller.cluster.datastore.TestShard.RequestFrontendMetadata;
72 import org.opendaylight.controller.cluster.datastore.TestShard.StartDropMessages;
73 import org.opendaylight.controller.cluster.datastore.TestShard.StopDropMessages;
74 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
75 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
76 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
77 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
78 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
79 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
80 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
81 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
82 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
83 import org.opendaylight.controller.cluster.datastore.persisted.FrontendClientMetadata;
84 import org.opendaylight.controller.cluster.datastore.persisted.FrontendShardDataTreeSnapshotMetadata;
85 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
86 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
87 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
88 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
89 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
90 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
91 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
92 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
93 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
94 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
95 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
96 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
97 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
98 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
99 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
100 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
101 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
102 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
103 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
104 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
105 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
106 import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
107 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
108 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
109 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
110 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
111 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
112 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
113 import org.opendaylight.yangtools.yang.common.Uint64;
114 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
115 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
117 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
119 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
120 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
121 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
122 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
123 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
124 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
125 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
126 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
127 import scala.collection.Set;
128 import scala.concurrent.Await;
129 import scala.concurrent.Future;
130 import scala.concurrent.duration.FiniteDuration;
131
132 /**
133  * End-to-end distributed data store tests that exercise remote shards and transactions.
134  *
135  * @author Thomas Pantelis
136  */
137 @RunWith(Parameterized.class)
138 public class DistributedDataStoreRemotingIntegrationTest extends AbstractTest {
139
140     @Parameters(name = "{0}")
141     public static Collection<Object[]> data() {
142         return Arrays.asList(new Object[][] {
143                 { TestDistributedDataStore.class, 7}, { TestClientBackedDataStore.class, 12 }
144         });
145     }
146
147     @Parameter(0)
148     public Class<? extends AbstractDataStore> testParameter;
149     @Parameter(1)
150     public int commitTimeout;
151
152     private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
153     private static final String[] CARS = {"cars"};
154
155     private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse(
156             "akka://cluster-test@127.0.0.1:2558");
157     private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse(
158             "akka://cluster-test@127.0.0.1:2559");
159
160     private static final String MODULE_SHARDS_CARS_ONLY_1_2 = "module-shards-cars-member-1-and-2.conf";
161     private static final String MODULE_SHARDS_CARS_PEOPLE_1_2 = "module-shards-member1-and-2.conf";
162     private static final String MODULE_SHARDS_CARS_PEOPLE_1_2_3 = "module-shards-member1-and-2-and-3.conf";
163     private static final String MODULE_SHARDS_CARS_1_2_3 = "module-shards-cars-member-1-and-2-and-3.conf";
164
165     private ActorSystem leaderSystem;
166     private ActorSystem followerSystem;
167     private ActorSystem follower2System;
168
169     private final DatastoreContext.Builder leaderDatastoreContextBuilder =
170             DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
171
172     private final DatastoreContext.Builder followerDatastoreContextBuilder =
173             DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5)
174                 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
175     private final TransactionIdentifier tx1 = nextTransactionId();
176     private final TransactionIdentifier tx2 = nextTransactionId();
177
178     private AbstractDataStore followerDistributedDataStore;
179     private AbstractDataStore leaderDistributedDataStore;
180     private IntegrationTestKit followerTestKit;
181     private IntegrationTestKit leaderTestKit;
182
183     @Before
184     public void setUp() {
185         InMemoryJournal.clear();
186         InMemorySnapshotStore.clear();
187
188         leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
189         Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
190
191         followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
192         Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
193
194         follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
195         Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
196     }
197
198     @After
199     public void tearDown() {
200         if (followerDistributedDataStore != null) {
201             leaderDistributedDataStore.close();
202         }
203         if (leaderDistributedDataStore != null) {
204             leaderDistributedDataStore.close();
205         }
206
207         TestKit.shutdownActorSystem(leaderSystem);
208         TestKit.shutdownActorSystem(followerSystem);
209         TestKit.shutdownActorSystem(follower2System);
210
211         InMemoryJournal.clear();
212         InMemorySnapshotStore.clear();
213     }
214
215     private void initDatastoresWithCars(final String type) throws Exception {
216         initDatastores(type, MODULE_SHARDS_CARS_ONLY_1_2, CARS);
217     }
218
219     private void initDatastoresWithCarsAndPeople(final String type) throws Exception {
220         initDatastores(type, MODULE_SHARDS_CARS_PEOPLE_1_2, CARS_AND_PEOPLE);
221     }
222
223     private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards)
224             throws Exception {
225         initDatastores(type, moduleShardsConfig, shards, leaderDatastoreContextBuilder,
226                 followerDatastoreContextBuilder);
227     }
228
229     private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards,
230             final DatastoreContext.Builder leaderBuilder, final DatastoreContext.Builder followerBuilder)
231                     throws Exception {
232         leaderTestKit = new IntegrationTestKit(leaderSystem, leaderBuilder, commitTimeout);
233
234         leaderDistributedDataStore = leaderTestKit.setupAbstractDataStore(
235                 testParameter, type, moduleShardsConfig, false, shards);
236
237         followerTestKit = new IntegrationTestKit(followerSystem, followerBuilder, commitTimeout);
238         followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
239                 testParameter, type, moduleShardsConfig, false, shards);
240
241         leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorUtils(), shards);
242
243         leaderTestKit.waitForMembersUp("member-2");
244         followerTestKit.waitForMembersUp("member-1");
245     }
246
247     private static void verifyCars(final DOMStoreReadTransaction readTx, final MapEntryNode... entries)
248             throws Exception {
249         final Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
250         assertTrue("isPresent", optional.isPresent());
251
252         final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(
253                 CarsModel.CAR_QNAME);
254         for (final NormalizedNode<?, ?> entry: entries) {
255             listBuilder.withChild((MapEntryNode) entry);
256         }
257
258         assertEquals("Car list node", listBuilder.build(), optional.get());
259     }
260
261     private static void verifyNode(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path,
262             final NormalizedNode<?, ?> expNode) throws Exception {
263         assertEquals(Optional.of(expNode), readTx.read(path).get(5, TimeUnit.SECONDS));
264     }
265
266     private static void verifyExists(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path)
267             throws Exception {
268         assertEquals("exists", Boolean.TRUE, readTx.exists(path).get(5, TimeUnit.SECONDS));
269     }
270
271     @Test
272     public void testWriteTransactionWithSingleShard() throws Exception {
273         final String testName = "testWriteTransactionWithSingleShard";
274         initDatastoresWithCars(testName);
275
276         final String followerCarShardName = "member-2-shard-cars-" + testName;
277
278         DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
279         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
280
281         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
282         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
283
284         final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
285         final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
286         writeTx.merge(car1Path, car1);
287
288         final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
289         final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
290         writeTx.merge(car2Path, car2);
291
292         followerTestKit.doCommit(writeTx.ready());
293
294         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
295
296         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
297
298         // Test delete
299
300         writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
301
302         writeTx.delete(car1Path);
303
304         followerTestKit.doCommit(writeTx.ready());
305
306         verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
307
308         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
309
310         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
311
312         // Re-instate the follower member 2 as a single-node to verify replication and recovery.
313
314         // The following is a bit tricky. Before we reinstate the follower we need to ensure it has persisted and
315         // applied and all the log entries from the leader. Since we've verified the car data above we know that
316         // all the transactions have been applied on the leader so we first read and capture its lastAppliedIndex.
317         final AtomicLong leaderLastAppliedIndex = new AtomicLong();
318         IntegrationTestKit.verifyShardState(leaderDistributedDataStore, CARS[0],
319             state -> leaderLastAppliedIndex.set(state.getLastApplied()));
320
321         // Now we need to make sure the follower has persisted the leader's lastAppliedIndex via ApplyJournalEntries.
322         // However we don't know exactly how many ApplyJournalEntries messages there will be as it can differ between
323         // the tell-based and ask-based front-ends. For ask-based there will be exactly 2 ApplyJournalEntries but
324         // tell-based persists additional payloads which could be replicated and applied in a batch resulting in
325         // either 2 or 3 ApplyJournalEntries. To handle this we read the follower's persisted ApplyJournalEntries
326         // until we find the one that encompasses the leader's lastAppliedIndex.
327         Stopwatch sw = Stopwatch.createStarted();
328         boolean done = false;
329         while (!done) {
330             final List<ApplyJournalEntries> entries = InMemoryJournal.get(followerCarShardName,
331                     ApplyJournalEntries.class);
332             for (ApplyJournalEntries aje: entries) {
333                 if (aje.getToIndex() >= leaderLastAppliedIndex.get()) {
334                     done = true;
335                     break;
336                 }
337             }
338
339             assertTrue("Follower did not persist ApplyJournalEntries containing leader's lastAppliedIndex "
340                     + leaderLastAppliedIndex + ". Entries persisted: " + entries, sw.elapsed(TimeUnit.SECONDS) <= 5);
341
342             Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
343         }
344
345         TestKit.shutdownActorSystem(leaderSystem, true);
346         TestKit.shutdownActorSystem(followerSystem, true);
347
348         final ActorSystem newSystem = newActorSystem("reinstated-member2", "Member2");
349
350         try (AbstractDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder,
351                 commitTimeout)
352                 .setupAbstractDataStore(testParameter, testName, "module-shards-member2", true, CARS)) {
353             verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
354         }
355     }
356
357     @Test
358     public void testSingleTransactionsWritesInQuickSuccession() throws Exception {
359         initDatastoresWithCars("testSingleTransactionsWritesInQuickSuccession");
360
361         final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
362
363         DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
364         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
365         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
366         followerTestKit.doCommit(writeTx.ready());
367
368         int numCars = 5;
369         for (int i = 0; i < numCars; i++) {
370             writeTx = txChain.newWriteOnlyTransaction();
371             writeTx.write(CarsModel.newCarPath("car" + i), CarsModel.newCarEntry("car" + i, Uint64.valueOf(20000)));
372             followerTestKit.doCommit(writeTx.ready());
373
374             DOMStoreReadTransaction domStoreReadTransaction = txChain.newReadOnlyTransaction();
375             domStoreReadTransaction.read(CarsModel.BASE_PATH).get();
376
377             domStoreReadTransaction.close();
378         }
379
380         // wait to let the shard catch up with purged
381         await("Range set leak test").atMost(5, TimeUnit.SECONDS)
382                 .pollInterval(500, TimeUnit.MILLISECONDS)
383                 .untilAsserted(() -> {
384                     final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars")
385                         .orElseThrow();
386                     final var frontendMetadata =
387                         (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
388                             .executeOperation(localShard, new RequestFrontendMetadata());
389
390                     final var clientMeta = frontendMetadata.getClients().get(0);
391                     if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
392                         assertTellClientMetadata(clientMeta, numCars);
393                     } else {
394                         assertAskClientMetadata(clientMeta);
395                     }
396                 });
397
398         try (var tx = txChain.newReadOnlyTransaction()) {
399             final var body = tx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS).orElseThrow().getValue();
400             assertThat(body, instanceOf(Collection.class));
401             assertEquals(numCars, ((Collection<?>) body).size());
402         }
403     }
404
405     private void assertAskClientMetadata(final FrontendClientMetadata clientMeta) {
406         // ask based should track no metadata
407         assertEquals(List.of(), clientMeta.getCurrentHistories());
408     }
409
410     private void assertTellClientMetadata(final FrontendClientMetadata clientMeta, final int numCars) {
411         final var iterator = clientMeta.getCurrentHistories().iterator();
412         var metadata = iterator.next();
413         while (iterator.hasNext() && metadata.getHistoryId() != 1) {
414             metadata = iterator.next();
415         }
416
417         assertEquals(0, metadata.getClosedTransactions().size());
418
419         final var purgedRanges = metadata.getPurgedTransactions().ranges();
420
421         // FIXME: CONTROLLER-1991: remove this assumption
422         assumeTrue(false);
423
424         assertEquals(1, purgedRanges.size());
425         final var purgedRange = purgedRanges.first();
426         assertEquals(UnsignedLong.ZERO, purgedRange.lower());
427         assertEquals(UnsignedLong.valueOf(10), purgedRange.upper());
428     }
429
430     @Test
431     public void testCloseTransactionMetadataLeak() throws Exception {
432         // FIXME: Ask-based frontend seems to have some issues with back to back close
433         assumeTrue(testParameter.isAssignableFrom(TestClientBackedDataStore.class));
434
435         initDatastoresWithCars("testCloseTransactionMetadataLeak");
436
437         final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
438
439         DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
440         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
441         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
442         followerTestKit.doCommit(writeTx.ready());
443
444         int numCars = 5;
445         for (int i = 0; i < numCars; i++) {
446             writeTx = txChain.newWriteOnlyTransaction();
447             writeTx.close();
448
449             DOMStoreReadTransaction domStoreReadTransaction = txChain.newReadOnlyTransaction();
450             domStoreReadTransaction.read(CarsModel.BASE_PATH).get();
451
452             domStoreReadTransaction.close();
453         }
454
455         writeTx = txChain.newWriteOnlyTransaction();
456         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
457         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
458         followerTestKit.doCommit(writeTx.ready());
459
460         // wait to let the shard catch up with purged
461         await("Close transaction purge leak test.").atMost(5, TimeUnit.SECONDS)
462                 .pollInterval(500, TimeUnit.MILLISECONDS)
463                 .untilAsserted(() -> {
464                     final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars")
465                         .orElseThrow();
466                     final var frontendMetadata =
467                             (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
468                                     .executeOperation(localShard, new RequestFrontendMetadata());
469
470                     final var clientMeta = frontendMetadata.getClients().get(0);
471                     if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
472                         assertTellClientMetadata(clientMeta, numCars);
473                     } else {
474                         assertAskClientMetadata(clientMeta);
475                     }
476                 });
477
478         try (var tx = txChain.newReadOnlyTransaction()) {
479             final var body = tx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS).orElseThrow().getValue();
480             assertThat(body, instanceOf(Collection.class));
481             assertEquals(numCars, ((Collection<?>) body).size());
482         }
483     }
484
485     @Test
486     public void testReadWriteTransactionWithSingleShard() throws Exception {
487         initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
488
489         final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
490         assertNotNull("newReadWriteTransaction returned null", rwTx);
491
492         rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
493         rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
494
495         final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
496         rwTx.merge(CarsModel.newCarPath("optima"), car1);
497
498         verifyCars(rwTx, car1);
499
500         final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
501         final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
502         rwTx.merge(car2Path, car2);
503
504         verifyExists(rwTx, car2Path);
505
506         followerTestKit.doCommit(rwTx.ready());
507
508         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
509     }
510
511     @Test
512     public void testWriteTransactionWithMultipleShards() throws Exception {
513         initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
514
515         final DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
516         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
517
518         final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
519         final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
520         writeTx.write(carsPath, carsNode);
521
522         final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
523         final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
524         writeTx.write(peoplePath, peopleNode);
525
526         followerTestKit.doCommit(writeTx.ready());
527
528         final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
529
530         verifyNode(readTx, carsPath, carsNode);
531         verifyNode(readTx, peoplePath, peopleNode);
532     }
533
534     @Test
535     public void testReadWriteTransactionWithMultipleShards() throws Exception {
536         initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
537
538         final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
539         assertNotNull("newReadWriteTransaction returned null", rwTx);
540
541         final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
542         final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
543         rwTx.write(carsPath, carsNode);
544
545         final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
546         final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
547         rwTx.write(peoplePath, peopleNode);
548
549         followerTestKit.doCommit(rwTx.ready());
550
551         final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
552
553         verifyNode(readTx, carsPath, carsNode);
554         verifyNode(readTx, peoplePath, peopleNode);
555     }
556
557     @Test
558     public void testTransactionChainWithSingleShard() throws Exception {
559         initDatastoresWithCars("testTransactionChainWithSingleShard");
560
561         final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
562
563         // Add the top-level cars container with write-only.
564
565         final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
566         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
567
568         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
569
570         final DOMStoreThreePhaseCommitCohort writeTxReady = writeTx.ready();
571
572         // Verify the top-level cars container with read-only.
573
574         verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
575
576         // Perform car operations with read-write.
577
578         final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
579
580         verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
581
582         rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
583
584         final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
585         final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
586         rwTx.write(car1Path, car1);
587
588         verifyExists(rwTx, car1Path);
589
590         verifyCars(rwTx, car1);
591
592         final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
593         rwTx.merge(CarsModel.newCarPath("sportage"), car2);
594
595         rwTx.delete(car1Path);
596
597         followerTestKit.doCommit(writeTxReady);
598
599         followerTestKit.doCommit(rwTx.ready());
600
601         txChain.close();
602
603         verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
604     }
605
606     @Test
607     public void testTransactionChainWithMultipleShards() throws Exception {
608         initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
609
610         final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
611
612         DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
613         assertNotNull("newWriteOnlyTransaction returned null", writeTx);
614
615         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
616         writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
617
618         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
619         writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
620
621         followerTestKit.doCommit(writeTx.ready());
622
623         final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
624
625         final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
626         final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
627         readWriteTx.write(carPath, car);
628
629         final MapEntryNode person = PeopleModel.newPersonEntry("jack");
630         final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
631         readWriteTx.merge(personPath, person);
632
633         assertEquals(Optional.of(car), readWriteTx.read(carPath).get(5, TimeUnit.SECONDS));
634         assertEquals(Optional.of(person), readWriteTx.read(personPath).get(5, TimeUnit.SECONDS));
635
636         final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
637
638         writeTx = txChain.newWriteOnlyTransaction();
639
640         writeTx.delete(personPath);
641
642         final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
643
644         followerTestKit.doCommit(cohort2);
645         followerTestKit.doCommit(cohort3);
646
647         txChain.close();
648
649         final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
650         verifyCars(readTx, car);
651
652         assertEquals(Optional.empty(), readTx.read(personPath).get(5, TimeUnit.SECONDS));
653     }
654
655     @Test
656     public void testChainedTransactionFailureWithSingleShard() throws Exception {
657         initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
658
659         final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
660                 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
661                         LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
662                         MoreExecutors.directExecutor());
663
664         final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
665         final DOMTransactionChain txChain = broker.createTransactionChain(listener);
666
667         final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
668
669         final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
670                 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
671                     .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
672
673         writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
674
675         final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
676             .getCause();
677         assertThat(ex, instanceOf(TransactionCommitFailedException.class));
678
679         verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
680
681         txChain.close();
682         broker.close();
683     }
684
685     @Test
686     public void testChainedTransactionFailureWithMultipleShards() throws Exception {
687         initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
688
689         final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
690                 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
691                         LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
692                         MoreExecutors.directExecutor());
693
694         final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
695         final DOMTransactionChain txChain = broker.createTransactionChain(listener);
696
697         final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
698
699         writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
700
701         final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
702                 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
703                     .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
704
705         // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
706         // done for put for performance reasons.
707         writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
708
709         final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
710             .getCause();
711         assertThat(ex, instanceOf(TransactionCommitFailedException.class));
712
713         verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
714
715         txChain.close();
716         broker.close();
717     }
718
719     @Test
720     public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
721         followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
722         final String testName = "testSingleShardTransactionsWithLeaderChanges";
723         initDatastoresWithCars(testName);
724
725         final String followerCarShardName = "member-2-shard-cars-" + testName;
726         InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class);
727
728         // Write top-level car container from the follower so it uses a remote Tx.
729
730         DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
731
732         writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
733         writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
734
735         followerTestKit.doCommit(writeTx.ready());
736
737         InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
738
739         // Switch the leader to the follower
740
741         sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
742                 .shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
743
744         TestKit.shutdownActorSystem(leaderSystem, true);
745         Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
746
747         followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorUtils(), CARS);
748
749         leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
750         Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
751
752         final DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder()
753                 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
754         IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder, commitTimeout);
755
756         try (AbstractDataStore ds =
757                 newMember1TestKit.setupAbstractDataStore(
758                         testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS)) {
759
760             followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), CARS);
761
762             // Write a car entry to the new leader - should switch to local Tx
763
764             writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
765
766             MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
767             YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
768             writeTx.merge(car1Path, car1);
769
770             followerTestKit.doCommit(writeTx.ready());
771
772             verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
773         }
774     }
775
776     @SuppressWarnings("unchecked")
777     @Test
778     public void testReadyLocalTransactionForwardedToLeader() throws Exception {
779         initDatastoresWithCars("testReadyLocalTransactionForwardedToLeader");
780         followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
781
782         final Optional<ActorRef> carsFollowerShard =
783                 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
784         assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
785
786         final DataTree dataTree = new InMemoryDataTreeFactory().create(
787             DataTreeConfiguration.DEFAULT_OPERATIONAL, SchemaContextHelper.full());
788
789         // Send a tx with immediate commit.
790
791         DataTreeModification modification = dataTree.takeSnapshot().newModification();
792         new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
793         new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
794
795         final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
796         new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
797         modification.ready();
798
799         ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(tx1 , modification, true, Optional.empty());
800
801         carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
802         Object resp = followerTestKit.expectMsgClass(Object.class);
803         if (resp instanceof akka.actor.Status.Failure) {
804             throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
805         }
806
807         assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
808
809         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
810
811         // Send another tx without immediate commit.
812
813         modification = dataTree.takeSnapshot().newModification();
814         MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
815         new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
816         modification.ready();
817
818         readyLocal = new ReadyLocalTransaction(tx2 , modification, false, Optional.empty());
819
820         carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
821         resp = followerTestKit.expectMsgClass(Object.class);
822         if (resp instanceof akka.actor.Status.Failure) {
823             throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
824         }
825
826         assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
827
828         final ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
829                 ((ReadyTransactionReply)resp).getCohortPath());
830
831         ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(leaderDistributedDataStore.getActorUtils(),
832             List.of(new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor),
833                 () -> DataStoreVersions.CURRENT_VERSION)), tx2);
834         cohort.canCommit().get(5, TimeUnit.SECONDS);
835         cohort.preCommit().get(5, TimeUnit.SECONDS);
836         cohort.commit().get(5, TimeUnit.SECONDS);
837
838         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
839     }
840
841     @SuppressWarnings("unchecked")
842     @Test
843     public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
844         initDatastoresWithCars("testForwardedReadyTransactionForwardedToLeader");
845         followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
846
847         final Optional<ActorRef> carsFollowerShard =
848                 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
849         assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
850
851         carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
852         final DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
853
854         // Send a tx with immediate commit.
855
856         DataTreeModification modification = dataTree.takeSnapshot().newModification();
857         new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
858         new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
859
860         final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
861         new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
862
863         ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction(tx1, DataStoreVersions.CURRENT_VERSION,
864             new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx1, modification),
865             true, Optional.empty());
866
867         carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
868         Object resp = followerTestKit.expectMsgClass(Object.class);
869         if (resp instanceof akka.actor.Status.Failure) {
870             throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
871         }
872
873         assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
874
875         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
876
877         // Send another tx without immediate commit.
878
879         modification = dataTree.takeSnapshot().newModification();
880         MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
881         new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
882
883         forwardedReady = new ForwardedReadyTransaction(tx2, DataStoreVersions.CURRENT_VERSION,
884             new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx2, modification),
885             false, Optional.empty());
886
887         carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
888         resp = followerTestKit.expectMsgClass(Object.class);
889         if (resp instanceof akka.actor.Status.Failure) {
890             throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
891         }
892
893         assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
894
895         ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
896                 ((ReadyTransactionReply)resp).getCohortPath());
897
898         final ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
899             leaderDistributedDataStore.getActorUtils(), List.of(
900                 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor),
901                     () -> DataStoreVersions.CURRENT_VERSION)), tx2);
902         cohort.canCommit().get(5, TimeUnit.SECONDS);
903         cohort.preCommit().get(5, TimeUnit.SECONDS);
904         cohort.commit().get(5, TimeUnit.SECONDS);
905
906         verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
907     }
908
909     @Test
910     public void testTransactionForwardedToLeaderAfterRetry() throws Exception {
911         // FIXME: remove when test passes also for ClientBackedDataStore
912         assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
913
914         followerDatastoreContextBuilder.shardBatchedModificationCount(2);
915         leaderDatastoreContextBuilder.shardBatchedModificationCount(2);
916         initDatastoresWithCarsAndPeople("testTransactionForwardedToLeaderAfterRetry");
917
918         // Do an initial write to get the primary shard info cached.
919
920         final DOMStoreWriteTransaction initialWriteTx = followerDistributedDataStore.newWriteOnlyTransaction();
921         initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
922         initialWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
923         followerTestKit.doCommit(initialWriteTx.ready());
924
925         // Wait for the commit to be replicated to the follower.
926
927         MemberNode.verifyRaftState(followerDistributedDataStore, "cars",
928             raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
929
930         MemberNode.verifyRaftState(followerDistributedDataStore, "people",
931             raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
932
933         // Prepare, ready and canCommit a WO tx that writes to 2 shards. This will become the current tx in
934         // the leader shard.
935
936         final DOMStoreWriteTransaction writeTx1 = followerDistributedDataStore.newWriteOnlyTransaction();
937         writeTx1.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
938         writeTx1.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
939         final DOMStoreThreePhaseCommitCohort writeTx1Cohort = writeTx1.ready();
940         final ListenableFuture<Boolean> writeTx1CanCommit = writeTx1Cohort.canCommit();
941         writeTx1CanCommit.get(5, TimeUnit.SECONDS);
942
943         // Prepare and ready another WO tx that writes to 2 shards but don't canCommit yet. This will be queued
944         // in the leader shard.
945
946         final DOMStoreWriteTransaction writeTx2 = followerDistributedDataStore.newWriteOnlyTransaction();
947         final LinkedList<MapEntryNode> cars = new LinkedList<>();
948         int carIndex = 1;
949         cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
950         writeTx2.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
951         carIndex++;
952         NormalizedNode<?, ?> people = ImmutableNodes.mapNodeBuilder(PeopleModel.PERSON_QNAME)
953                 .withChild(PeopleModel.newPersonEntry("Dude")).build();
954         writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
955         final DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
956
957         // Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
958         // tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
959         // leader shard (with shardBatchedModificationCount set to 2). The 3rd BatchedModidifications will be
960         // sent on ready.
961
962         final DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
963         for (int i = 1; i <= 5; i++, carIndex++) {
964             cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
965             writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
966         }
967
968         // Prepare another WO that writes to a single shard. This will send a single BatchedModidifications
969         // message on ready.
970
971         final DOMStoreWriteTransaction writeTx4 = followerDistributedDataStore.newWriteOnlyTransaction();
972         cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
973         writeTx4.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
974         carIndex++;
975
976         // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaciton message to the
977         // leader shard on ready.
978
979         final DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
980         cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
981         readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
982
983         IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
984             stats -> assertEquals("getReadWriteTransactionCount", 5, stats.getReadWriteTransactionCount()));
985
986         // Disable elections on the leader so it switches to follower.
987
988         sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
989                 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
990                 .shardElectionTimeoutFactor(10));
991
992         leaderTestKit.waitUntilNoLeader(leaderDistributedDataStore.getActorUtils(), "cars");
993
994         // Submit all tx's - the messages should get queued for retry.
995
996         final ListenableFuture<Boolean> writeTx2CanCommit = writeTx2Cohort.canCommit();
997         final DOMStoreThreePhaseCommitCohort writeTx3Cohort = writeTx3.ready();
998         final DOMStoreThreePhaseCommitCohort writeTx4Cohort = writeTx4.ready();
999         final DOMStoreThreePhaseCommitCohort rwTxCohort = readWriteTx.ready();
1000
1001         // Enable elections on the other follower so it becomes the leader, at which point the
1002         // tx's should get forwarded from the previous leader to the new leader to complete the commits.
1003
1004         sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1005                 .customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
1006         IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorUtils(), "cars")
1007                 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
1008         IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorUtils(), "people")
1009                 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
1010
1011         followerTestKit.doCommit(writeTx1CanCommit, writeTx1Cohort);
1012         followerTestKit.doCommit(writeTx2CanCommit, writeTx2Cohort);
1013         followerTestKit.doCommit(writeTx3Cohort);
1014         followerTestKit.doCommit(writeTx4Cohort);
1015         followerTestKit.doCommit(rwTxCohort);
1016
1017         DOMStoreReadTransaction readTx = leaderDistributedDataStore.newReadOnlyTransaction();
1018         verifyCars(readTx, cars.toArray(new MapEntryNode[cars.size()]));
1019         verifyNode(readTx, PeopleModel.PERSON_LIST_PATH, people);
1020     }
1021
1022     @Test
1023     public void testLeadershipTransferOnShutdown() throws Exception {
1024         // FIXME: remove when test passes also for ClientBackedDataStore
1025         assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1026
1027         leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
1028         followerDatastoreContextBuilder.shardElectionTimeoutFactor(10).customRaftPolicyImplementation(null);
1029         final String testName = "testLeadershipTransferOnShutdown";
1030         initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS_AND_PEOPLE);
1031
1032         final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1033                 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500),
1034                 commitTimeout);
1035         try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1036                 testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
1037
1038             followerTestKit.waitForMembersUp("member-3");
1039             follower2TestKit.waitForMembersUp("member-1", "member-2");
1040
1041             // Create and submit a couple tx's so they're pending.
1042
1043             DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
1044             writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1045             writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1046             writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
1047             final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
1048
1049             IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1050                 stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
1051
1052             writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
1053             final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
1054             writeTx.write(CarsModel.newCarPath("optima"), car);
1055             final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
1056
1057             IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1058                 stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
1059
1060             // Gracefully stop the leader via a Shutdown message.
1061
1062             sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1063                 .shardElectionTimeoutFactor(100));
1064
1065             final FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
1066             final Future<ActorRef> future = leaderDistributedDataStore.getActorUtils().findLocalShardAsync("cars");
1067             final ActorRef leaderActor = Await.result(future, duration);
1068
1069             final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);
1070
1071             // Commit the 2 transactions. They should finish and succeed.
1072
1073             followerTestKit.doCommit(cohort1);
1074             followerTestKit.doCommit(cohort2);
1075
1076             // Wait for the leader actor stopped.
1077
1078             final Boolean stopped = Await.result(stopFuture, duration);
1079             assertEquals("Stopped", Boolean.TRUE, stopped);
1080
1081             // Verify leadership was transferred by reading the committed data from the other nodes.
1082
1083             verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
1084             verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
1085         }
1086     }
1087
1088     @Test
1089     public void testTransactionWithIsolatedLeader() throws Exception {
1090         // FIXME: remove when test passes also for ClientBackedDataStore
1091         assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1092
1093         // Set the isolated leader check interval high so we can control the switch to IsolatedLeader.
1094         leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(10000000);
1095         final String testName = "testTransactionWithIsolatedLeader";
1096         initDatastoresWithCars(testName);
1097
1098         // Tx that is submitted after the follower is stopped but before the leader transitions to IsolatedLeader.
1099         final DOMStoreWriteTransaction preIsolatedLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1100         preIsolatedLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1101
1102         // Tx that is submitted after the leader transitions to IsolatedLeader.
1103         final DOMStoreWriteTransaction noShardLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1104         noShardLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1105
1106         // Tx that is submitted after the follower is reinstated.
1107         final DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1108         successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1109
1110         // Stop the follower
1111         followerTestKit.watch(followerDistributedDataStore.getActorUtils().getShardManager());
1112         followerDistributedDataStore.close();
1113         followerTestKit.expectTerminated(followerDistributedDataStore.getActorUtils().getShardManager());
1114
1115         // Submit the preIsolatedLeaderWriteTx so it's pending
1116         final DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
1117
1118         // Change the isolated leader check interval low so it changes to IsolatedLeader.
1119         sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1120                 .shardIsolatedLeaderCheckIntervalInMillis(200));
1121
1122         MemberNode.verifyRaftState(leaderDistributedDataStore, "cars",
1123             raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
1124
1125         final var ex = assertThrows(ExecutionException.class,
1126             () -> leaderTestKit.doCommit(noShardLeaderWriteTx.ready()));
1127         assertEquals(NoShardLeaderException.class, Throwables.getRootCause(ex).getClass());
1128
1129         sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1130                 .shardElectionTimeoutFactor(100));
1131
1132         final DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
1133
1134         followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
1135                 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
1136
1137         leaderTestKit.doCommit(preIsolatedLeaderTxCohort);
1138         leaderTestKit.doCommit(successTxCohort);
1139     }
1140
1141     @Test
1142     public void testTransactionWithShardLeaderNotResponding() throws Exception {
1143         followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1144         followerDatastoreContextBuilder.shardElectionTimeoutFactor(50);
1145         initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
1146
1147         // Do an initial read to get the primary shard info cached.
1148
1149         final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1150         readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1151
1152         // Shutdown the leader and try to create a new tx.
1153
1154         TestKit.shutdownActorSystem(leaderSystem, true);
1155
1156         followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
1157         sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
1158
1159         final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1160
1161         rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1162
1163         final var ex = assertThrows(ExecutionException.class, () -> followerTestKit.doCommit(rwTx.ready()));
1164         final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause());
1165         if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
1166             assertTrue(msg, Throwables.getRootCause(ex) instanceof NoShardLeaderException
1167                 || ex.getCause() instanceof ShardLeaderNotRespondingException);
1168         } else {
1169             assertThat(msg, Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
1170         }
1171     }
1172
1173     @Test
1174     public void testTransactionWithCreateTxFailureDueToNoLeader() throws Exception {
1175         followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1176         initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
1177
1178         // Do an initial read to get the primary shard info cached.
1179
1180         final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1181         readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1182
1183         // Shutdown the leader and try to create a new tx.
1184
1185         TestKit.shutdownActorSystem(leaderSystem, true);
1186
1187         Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1188
1189         Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
1190
1191         sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1192                 .operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1193
1194         final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1195
1196         rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1197
1198         final var ex = assertThrows(ExecutionException.class, () -> followerTestKit.doCommit(rwTx.ready()));
1199         final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause());
1200         if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
1201             assertThat(msg, Throwables.getRootCause(ex), instanceOf(NoShardLeaderException.class));
1202         } else {
1203             assertThat(msg, Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
1204         }
1205     }
1206
1207     @Test
1208     public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
1209         followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
1210         String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
1211         initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1212
1213         final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1214                 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1215         final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1216                 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1217
1218         try (AbstractDataStore ds =
1219                 follower2TestKit.setupAbstractDataStore(
1220                         testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS)) {
1221
1222             followerTestKit.waitForMembersUp("member-1", "member-3");
1223             follower2TestKit.waitForMembersUp("member-1", "member-2");
1224
1225             // Do an initial read to get the primary shard info cached.
1226
1227             final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1228             readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1229
1230             // Shutdown the leader and try to create a new tx.
1231
1232             TestKit.shutdownActorSystem(leaderSystem, true);
1233
1234             Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1235
1236             sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1237                 .operationTimeoutInMillis(500).shardElectionTimeoutFactor(5).customRaftPolicyImplementation(null));
1238
1239             final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1240
1241             rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1242
1243             followerTestKit.doCommit(rwTx.ready());
1244         }
1245     }
1246
1247     @Test
1248     public void testSemiReachableCandidateNotDroppingLeader() throws Exception {
1249         final String testName = "testSemiReachableCandidateNotDroppingLeader";
1250         initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1251
1252         final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1253                 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1254         final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1255                 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1256
1257         final AbstractDataStore ds2 =
1258                      follower2TestKit.setupAbstractDataStore(
1259                              testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS);
1260
1261         followerTestKit.waitForMembersUp("member-1", "member-3");
1262         follower2TestKit.waitForMembersUp("member-1", "member-2");
1263
1264         TestKit.shutdownActorSystem(follower2System);
1265
1266         ActorRef cars = leaderDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1267         OnDemandRaftState initialState = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1268                 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1269
1270         Cluster leaderCluster = Cluster.get(leaderSystem);
1271         Cluster followerCluster = Cluster.get(followerSystem);
1272         Cluster follower2Cluster = Cluster.get(follower2System);
1273
1274         Member follower2Member = follower2Cluster.readView().self();
1275
1276         await().atMost(10, TimeUnit.SECONDS)
1277                 .until(() -> containsUnreachable(leaderCluster, follower2Member));
1278         await().atMost(10, TimeUnit.SECONDS)
1279                 .until(() -> containsUnreachable(followerCluster, follower2Member));
1280
1281         ActorRef followerCars = followerDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1282
1283         // to simulate a follower not being able to receive messages, but still being able to send messages and becoming
1284         // candidate, we can just send a couple of RequestVotes to both leader and follower.
1285         cars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1286         followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1287         cars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1288         followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1289
1290         OnDemandRaftState stateAfter = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1291                 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1292         OnDemandRaftState followerState = (OnDemandRaftState) followerDistributedDataStore.getActorUtils()
1293                 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1294
1295         assertEquals(initialState.getCurrentTerm(), stateAfter.getCurrentTerm());
1296         assertEquals(initialState.getCurrentTerm(), followerState.getCurrentTerm());
1297
1298         ds2.close();
1299     }
1300
1301     private static Boolean containsUnreachable(final Cluster cluster, final Member member) {
1302         // unreachableMembers() returns scala.collection.immutable.Set, but we are using scala.collection.Set to fix JDT
1303         // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=468276#c32
1304         final Set<Member> members = cluster.readView().unreachableMembers();
1305         return members.contains(member);
1306     }
1307
1308     @Test
1309     public void testInstallSnapshot() throws Exception {
1310         final String testName = "testInstallSnapshot";
1311         final String leaderCarShardName = "member-1-shard-cars-" + testName;
1312         final String followerCarShardName = "member-2-shard-cars-" + testName;
1313
1314         // Setup a saved snapshot on the leader. The follower will startup with no data and the leader should
1315         // install a snapshot to sync the follower.
1316
1317         DataTree tree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_CONFIGURATION,
1318             SchemaContextHelper.full());
1319
1320         final ContainerNode carsNode = CarsModel.newCarsNode(
1321                 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", Uint64.valueOf(20000))));
1322         AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
1323
1324         final NormalizedNode<?, ?> snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.empty());
1325         final Snapshot initialSnapshot = Snapshot.create(
1326                 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
1327                 Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
1328         InMemorySnapshotStore.addSnapshot(leaderCarShardName, initialSnapshot);
1329
1330         InMemorySnapshotStore.addSnapshotSavedLatch(leaderCarShardName);
1331         InMemorySnapshotStore.addSnapshotSavedLatch(followerCarShardName);
1332
1333         initDatastoresWithCars(testName);
1334
1335         assertEquals(Optional.of(carsNode), leaderDistributedDataStore.newReadOnlyTransaction().read(
1336             CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS));
1337
1338         verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(leaderCarShardName, Snapshot.class),
1339                 initialSnapshot, snapshotRoot);
1340
1341         verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(followerCarShardName, Snapshot.class),
1342                 initialSnapshot, snapshotRoot);
1343     }
1344
1345     @Test
1346     public void testReadWriteMessageSlicing() throws Exception {
1347         // The slicing is only implemented for tell-based protocol
1348         assumeTrue(ClientBackedDataStore.class.isAssignableFrom(testParameter));
1349
1350         leaderDatastoreContextBuilder.maximumMessageSliceSize(100);
1351         followerDatastoreContextBuilder.maximumMessageSliceSize(100);
1352         initDatastoresWithCars("testLargeReadReplySlicing");
1353
1354         final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1355
1356         final NormalizedNode<?, ?> carsNode = CarsModel.create();
1357         rwTx.write(CarsModel.BASE_PATH, carsNode);
1358
1359         verifyNode(rwTx, CarsModel.BASE_PATH, carsNode);
1360     }
1361
1362     @SuppressWarnings("IllegalCatch")
1363     @Test
1364     public void testRaftCallbackDuringLeadershipDrop() throws Exception {
1365         final String testName = "testRaftCallbackDuringLeadershipDrop";
1366         initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1367
1368         final ExecutorService executor = Executors.newSingleThreadExecutor();
1369
1370         final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1371                 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500)
1372                         .shardLeaderElectionTimeoutInSeconds(3600),
1373                 commitTimeout);
1374
1375         final DOMStoreWriteTransaction initialWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1376         initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1377         leaderTestKit.doCommit(initialWriteTx.ready());
1378
1379         try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1380                 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false)) {
1381
1382             final ActorRef member3Cars = ((LocalShardStore) follower2DistributedDataStore).getLocalShards()
1383                     .getLocalShards().get("cars").getActor();
1384             final ActorRef member2Cars = ((LocalShardStore)followerDistributedDataStore).getLocalShards()
1385                     .getLocalShards().get("cars").getActor();
1386             member2Cars.tell(new StartDropMessages(AppendEntries.class), null);
1387             member3Cars.tell(new StartDropMessages(AppendEntries.class), null);
1388
1389             final DOMStoreWriteTransaction newTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1390             newTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1391             final AtomicBoolean submitDone = new AtomicBoolean(false);
1392             executor.submit(() -> {
1393                 try {
1394                     leaderTestKit.doCommit(newTx.ready());
1395                     submitDone.set(true);
1396                 } catch (Exception e) {
1397                     throw new RuntimeException(e);
1398                 }
1399             });
1400             final ActorRef leaderCars = ((LocalShardStore) leaderDistributedDataStore).getLocalShards()
1401                     .getLocalShards().get("cars").getActor();
1402             await().atMost(10, TimeUnit.SECONDS)
1403                     .until(() -> ((OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1404                             .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE)).getLastIndex() >= 1);
1405
1406             final OnDemandRaftState raftState = (OnDemandRaftState)leaderDistributedDataStore.getActorUtils()
1407                     .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE);
1408
1409             // Simulate a follower not receiving heartbeats but still being able to send messages ie RequestVote with
1410             // new term(switching to candidate after election timeout)
1411             leaderCars.tell(new RequestVote(raftState.getCurrentTerm() + 1,
1412                     "member-3-shard-cars-testRaftCallbackDuringLeadershipDrop", -1,
1413                             -1), member3Cars);
1414
1415             member2Cars.tell(new StopDropMessages(AppendEntries.class), null);
1416             member3Cars.tell(new StopDropMessages(AppendEntries.class), null);
1417
1418             await("Is tx stuck in COMMIT_PENDING")
1419                     .atMost(10, TimeUnit.SECONDS).untilAtomic(submitDone, equalTo(true));
1420
1421         }
1422
1423         executor.shutdownNow();
1424     }
1425
1426     @Test
1427     public void testSnapshotOnRootOverwrite() throws Exception {
1428         // FIXME: ClientBackedDatastore does not have stable indexes/term, the snapshot index seems to fluctuate
1429         assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1430
1431         final String testName = "testSnapshotOnRootOverwrite";
1432         final String[] shards = {"cars", "default"};
1433         initDatastores(testName, "module-shards-default-cars-member1-and-2.conf", shards,
1434                 leaderDatastoreContextBuilder.snapshotOnRootOverwrite(true),
1435                 followerDatastoreContextBuilder.snapshotOnRootOverwrite(true));
1436
1437         leaderTestKit.waitForMembersUp("member-2");
1438         final ContainerNode rootNode = ImmutableContainerNodeBuilder.create()
1439                 .withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(SchemaContext.NAME))
1440                 .withChild((ContainerNode) CarsModel.create())
1441                 .build();
1442
1443         leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1444
1445         IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1446             state -> assertEquals(1, state.getSnapshotIndex()));
1447
1448         IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1449             state -> assertEquals(1, state.getSnapshotIndex()));
1450
1451         verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1452         verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1453
1454         for (int i = 0; i < 10; i++) {
1455             leaderTestKit.testWriteTransaction(leaderDistributedDataStore, CarsModel.newCarPath("car " + i),
1456                     CarsModel.newCarEntry("car " + i, Uint64.ONE));
1457         }
1458
1459         // fake snapshot causes the snapshotIndex to move
1460         IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1461             state -> assertEquals(10, state.getSnapshotIndex()));
1462         IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1463             state -> assertEquals(10, state.getSnapshotIndex()));
1464
1465         // however the real snapshot still has not changed and was taken at index 1
1466         verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1467         verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1468
1469         // root overwrite so expect a snapshot
1470         leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1471
1472         // this was a real snapshot so everything should be in it(1(DisableTrackingPayload) + 1 + 10 + 1)
1473         IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1474             state -> assertEquals(12, state.getSnapshotIndex()));
1475         IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1476             state -> assertEquals(12, state.getSnapshotIndex()));
1477
1478         verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 12);
1479         verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 12);
1480     }
1481
1482     private void verifySnapshot(final String persistenceId, final long lastAppliedIndex) {
1483         await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
1484                 List<Snapshot> snap = InMemorySnapshotStore.getSnapshots(persistenceId, Snapshot.class);
1485                 assertEquals(1, snap.size());
1486                 assertEquals(lastAppliedIndex, snap.get(0).getLastAppliedIndex());
1487             }
1488         );
1489     }
1490
1491     private static void verifySnapshot(final Snapshot actual, final Snapshot expected,
1492                                        final NormalizedNode<?, ?> expRoot) {
1493         assertEquals("Snapshot getLastAppliedTerm", expected.getLastAppliedTerm(), actual.getLastAppliedTerm());
1494         assertEquals("Snapshot getLastAppliedIndex", expected.getLastAppliedIndex(), actual.getLastAppliedIndex());
1495         assertEquals("Snapshot getLastTerm", expected.getLastTerm(), actual.getLastTerm());
1496         assertEquals("Snapshot getLastIndex", expected.getLastIndex(), actual.getLastIndex());
1497         assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
1498         MetadataShardDataTreeSnapshot shardSnapshot =
1499                 (MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
1500         assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
1501     }
1502
1503     private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1504         final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1505         final DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
1506         final Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1507         doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1508         doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(anyString());
1509         dataStore.onDatastoreContextUpdated(mockContextFactory);
1510     }
1511 }