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