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