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