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