2 * Copyright (c) 2015, 2017 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.datastore;
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;
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.MapNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
119 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
120 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
121 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
122 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
123 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
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;
133 * End-to-end distributed data store tests that exercise remote shards and transactions.
135 * @author Thomas Pantelis
137 @RunWith(Parameterized.class)
138 public class DistributedDataStoreRemotingIntegrationTest extends AbstractTest {
140 @Parameters(name = "{0}")
141 public static Collection<Object[]> data() {
142 return Arrays.asList(new Object[][] {
143 { TestDistributedDataStore.class, 7}, { TestClientBackedDataStore.class, 12 }
148 public Class<? extends AbstractDataStore> testParameter;
150 public int commitTimeout;
152 private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
153 private static final String[] CARS = {"cars"};
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");
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";
165 private ActorSystem leaderSystem;
166 private ActorSystem followerSystem;
167 private ActorSystem follower2System;
169 private final DatastoreContext.Builder leaderDatastoreContextBuilder =
170 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
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();
178 private AbstractDataStore followerDistributedDataStore;
179 private AbstractDataStore leaderDistributedDataStore;
180 private IntegrationTestKit followerTestKit;
181 private IntegrationTestKit leaderTestKit;
184 public void setUp() {
185 InMemoryJournal.clear();
186 InMemorySnapshotStore.clear();
188 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
189 Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
191 followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
192 Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
194 follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
195 Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
199 public void tearDown() {
200 if (followerDistributedDataStore != null) {
201 leaderDistributedDataStore.close();
203 if (leaderDistributedDataStore != null) {
204 leaderDistributedDataStore.close();
207 TestKit.shutdownActorSystem(leaderSystem, true);
208 TestKit.shutdownActorSystem(followerSystem, true);
209 TestKit.shutdownActorSystem(follower2System,true);
211 InMemoryJournal.clear();
212 InMemorySnapshotStore.clear();
215 private void initDatastoresWithCars(final String type) throws Exception {
216 initDatastores(type, MODULE_SHARDS_CARS_ONLY_1_2, CARS);
219 private void initDatastoresWithCarsAndPeople(final String type) throws Exception {
220 initDatastores(type, MODULE_SHARDS_CARS_PEOPLE_1_2, CARS_AND_PEOPLE);
223 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards)
225 initDatastores(type, moduleShardsConfig, shards, leaderDatastoreContextBuilder,
226 followerDatastoreContextBuilder);
229 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards,
230 final DatastoreContext.Builder leaderBuilder, final DatastoreContext.Builder followerBuilder)
232 leaderTestKit = new IntegrationTestKit(leaderSystem, leaderBuilder, commitTimeout);
234 leaderDistributedDataStore = leaderTestKit.setupAbstractDataStore(
235 testParameter, type, moduleShardsConfig, false, shards);
237 followerTestKit = new IntegrationTestKit(followerSystem, followerBuilder, commitTimeout);
238 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
239 testParameter, type, moduleShardsConfig, false, shards);
241 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorUtils(), shards);
243 leaderTestKit.waitForMembersUp("member-2");
244 followerTestKit.waitForMembersUp("member-1");
247 private static void verifyCars(final DOMStoreReadTransaction readTx, final MapEntryNode... entries)
249 final Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
250 assertTrue("isPresent", optional.isPresent());
252 final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(
253 CarsModel.CAR_QNAME);
254 for (final NormalizedNode<?, ?> entry: entries) {
255 listBuilder.withChild((MapEntryNode) entry);
258 assertEquals("Car list node", listBuilder.build(), optional.get());
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));
266 private static void verifyExists(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path)
268 assertEquals("exists", Boolean.TRUE, readTx.exists(path).get(5, TimeUnit.SECONDS));
272 public void testWriteTransactionWithSingleShard() throws Exception {
273 final String testName = "testWriteTransactionWithSingleShard";
274 initDatastoresWithCars(testName);
276 final String followerCarShardName = "member-2-shard-cars-" + testName;
278 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
279 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
281 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
282 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
284 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
285 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
286 writeTx.merge(car1Path, car1);
288 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
289 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
290 writeTx.merge(car2Path, car2);
292 followerTestKit.doCommit(writeTx.ready());
294 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
296 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
300 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
302 writeTx.delete(car1Path);
304 followerTestKit.doCommit(writeTx.ready());
306 verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
308 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
310 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
312 // Re-instate the follower member 2 as a single-node to verify replication and recovery.
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()));
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;
330 final List<ApplyJournalEntries> entries = InMemoryJournal.get(followerCarShardName,
331 ApplyJournalEntries.class);
332 for (ApplyJournalEntries aje: entries) {
333 if (aje.getToIndex() >= leaderLastAppliedIndex.get()) {
339 assertTrue("Follower did not persist ApplyJournalEntries containing leader's lastAppliedIndex "
340 + leaderLastAppliedIndex + ". Entries persisted: " + entries, sw.elapsed(TimeUnit.SECONDS) <= 5);
342 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
345 TestKit.shutdownActorSystem(leaderSystem, true);
346 TestKit.shutdownActorSystem(followerSystem, true);
348 final ActorSystem newSystem = newActorSystem("reinstated-member2", "Member2");
350 try (AbstractDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder,
352 .setupAbstractDataStore(testParameter, testName, "module-shards-member2", true, CARS)) {
353 verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
358 public void testSingleTransactionsWritesInQuickSuccession() throws Exception {
359 initDatastoresWithCars("testSingleTransactionsWritesInQuickSuccession");
361 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
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());
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());
374 try (var tx = txChain.newReadOnlyTransaction()) {
375 tx.read(CarsModel.BASE_PATH).get();
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")
385 final var frontendMetadata =
386 (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
387 .executeOperation(localShard, new RequestFrontendMetadata());
389 final var clientMeta = frontendMetadata.getClients().get(0);
390 if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
391 assertTellClientMetadata(clientMeta, numCars * 2);
393 assertAskClientMetadata(clientMeta);
397 try (var tx = txChain.newReadOnlyTransaction()) {
398 final var body = tx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS).orElseThrow().getValue();
399 assertThat(body, instanceOf(Collection.class));
400 assertEquals(numCars, ((Collection<?>) body).size());
404 private void assertAskClientMetadata(final FrontendClientMetadata clientMeta) {
405 // ask based should track no metadata
406 assertEquals(List.of(), clientMeta.getCurrentHistories());
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();
416 // FIXME: CONTROLLER-1991: remove this assumption
419 assertEquals(UnsignedLongBitmap.of(), metadata.getClosedTransactions());
420 assertEquals("[[0.." + lastPurged + "]]", metadata.getPurgedTransactions().ranges().toString());
424 public void testCloseTransactionMetadataLeak() throws Exception {
425 // FIXME: Ask-based frontend seems to have some issues with back to back close
426 assumeTrue(testParameter.isAssignableFrom(TestClientBackedDataStore.class));
428 initDatastoresWithCars("testCloseTransactionMetadataLeak");
430 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
432 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
433 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
434 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
435 followerTestKit.doCommit(writeTx.ready());
438 for (int i = 0; i < numCars; i++) {
439 writeTx = txChain.newWriteOnlyTransaction();
442 try (var tx = txChain.newReadOnlyTransaction()) {
443 tx.read(CarsModel.BASE_PATH).get();
447 writeTx = txChain.newWriteOnlyTransaction();
448 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
449 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
450 followerTestKit.doCommit(writeTx.ready());
452 // wait to let the shard catch up with purged
453 await("Close transaction purge leak test.").atMost(5, TimeUnit.SECONDS)
454 .pollInterval(500, TimeUnit.MILLISECONDS)
455 .untilAsserted(() -> {
456 final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars")
458 final var frontendMetadata =
459 (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
460 .executeOperation(localShard, new RequestFrontendMetadata());
462 final var clientMeta = frontendMetadata.getClients().get(0);
463 if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
464 assertTellClientMetadata(clientMeta, numCars * 2 + 1);
466 assertAskClientMetadata(clientMeta);
470 try (var tx = txChain.newReadOnlyTransaction()) {
471 final var body = tx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS).orElseThrow().getValue();
472 assertThat(body, instanceOf(Collection.class));
473 assertEquals(numCars, ((Collection<?>) body).size());
478 public void testReadWriteTransactionWithSingleShard() throws Exception {
479 initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
481 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
482 assertNotNull("newReadWriteTransaction returned null", rwTx);
484 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
485 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
487 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
488 rwTx.merge(CarsModel.newCarPath("optima"), car1);
490 verifyCars(rwTx, car1);
492 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
493 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
494 rwTx.merge(car2Path, car2);
496 verifyExists(rwTx, car2Path);
498 followerTestKit.doCommit(rwTx.ready());
500 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
504 public void testWriteTransactionWithMultipleShards() throws Exception {
505 initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
507 final DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
508 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
510 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
511 final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
512 writeTx.write(carsPath, carsNode);
514 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
515 final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
516 writeTx.write(peoplePath, peopleNode);
518 followerTestKit.doCommit(writeTx.ready());
520 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
522 verifyNode(readTx, carsPath, carsNode);
523 verifyNode(readTx, peoplePath, peopleNode);
527 public void testReadWriteTransactionWithMultipleShards() throws Exception {
528 initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
530 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
531 assertNotNull("newReadWriteTransaction returned null", rwTx);
533 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
534 final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
535 rwTx.write(carsPath, carsNode);
537 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
538 final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
539 rwTx.write(peoplePath, peopleNode);
541 followerTestKit.doCommit(rwTx.ready());
543 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
545 verifyNode(readTx, carsPath, carsNode);
546 verifyNode(readTx, peoplePath, peopleNode);
550 public void testTransactionChainWithSingleShard() throws Exception {
551 initDatastoresWithCars("testTransactionChainWithSingleShard");
553 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
555 // Add the top-level cars container with write-only.
557 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
558 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
560 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
562 final DOMStoreThreePhaseCommitCohort writeTxReady = writeTx.ready();
564 // Verify the top-level cars container with read-only.
566 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
568 // Perform car operations with read-write.
570 final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
572 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
574 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
576 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
577 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
578 rwTx.write(car1Path, car1);
580 verifyExists(rwTx, car1Path);
582 verifyCars(rwTx, car1);
584 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
585 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
587 rwTx.delete(car1Path);
589 followerTestKit.doCommit(writeTxReady);
591 followerTestKit.doCommit(rwTx.ready());
595 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
599 public void testTransactionChainWithMultipleShards() throws Exception {
600 initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
602 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
604 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
605 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
607 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
608 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
610 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
611 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
613 followerTestKit.doCommit(writeTx.ready());
615 final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
617 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
618 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
619 readWriteTx.write(carPath, car);
621 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
622 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
623 readWriteTx.merge(personPath, person);
625 assertEquals(Optional.of(car), readWriteTx.read(carPath).get(5, TimeUnit.SECONDS));
626 assertEquals(Optional.of(person), readWriteTx.read(personPath).get(5, TimeUnit.SECONDS));
628 final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
630 writeTx = txChain.newWriteOnlyTransaction();
632 writeTx.delete(personPath);
634 final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
636 followerTestKit.doCommit(cohort2);
637 followerTestKit.doCommit(cohort3);
641 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
642 verifyCars(readTx, car);
644 assertEquals(Optional.empty(), readTx.read(personPath).get(5, TimeUnit.SECONDS));
648 public void testChainedTransactionFailureWithSingleShard() throws Exception {
649 initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
651 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
652 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
653 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
654 MoreExecutors.directExecutor());
656 final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
657 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
659 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
661 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
662 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
663 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
665 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
667 final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
669 assertThat(ex, instanceOf(TransactionCommitFailedException.class));
671 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
678 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
679 initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
681 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
682 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
683 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
684 MoreExecutors.directExecutor());
686 final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
687 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
689 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
691 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
693 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
694 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
695 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
697 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
698 // done for put for performance reasons.
699 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
701 final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
703 assertThat(ex, instanceOf(TransactionCommitFailedException.class));
705 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
712 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
713 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
714 final String testName = "testSingleShardTransactionsWithLeaderChanges";
715 initDatastoresWithCars(testName);
717 final String followerCarShardName = "member-2-shard-cars-" + testName;
718 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class);
720 // Write top-level car container from the follower so it uses a remote Tx.
722 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
724 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
725 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
727 followerTestKit.doCommit(writeTx.ready());
729 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
731 // Switch the leader to the follower
733 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
734 .shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
736 TestKit.shutdownActorSystem(leaderSystem, true);
737 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
739 followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorUtils(), CARS);
741 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
742 Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
744 final DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder()
745 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
746 IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder, commitTimeout);
748 try (AbstractDataStore ds =
749 newMember1TestKit.setupAbstractDataStore(
750 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS)) {
752 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), CARS);
754 // Write a car entry to the new leader - should switch to local Tx
756 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
758 MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
759 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
760 writeTx.merge(car1Path, car1);
762 followerTestKit.doCommit(writeTx.ready());
764 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
768 @SuppressWarnings("unchecked")
770 public void testReadyLocalTransactionForwardedToLeader() throws Exception {
771 initDatastoresWithCars("testReadyLocalTransactionForwardedToLeader");
772 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
774 final Optional<ActorRef> carsFollowerShard =
775 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
776 assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
778 final DataTree dataTree = new InMemoryDataTreeFactory().create(
779 DataTreeConfiguration.DEFAULT_OPERATIONAL, SchemaContextHelper.full());
781 // Send a tx with immediate commit.
783 DataTreeModification modification = dataTree.takeSnapshot().newModification();
784 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
785 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
787 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
788 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
789 modification.ready();
791 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(tx1 , modification, true, Optional.empty());
793 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
794 Object resp = followerTestKit.expectMsgClass(Object.class);
795 if (resp instanceof akka.actor.Status.Failure) {
796 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
799 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
801 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
803 // Send another tx without immediate commit.
805 modification = dataTree.takeSnapshot().newModification();
806 MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
807 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
808 modification.ready();
810 readyLocal = new ReadyLocalTransaction(tx2 , modification, false, Optional.empty());
812 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
813 resp = followerTestKit.expectMsgClass(Object.class);
814 if (resp instanceof akka.actor.Status.Failure) {
815 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
818 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
820 final ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
821 ((ReadyTransactionReply)resp).getCohortPath());
823 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(leaderDistributedDataStore.getActorUtils(),
824 List.of(new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor),
825 () -> DataStoreVersions.CURRENT_VERSION)), tx2);
826 cohort.canCommit().get(5, TimeUnit.SECONDS);
827 cohort.preCommit().get(5, TimeUnit.SECONDS);
828 cohort.commit().get(5, TimeUnit.SECONDS);
830 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
833 @SuppressWarnings("unchecked")
835 public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
836 initDatastoresWithCars("testForwardedReadyTransactionForwardedToLeader");
837 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
839 final Optional<ActorRef> carsFollowerShard =
840 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
841 assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
843 carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
844 final DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
846 // Send a tx with immediate commit.
848 DataTreeModification modification = dataTree.takeSnapshot().newModification();
849 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
850 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
852 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
853 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
855 ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction(tx1, DataStoreVersions.CURRENT_VERSION,
856 new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx1, modification),
857 true, Optional.empty());
859 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
860 Object resp = followerTestKit.expectMsgClass(Object.class);
861 if (resp instanceof akka.actor.Status.Failure) {
862 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
865 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
867 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
869 // Send another tx without immediate commit.
871 modification = dataTree.takeSnapshot().newModification();
872 MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
873 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
875 forwardedReady = new ForwardedReadyTransaction(tx2, DataStoreVersions.CURRENT_VERSION,
876 new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx2, modification),
877 false, Optional.empty());
879 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
880 resp = followerTestKit.expectMsgClass(Object.class);
881 if (resp instanceof akka.actor.Status.Failure) {
882 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
885 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
887 ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
888 ((ReadyTransactionReply)resp).getCohortPath());
890 final ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
891 leaderDistributedDataStore.getActorUtils(), List.of(
892 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor),
893 () -> DataStoreVersions.CURRENT_VERSION)), tx2);
894 cohort.canCommit().get(5, TimeUnit.SECONDS);
895 cohort.preCommit().get(5, TimeUnit.SECONDS);
896 cohort.commit().get(5, TimeUnit.SECONDS);
898 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
902 public void testTransactionForwardedToLeaderAfterRetry() throws Exception {
903 followerDatastoreContextBuilder.shardBatchedModificationCount(2);
904 leaderDatastoreContextBuilder.shardBatchedModificationCount(2);
905 initDatastoresWithCarsAndPeople("testTransactionForwardedToLeaderAfterRetry");
907 // Do an initial write to get the primary shard info cached.
909 final DOMStoreWriteTransaction initialWriteTx = followerDistributedDataStore.newWriteOnlyTransaction();
910 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
911 initialWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
912 followerTestKit.doCommit(initialWriteTx.ready());
914 // Wait for the commit to be replicated to the follower.
916 MemberNode.verifyRaftState(followerDistributedDataStore, "cars",
917 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
919 MemberNode.verifyRaftState(followerDistributedDataStore, "people",
920 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
922 // Prepare, ready and canCommit a WO tx that writes to 2 shards. This will become the current tx in
925 final DOMStoreWriteTransaction writeTx1 = followerDistributedDataStore.newWriteOnlyTransaction();
926 writeTx1.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
927 writeTx1.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
928 final DOMStoreThreePhaseCommitCohort writeTx1Cohort = writeTx1.ready();
929 final ListenableFuture<Boolean> writeTx1CanCommit = writeTx1Cohort.canCommit();
930 writeTx1CanCommit.get(5, TimeUnit.SECONDS);
932 // Prepare and ready another WO tx that writes to 2 shards but don't canCommit yet. This will be queued
933 // in the leader shard.
935 final DOMStoreWriteTransaction writeTx2 = followerDistributedDataStore.newWriteOnlyTransaction();
936 final LinkedList<MapEntryNode> cars = new LinkedList<>();
938 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
939 writeTx2.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
941 NormalizedNode<?, ?> people = ImmutableNodes.mapNodeBuilder(PeopleModel.PERSON_QNAME)
942 .withChild(PeopleModel.newPersonEntry("Dude")).build();
943 writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
944 final DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
946 // Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
947 // tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
948 // leader shard (with shardBatchedModificationCount set to 2). The 3rd BatchedModidifications will be
951 final DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
952 for (int i = 1; i <= 5; i++, carIndex++) {
953 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
954 writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
957 // Prepare another WO that writes to a single shard. This will send a single BatchedModidifications
960 final DOMStoreWriteTransaction writeTx4 = followerDistributedDataStore.newWriteOnlyTransaction();
961 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
962 writeTx4.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
965 // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaciton message to the
966 // leader shard on ready.
968 final DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
969 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
970 readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
972 // FIXME: CONTROLLER-2017: ClientBackedDataStore reports only 4 transactions
973 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
974 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
975 stats -> assertEquals("getReadWriteTransactionCount", 5, stats.getReadWriteTransactionCount()));
977 // Disable elections on the leader so it switches to follower.
979 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
980 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
981 .shardElectionTimeoutFactor(10));
983 leaderTestKit.waitUntilNoLeader(leaderDistributedDataStore.getActorUtils(), "cars");
985 // Submit all tx's - the messages should get queued for retry.
987 final ListenableFuture<Boolean> writeTx2CanCommit = writeTx2Cohort.canCommit();
988 final DOMStoreThreePhaseCommitCohort writeTx3Cohort = writeTx3.ready();
989 final DOMStoreThreePhaseCommitCohort writeTx4Cohort = writeTx4.ready();
990 final DOMStoreThreePhaseCommitCohort rwTxCohort = readWriteTx.ready();
992 // Enable elections on the other follower so it becomes the leader, at which point the
993 // tx's should get forwarded from the previous leader to the new leader to complete the commits.
995 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
996 .customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
997 IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorUtils(), "cars")
998 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
999 IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorUtils(), "people")
1000 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
1002 followerTestKit.doCommit(writeTx1CanCommit, writeTx1Cohort);
1003 followerTestKit.doCommit(writeTx2CanCommit, writeTx2Cohort);
1004 followerTestKit.doCommit(writeTx3Cohort);
1005 followerTestKit.doCommit(writeTx4Cohort);
1006 followerTestKit.doCommit(rwTxCohort);
1008 DOMStoreReadTransaction readTx = leaderDistributedDataStore.newReadOnlyTransaction();
1009 verifyCars(readTx, cars.toArray(new MapEntryNode[cars.size()]));
1010 verifyNode(readTx, PeopleModel.PERSON_LIST_PATH, people);
1014 public void testLeadershipTransferOnShutdown() throws Exception {
1015 // FIXME: remove when test passes also for ClientBackedDataStore
1016 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1018 leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
1019 followerDatastoreContextBuilder.shardElectionTimeoutFactor(10).customRaftPolicyImplementation(null);
1020 final String testName = "testLeadershipTransferOnShutdown";
1021 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS_AND_PEOPLE);
1023 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1024 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500),
1026 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1027 testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
1029 followerTestKit.waitForMembersUp("member-3");
1030 follower2TestKit.waitForMembersUp("member-1", "member-2");
1032 // Create and submit a couple tx's so they're pending.
1034 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
1035 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1036 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1037 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
1038 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
1040 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1041 stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
1043 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
1044 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
1045 writeTx.write(CarsModel.newCarPath("optima"), car);
1046 final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
1048 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1049 stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
1051 // Gracefully stop the leader via a Shutdown message.
1053 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1054 .shardElectionTimeoutFactor(100));
1056 final FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
1057 final Future<ActorRef> future = leaderDistributedDataStore.getActorUtils().findLocalShardAsync("cars");
1058 final ActorRef leaderActor = Await.result(future, duration);
1060 final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);
1062 // Commit the 2 transactions. They should finish and succeed.
1064 followerTestKit.doCommit(cohort1);
1065 followerTestKit.doCommit(cohort2);
1067 // Wait for the leader actor stopped.
1069 final Boolean stopped = Await.result(stopFuture, duration);
1070 assertEquals("Stopped", Boolean.TRUE, stopped);
1072 // Verify leadership was transferred by reading the committed data from the other nodes.
1074 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
1075 verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
1080 public void testTransactionWithIsolatedLeader() throws Exception {
1081 // FIXME: remove when test passes also for ClientBackedDataStore
1082 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1084 // Set the isolated leader check interval high so we can control the switch to IsolatedLeader.
1085 leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(10000000);
1086 final String testName = "testTransactionWithIsolatedLeader";
1087 initDatastoresWithCars(testName);
1089 // Tx that is submitted after the follower is stopped but before the leader transitions to IsolatedLeader.
1090 final DOMStoreWriteTransaction preIsolatedLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1091 preIsolatedLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1093 // Tx that is submitted after the leader transitions to IsolatedLeader.
1094 final DOMStoreWriteTransaction noShardLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1095 noShardLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1097 // Tx that is submitted after the follower is reinstated.
1098 final DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1099 successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1101 // Stop the follower
1102 followerTestKit.watch(followerDistributedDataStore.getActorUtils().getShardManager());
1103 followerDistributedDataStore.close();
1104 followerTestKit.expectTerminated(followerDistributedDataStore.getActorUtils().getShardManager());
1106 // Submit the preIsolatedLeaderWriteTx so it's pending
1107 final DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
1109 // Change the isolated leader check interval low so it changes to IsolatedLeader.
1110 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1111 .shardIsolatedLeaderCheckIntervalInMillis(200));
1113 MemberNode.verifyRaftState(leaderDistributedDataStore, "cars",
1114 raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
1116 final var ex = assertThrows(ExecutionException.class,
1117 () -> leaderTestKit.doCommit(noShardLeaderWriteTx.ready()));
1118 assertEquals(NoShardLeaderException.class, Throwables.getRootCause(ex).getClass());
1120 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1121 .shardElectionTimeoutFactor(100));
1123 final DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
1125 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
1126 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
1128 leaderTestKit.doCommit(preIsolatedLeaderTxCohort);
1129 leaderTestKit.doCommit(successTxCohort);
1133 public void testTransactionWithShardLeaderNotResponding() throws Exception {
1134 followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1135 followerDatastoreContextBuilder.shardElectionTimeoutFactor(50);
1136 initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
1138 // Do an initial read to get the primary shard info cached.
1140 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1141 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1143 // Shutdown the leader and try to create a new tx.
1145 TestKit.shutdownActorSystem(leaderSystem, true);
1147 followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
1148 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
1150 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1152 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1154 final var ex = assertThrows(ExecutionException.class, () -> followerTestKit.doCommit(rwTx.ready()));
1155 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause());
1156 if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
1157 assertTrue(msg, Throwables.getRootCause(ex) instanceof NoShardLeaderException
1158 || ex.getCause() instanceof ShardLeaderNotRespondingException);
1160 assertThat(msg, Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
1165 public void testTransactionWithCreateTxFailureDueToNoLeader() throws Exception {
1166 followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1167 initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
1169 // Do an initial read to get the primary shard info cached.
1171 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1172 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1174 // Shutdown the leader and try to create a new tx.
1176 TestKit.shutdownActorSystem(leaderSystem, true);
1178 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1180 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
1182 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1183 .operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1185 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1187 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1189 final var ex = assertThrows(ExecutionException.class, () -> followerTestKit.doCommit(rwTx.ready()));
1190 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause());
1191 if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
1192 assertThat(msg, Throwables.getRootCause(ex), instanceOf(NoShardLeaderException.class));
1194 assertThat(msg, Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
1199 public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
1200 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
1201 String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
1202 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1204 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1205 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1206 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1207 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1209 try (AbstractDataStore ds =
1210 follower2TestKit.setupAbstractDataStore(
1211 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS)) {
1213 followerTestKit.waitForMembersUp("member-1", "member-3");
1214 follower2TestKit.waitForMembersUp("member-1", "member-2");
1216 // Do an initial read to get the primary shard info cached.
1218 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1219 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1221 // Shutdown the leader and try to create a new tx.
1223 TestKit.shutdownActorSystem(leaderSystem, true);
1225 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1227 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1228 .operationTimeoutInMillis(500).shardElectionTimeoutFactor(5).customRaftPolicyImplementation(null));
1230 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1232 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1234 followerTestKit.doCommit(rwTx.ready());
1239 public void testSemiReachableCandidateNotDroppingLeader() throws Exception {
1240 final String testName = "testSemiReachableCandidateNotDroppingLeader";
1241 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1243 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1244 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1245 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1246 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1248 final AbstractDataStore ds2 =
1249 follower2TestKit.setupAbstractDataStore(
1250 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS);
1252 followerTestKit.waitForMembersUp("member-1", "member-3");
1253 follower2TestKit.waitForMembersUp("member-1", "member-2");
1255 // behavior is controlled by akka.coordinated-shutdown.run-by-actor-system-terminate configuration option
1256 TestKit.shutdownActorSystem(follower2System, true);
1258 ActorRef cars = leaderDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1259 final OnDemandRaftState initialState = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1260 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1262 Cluster leaderCluster = Cluster.get(leaderSystem);
1263 Cluster followerCluster = Cluster.get(followerSystem);
1264 Cluster follower2Cluster = Cluster.get(follower2System);
1266 Member follower2Member = follower2Cluster.readView().self();
1268 await().atMost(10, TimeUnit.SECONDS)
1269 .until(() -> containsUnreachable(leaderCluster, follower2Member));
1270 await().atMost(10, TimeUnit.SECONDS)
1271 .until(() -> containsUnreachable(followerCluster, follower2Member));
1273 ActorRef followerCars = followerDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1275 // to simulate a follower not being able to receive messages, but still being able to send messages and becoming
1276 // candidate, we can just send a couple of RequestVotes to both leader and follower.
1277 cars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1278 followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1279 cars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1280 followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1282 OnDemandRaftState stateAfter = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1283 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1284 OnDemandRaftState followerState = (OnDemandRaftState) followerDistributedDataStore.getActorUtils()
1285 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1287 assertEquals(initialState.getCurrentTerm(), stateAfter.getCurrentTerm());
1288 assertEquals(initialState.getCurrentTerm(), followerState.getCurrentTerm());
1293 private static Boolean containsUnreachable(final Cluster cluster, final Member member) {
1294 // unreachableMembers() returns scala.collection.immutable.Set, but we are using scala.collection.Set to fix JDT
1295 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=468276#c32
1296 final Set<Member> members = cluster.readView().unreachableMembers();
1297 return members.contains(member);
1301 public void testInstallSnapshot() throws Exception {
1302 final String testName = "testInstallSnapshot";
1303 final String leaderCarShardName = "member-1-shard-cars-" + testName;
1304 final String followerCarShardName = "member-2-shard-cars-" + testName;
1306 // Setup a saved snapshot on the leader. The follower will startup with no data and the leader should
1307 // install a snapshot to sync the follower.
1309 DataTree tree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_CONFIGURATION,
1310 SchemaContextHelper.full());
1312 final ContainerNode carsNode = CarsModel.newCarsNode(
1313 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", Uint64.valueOf(20000))));
1314 AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
1316 final NormalizedNode<?, ?> snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.empty());
1317 final Snapshot initialSnapshot = Snapshot.create(
1318 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
1319 Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
1320 InMemorySnapshotStore.addSnapshot(leaderCarShardName, initialSnapshot);
1322 InMemorySnapshotStore.addSnapshotSavedLatch(leaderCarShardName);
1323 InMemorySnapshotStore.addSnapshotSavedLatch(followerCarShardName);
1325 initDatastoresWithCars(testName);
1327 assertEquals(Optional.of(carsNode), leaderDistributedDataStore.newReadOnlyTransaction().read(
1328 CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS));
1330 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(leaderCarShardName, Snapshot.class),
1331 initialSnapshot, snapshotRoot);
1333 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(followerCarShardName, Snapshot.class),
1334 initialSnapshot, snapshotRoot);
1338 public void testReadWriteMessageSlicing() throws Exception {
1339 // The slicing is only implemented for tell-based protocol
1340 assumeTrue(ClientBackedDataStore.class.isAssignableFrom(testParameter));
1342 leaderDatastoreContextBuilder.maximumMessageSliceSize(100);
1343 followerDatastoreContextBuilder.maximumMessageSliceSize(100);
1344 initDatastoresWithCars("testLargeReadReplySlicing");
1346 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1348 final NormalizedNode<?, ?> carsNode = CarsModel.create();
1349 rwTx.write(CarsModel.BASE_PATH, carsNode);
1351 verifyNode(rwTx, CarsModel.BASE_PATH, carsNode);
1354 @SuppressWarnings("IllegalCatch")
1356 public void testRaftCallbackDuringLeadershipDrop() throws Exception {
1357 final String testName = "testRaftCallbackDuringLeadershipDrop";
1358 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1360 final ExecutorService executor = Executors.newSingleThreadExecutor();
1362 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1363 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500)
1364 .shardLeaderElectionTimeoutInSeconds(3600),
1367 final DOMStoreWriteTransaction initialWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1368 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1369 leaderTestKit.doCommit(initialWriteTx.ready());
1371 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1372 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false)) {
1374 final ActorRef member3Cars = ((LocalShardStore) follower2DistributedDataStore).getLocalShards()
1375 .getLocalShards().get("cars").getActor();
1376 final ActorRef member2Cars = ((LocalShardStore)followerDistributedDataStore).getLocalShards()
1377 .getLocalShards().get("cars").getActor();
1378 member2Cars.tell(new StartDropMessages(AppendEntries.class), null);
1379 member3Cars.tell(new StartDropMessages(AppendEntries.class), null);
1381 final DOMStoreWriteTransaction newTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1382 newTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1383 final AtomicBoolean submitDone = new AtomicBoolean(false);
1384 executor.submit(() -> {
1386 leaderTestKit.doCommit(newTx.ready());
1387 submitDone.set(true);
1388 } catch (Exception e) {
1389 throw new RuntimeException(e);
1392 final ActorRef leaderCars = ((LocalShardStore) leaderDistributedDataStore).getLocalShards()
1393 .getLocalShards().get("cars").getActor();
1394 await().atMost(10, TimeUnit.SECONDS)
1395 .until(() -> ((OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1396 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE)).getLastIndex() >= 1);
1398 final OnDemandRaftState raftState = (OnDemandRaftState)leaderDistributedDataStore.getActorUtils()
1399 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE);
1401 // Simulate a follower not receiving heartbeats but still being able to send messages ie RequestVote with
1402 // new term(switching to candidate after election timeout)
1403 leaderCars.tell(new RequestVote(raftState.getCurrentTerm() + 1,
1404 "member-3-shard-cars-testRaftCallbackDuringLeadershipDrop", -1,
1407 member2Cars.tell(new StopDropMessages(AppendEntries.class), null);
1408 member3Cars.tell(new StopDropMessages(AppendEntries.class), null);
1410 await("Is tx stuck in COMMIT_PENDING")
1411 .atMost(10, TimeUnit.SECONDS).untilAtomic(submitDone, equalTo(true));
1415 executor.shutdownNow();
1419 public void testSnapshotOnRootOverwrite() throws Exception {
1420 // FIXME: ClientBackedDatastore does not have stable indexes/term, the snapshot index seems to fluctuate
1421 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1423 final String testName = "testSnapshotOnRootOverwrite";
1424 final String[] shards = {"cars", "default"};
1425 initDatastores(testName, "module-shards-default-cars-member1-and-2.conf", shards,
1426 leaderDatastoreContextBuilder.snapshotOnRootOverwrite(true),
1427 followerDatastoreContextBuilder.snapshotOnRootOverwrite(true));
1429 leaderTestKit.waitForMembersUp("member-2");
1430 final ContainerNode rootNode = ImmutableContainerNodeBuilder.create()
1431 .withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(SchemaContext.NAME))
1432 .withChild((ContainerNode) CarsModel.create())
1435 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1437 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1438 state -> assertEquals(1, state.getSnapshotIndex()));
1440 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1441 state -> assertEquals(1, state.getSnapshotIndex()));
1443 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1444 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1446 for (int i = 0; i < 10; i++) {
1447 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, CarsModel.newCarPath("car " + i),
1448 CarsModel.newCarEntry("car " + i, Uint64.ONE));
1451 // fake snapshot causes the snapshotIndex to move
1452 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1453 state -> assertEquals(10, state.getSnapshotIndex()));
1454 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1455 state -> assertEquals(10, state.getSnapshotIndex()));
1457 // however the real snapshot still has not changed and was taken at index 1
1458 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1459 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1461 // root overwrite so expect a snapshot
1462 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1464 // this was a real snapshot so everything should be in it(1(DisableTrackingPayload) + 1 + 10 + 1)
1465 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1466 state -> assertEquals(12, state.getSnapshotIndex()));
1467 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1468 state -> assertEquals(12, state.getSnapshotIndex()));
1470 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 12);
1471 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 12);
1474 private void verifySnapshot(final String persistenceId, final long lastAppliedIndex) {
1475 await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
1476 List<Snapshot> snap = InMemorySnapshotStore.getSnapshots(persistenceId, Snapshot.class);
1477 assertEquals(1, snap.size());
1478 assertEquals(lastAppliedIndex, snap.get(0).getLastAppliedIndex());
1483 private static void verifySnapshot(final Snapshot actual, final Snapshot expected,
1484 final NormalizedNode<?, ?> expRoot) {
1485 assertEquals("Snapshot getLastAppliedTerm", expected.getLastAppliedTerm(), actual.getLastAppliedTerm());
1486 assertEquals("Snapshot getLastAppliedIndex", expected.getLastAppliedIndex(), actual.getLastAppliedIndex());
1487 assertEquals("Snapshot getLastTerm", expected.getLastTerm(), actual.getLastTerm());
1488 assertEquals("Snapshot getLastIndex", expected.getLastIndex(), actual.getLastIndex());
1489 assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
1490 MetadataShardDataTreeSnapshot shardSnapshot =
1491 (MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
1492 assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
1495 private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1496 final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1497 final DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
1498 final Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1499 doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1500 doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(anyString());
1501 dataStore.onDatastoreContextUpdated(mockContextFactory);