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