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.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;
132 * End-to-end distributed data store tests that exercise remote shards and transactions.
134 * @author Thomas Pantelis
136 @RunWith(Parameterized.class)
137 public class DistributedDataStoreRemotingIntegrationTest extends AbstractTest {
139 @Parameters(name = "{0}")
140 public static Collection<Object[]> data() {
141 return Arrays.asList(new Object[][] {
142 { TestDistributedDataStore.class, 7}, { TestClientBackedDataStore.class, 12 }
147 public Class<? extends AbstractDataStore> testParameter;
149 public int commitTimeout;
151 private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
152 private static final String[] CARS = {"cars"};
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");
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";
164 private ActorSystem leaderSystem;
165 private ActorSystem followerSystem;
166 private ActorSystem follower2System;
168 private final DatastoreContext.Builder leaderDatastoreContextBuilder =
169 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
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();
177 private AbstractDataStore followerDistributedDataStore;
178 private AbstractDataStore leaderDistributedDataStore;
179 private IntegrationTestKit followerTestKit;
180 private IntegrationTestKit leaderTestKit;
183 public void setUp() {
184 InMemoryJournal.clear();
185 InMemorySnapshotStore.clear();
187 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
188 Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
190 followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
191 Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
193 follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
194 Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
198 public void tearDown() {
199 if (followerDistributedDataStore != null) {
200 leaderDistributedDataStore.close();
202 if (leaderDistributedDataStore != null) {
203 leaderDistributedDataStore.close();
206 TestKit.shutdownActorSystem(leaderSystem, true);
207 TestKit.shutdownActorSystem(followerSystem, true);
208 TestKit.shutdownActorSystem(follower2System,true);
210 InMemoryJournal.clear();
211 InMemorySnapshotStore.clear();
214 private void initDatastoresWithCars(final String type) throws Exception {
215 initDatastores(type, MODULE_SHARDS_CARS_ONLY_1_2, CARS);
218 private void initDatastoresWithCarsAndPeople(final String type) throws Exception {
219 initDatastores(type, MODULE_SHARDS_CARS_PEOPLE_1_2, CARS_AND_PEOPLE);
222 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards)
224 initDatastores(type, moduleShardsConfig, shards, leaderDatastoreContextBuilder,
225 followerDatastoreContextBuilder);
228 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards,
229 final DatastoreContext.Builder leaderBuilder, final DatastoreContext.Builder followerBuilder)
231 leaderTestKit = new IntegrationTestKit(leaderSystem, leaderBuilder, commitTimeout);
233 leaderDistributedDataStore = leaderTestKit.setupAbstractDataStore(
234 testParameter, type, moduleShardsConfig, false, shards);
236 followerTestKit = new IntegrationTestKit(followerSystem, followerBuilder, commitTimeout);
237 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
238 testParameter, type, moduleShardsConfig, false, shards);
240 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorUtils(), shards);
242 leaderTestKit.waitForMembersUp("member-2");
243 followerTestKit.waitForMembersUp("member-1");
246 private static void verifyCars(final DOMStoreReadTransaction readTx, final MapEntryNode... entries)
248 final Optional<NormalizedNode> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
249 assertTrue("isPresent", optional.isPresent());
251 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> listBuilder = ImmutableNodes.mapNodeBuilder(
252 CarsModel.CAR_QNAME);
253 for (final NormalizedNode entry: entries) {
254 listBuilder.withChild((MapEntryNode) entry);
257 assertEquals("Car list node", listBuilder.build(), optional.get());
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));
265 private static void verifyExists(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path)
267 assertEquals("exists", Boolean.TRUE, readTx.exists(path).get(5, TimeUnit.SECONDS));
271 public void testWriteTransactionWithSingleShard() throws Exception {
272 final String testName = "testWriteTransactionWithSingleShard";
273 initDatastoresWithCars(testName);
275 final String followerCarShardName = "member-2-shard-cars-" + testName;
277 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
278 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
280 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
281 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
283 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
284 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
285 writeTx.merge(car1Path, car1);
287 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
288 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
289 writeTx.merge(car2Path, car2);
291 followerTestKit.doCommit(writeTx.ready());
293 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
295 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
299 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
301 writeTx.delete(car1Path);
303 followerTestKit.doCommit(writeTx.ready());
305 verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
307 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
309 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
311 // Re-instate the follower member 2 as a single-node to verify replication and recovery.
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()));
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;
329 final List<ApplyJournalEntries> entries = InMemoryJournal.get(followerCarShardName,
330 ApplyJournalEntries.class);
331 for (ApplyJournalEntries aje: entries) {
332 if (aje.getToIndex() >= leaderLastAppliedIndex.get()) {
338 assertTrue("Follower did not persist ApplyJournalEntries containing leader's lastAppliedIndex "
339 + leaderLastAppliedIndex + ". Entries persisted: " + entries, sw.elapsed(TimeUnit.SECONDS) <= 5);
341 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
344 TestKit.shutdownActorSystem(leaderSystem, true);
345 TestKit.shutdownActorSystem(followerSystem, true);
347 final ActorSystem newSystem = newActorSystem("reinstated-member2", "Member2");
349 try (AbstractDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder,
351 .setupAbstractDataStore(testParameter, testName, "module-shards-member2", true, CARS)) {
352 verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
357 public void testSingleTransactionsWritesInQuickSuccession() throws Exception {
358 initDatastoresWithCars("testSingleTransactionsWritesInQuickSuccession");
360 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
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());
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());
373 try (var tx = txChain.newReadOnlyTransaction()) {
374 tx.read(CarsModel.BASE_PATH).get();
378 // wait to let the shard catch up with purged
379 await("Range set leak test").atMost(5, TimeUnit.SECONDS)
380 .pollInterval(500, TimeUnit.MILLISECONDS)
381 .untilAsserted(() -> {
382 final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars")
384 final var frontendMetadata =
385 (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
386 .executeOperation(localShard, new RequestFrontendMetadata());
388 final var clientMeta = frontendMetadata.getClients().get(0);
389 if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
390 assertTellClientMetadata(clientMeta, numCars);
392 assertAskClientMetadata(clientMeta);
396 try (var tx = txChain.newReadOnlyTransaction()) {
397 final var body = tx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS).orElseThrow().body();
398 assertThat(body, instanceOf(Collection.class));
399 assertEquals(numCars, ((Collection<?>) body).size());
403 private void assertAskClientMetadata(final FrontendClientMetadata clientMeta) {
404 // ask based should track no metadata
405 assertEquals(List.of(), clientMeta.getCurrentHistories());
408 private void assertTellClientMetadata(final FrontendClientMetadata clientMeta, final int numCars) {
409 final var iterator = clientMeta.getCurrentHistories().iterator();
410 var metadata = iterator.next();
411 while (iterator.hasNext() && metadata.getHistoryId() != 1) {
412 metadata = iterator.next();
415 // FIXME: CONTROLLER-1991: remove this assumption
418 assertEquals(UnsignedLongBitmap.of(), metadata.getClosedTransactions());
419 assertEquals("[[0.." + numCars * 2 + "]]", metadata.getPurgedTransactions().toString());
423 public void testCloseTransactionMetadataLeak() throws Exception {
424 // FIXME: Ask-based frontend seems to have some issues with back to back close
425 assumeTrue(testParameter.isAssignableFrom(TestClientBackedDataStore.class));
427 initDatastoresWithCars("testCloseTransactionMetadataLeak");
429 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
431 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
432 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
433 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
434 followerTestKit.doCommit(writeTx.ready());
437 for (int i = 0; i < numCars; i++) {
438 writeTx = txChain.newWriteOnlyTransaction();
441 try (var tx = txChain.newReadOnlyTransaction()) {
442 tx.read(CarsModel.BASE_PATH).get();
446 writeTx = txChain.newWriteOnlyTransaction();
447 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
448 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
449 followerTestKit.doCommit(writeTx.ready());
451 // wait to let the shard catch up with purged
452 await("Close transaction purge leak test.").atMost(5, TimeUnit.SECONDS)
453 .pollInterval(500, TimeUnit.MILLISECONDS)
454 .untilAsserted(() -> {
455 final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars")
457 final var frontendMetadata =
458 (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
459 .executeOperation(localShard, new RequestFrontendMetadata());
461 final var clientMeta = frontendMetadata.getClients().get(0);
462 if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
463 assertTellClientMetadata(clientMeta, numCars);
465 assertAskClientMetadata(clientMeta);
469 try (var tx = txChain.newReadOnlyTransaction()) {
470 final var body = tx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS).orElseThrow().body();
471 assertThat(body, instanceOf(Collection.class));
472 assertEquals(numCars, ((Collection<?>) body).size());
477 public void testReadWriteTransactionWithSingleShard() throws Exception {
478 initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
480 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
481 assertNotNull("newReadWriteTransaction returned null", rwTx);
483 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
484 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
486 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
487 rwTx.merge(CarsModel.newCarPath("optima"), car1);
489 verifyCars(rwTx, car1);
491 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
492 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
493 rwTx.merge(car2Path, car2);
495 verifyExists(rwTx, car2Path);
497 followerTestKit.doCommit(rwTx.ready());
499 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
503 public void testWriteTransactionWithMultipleShards() throws Exception {
504 initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
506 final DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
507 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
509 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
510 final NormalizedNode carsNode = CarsModel.emptyContainer();
511 writeTx.write(carsPath, carsNode);
513 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
514 final NormalizedNode peopleNode = PeopleModel.emptyContainer();
515 writeTx.write(peoplePath, peopleNode);
517 followerTestKit.doCommit(writeTx.ready());
519 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
521 verifyNode(readTx, carsPath, carsNode);
522 verifyNode(readTx, peoplePath, peopleNode);
526 public void testReadWriteTransactionWithMultipleShards() throws Exception {
527 initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
529 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
530 assertNotNull("newReadWriteTransaction returned null", rwTx);
532 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
533 final NormalizedNode carsNode = CarsModel.emptyContainer();
534 rwTx.write(carsPath, carsNode);
536 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
537 final NormalizedNode peopleNode = PeopleModel.emptyContainer();
538 rwTx.write(peoplePath, peopleNode);
540 followerTestKit.doCommit(rwTx.ready());
542 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
544 verifyNode(readTx, carsPath, carsNode);
545 verifyNode(readTx, peoplePath, peopleNode);
549 public void testTransactionChainWithSingleShard() throws Exception {
550 initDatastoresWithCars("testTransactionChainWithSingleShard");
552 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
554 // Add the top-level cars container with write-only.
556 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
557 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
559 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
561 final DOMStoreThreePhaseCommitCohort writeTxReady = writeTx.ready();
563 // Verify the top-level cars container with read-only.
565 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
567 // Perform car operations with read-write.
569 final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
571 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
573 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
575 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
576 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
577 rwTx.write(car1Path, car1);
579 verifyExists(rwTx, car1Path);
581 verifyCars(rwTx, car1);
583 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
584 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
586 rwTx.delete(car1Path);
588 followerTestKit.doCommit(writeTxReady);
590 followerTestKit.doCommit(rwTx.ready());
594 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
598 public void testTransactionChainWithMultipleShards() throws Exception {
599 initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
601 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
603 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
604 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
606 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
607 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
609 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
610 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
612 followerTestKit.doCommit(writeTx.ready());
614 final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
616 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
617 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
618 readWriteTx.write(carPath, car);
620 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
621 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
622 readWriteTx.merge(personPath, person);
624 assertEquals(Optional.of(car), readWriteTx.read(carPath).get(5, TimeUnit.SECONDS));
625 assertEquals(Optional.of(person), readWriteTx.read(personPath).get(5, TimeUnit.SECONDS));
627 final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
629 writeTx = txChain.newWriteOnlyTransaction();
631 writeTx.delete(personPath);
633 final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
635 followerTestKit.doCommit(cohort2);
636 followerTestKit.doCommit(cohort3);
640 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
641 verifyCars(readTx, car);
643 assertEquals(Optional.empty(), readTx.read(personPath).get(5, TimeUnit.SECONDS));
647 public void testChainedTransactionFailureWithSingleShard() throws Exception {
648 initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
650 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
651 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
652 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
653 MoreExecutors.directExecutor());
655 final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
656 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
658 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
660 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
661 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
662 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
664 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
666 final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
668 assertThat(ex, instanceOf(TransactionCommitFailedException.class));
670 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
677 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
678 initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
680 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
681 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
682 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
683 MoreExecutors.directExecutor());
685 final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
686 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
688 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
690 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
692 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
693 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
694 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
696 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
697 // done for put for performance reasons.
698 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
700 final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
702 assertThat(ex, instanceOf(TransactionCommitFailedException.class));
704 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
711 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
712 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
713 final String testName = "testSingleShardTransactionsWithLeaderChanges";
714 initDatastoresWithCars(testName);
716 final String followerCarShardName = "member-2-shard-cars-" + testName;
717 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class);
719 // Write top-level car container from the follower so it uses a remote Tx.
721 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
723 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
724 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
726 followerTestKit.doCommit(writeTx.ready());
728 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
730 // Switch the leader to the follower
732 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
733 .shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
735 TestKit.shutdownActorSystem(leaderSystem, true);
736 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
738 followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorUtils(), CARS);
740 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
741 Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
743 final DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder()
744 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
745 IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder, commitTimeout);
747 try (AbstractDataStore ds =
748 newMember1TestKit.setupAbstractDataStore(
749 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS)) {
751 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), CARS);
753 // Write a car entry to the new leader - should switch to local Tx
755 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
757 MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
758 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
759 writeTx.merge(car1Path, car1);
761 followerTestKit.doCommit(writeTx.ready());
763 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
767 @SuppressWarnings("unchecked")
769 public void testReadyLocalTransactionForwardedToLeader() throws Exception {
770 initDatastoresWithCars("testReadyLocalTransactionForwardedToLeader");
771 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
773 final Optional<ActorRef> carsFollowerShard =
774 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
775 assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
777 final DataTree dataTree = new InMemoryDataTreeFactory().create(
778 DataTreeConfiguration.DEFAULT_OPERATIONAL, SchemaContextHelper.full());
780 // Send a tx with immediate commit.
782 DataTreeModification modification = dataTree.takeSnapshot().newModification();
783 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
784 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
786 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
787 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
788 modification.ready();
790 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(tx1 , modification, true, Optional.empty());
792 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
793 Object resp = followerTestKit.expectMsgClass(Object.class);
794 if (resp instanceof akka.actor.Status.Failure) {
795 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
798 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
800 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
802 // Send another tx without immediate commit.
804 modification = dataTree.takeSnapshot().newModification();
805 MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
806 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
807 modification.ready();
809 readyLocal = new ReadyLocalTransaction(tx2 , modification, false, Optional.empty());
811 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
812 resp = followerTestKit.expectMsgClass(Object.class);
813 if (resp instanceof akka.actor.Status.Failure) {
814 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
817 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
819 final ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
820 ((ReadyTransactionReply)resp).getCohortPath());
822 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(leaderDistributedDataStore.getActorUtils(),
823 List.of(new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor),
824 () -> DataStoreVersions.CURRENT_VERSION)), tx2);
825 cohort.canCommit().get(5, TimeUnit.SECONDS);
826 cohort.preCommit().get(5, TimeUnit.SECONDS);
827 cohort.commit().get(5, TimeUnit.SECONDS);
829 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
832 @SuppressWarnings("unchecked")
834 public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
835 initDatastoresWithCars("testForwardedReadyTransactionForwardedToLeader");
836 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
838 final Optional<ActorRef> carsFollowerShard =
839 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
840 assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
842 carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
843 final DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
845 // Send a tx with immediate commit.
847 DataTreeModification modification = dataTree.takeSnapshot().newModification();
848 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
849 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
851 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
852 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
854 ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction(tx1, DataStoreVersions.CURRENT_VERSION,
855 new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx1, modification),
856 true, Optional.empty());
858 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
859 Object resp = followerTestKit.expectMsgClass(Object.class);
860 if (resp instanceof akka.actor.Status.Failure) {
861 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
864 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
866 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
868 // Send another tx without immediate commit.
870 modification = dataTree.takeSnapshot().newModification();
871 MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
872 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
874 forwardedReady = new ForwardedReadyTransaction(tx2, DataStoreVersions.CURRENT_VERSION,
875 new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx2, modification),
876 false, Optional.empty());
878 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
879 resp = followerTestKit.expectMsgClass(Object.class);
880 if (resp instanceof akka.actor.Status.Failure) {
881 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
884 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
886 ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
887 ((ReadyTransactionReply)resp).getCohortPath());
889 final ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
890 leaderDistributedDataStore.getActorUtils(), List.of(
891 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor),
892 () -> DataStoreVersions.CURRENT_VERSION)), tx2);
893 cohort.canCommit().get(5, TimeUnit.SECONDS);
894 cohort.preCommit().get(5, TimeUnit.SECONDS);
895 cohort.commit().get(5, TimeUnit.SECONDS);
897 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
901 public void testTransactionForwardedToLeaderAfterRetry() throws Exception {
902 // FIXME: remove when test passes also for ClientBackedDataStore
903 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
905 followerDatastoreContextBuilder.shardBatchedModificationCount(2);
906 leaderDatastoreContextBuilder.shardBatchedModificationCount(2);
907 initDatastoresWithCarsAndPeople("testTransactionForwardedToLeaderAfterRetry");
909 // Do an initial write to get the primary shard info cached.
911 final DOMStoreWriteTransaction initialWriteTx = followerDistributedDataStore.newWriteOnlyTransaction();
912 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
913 initialWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
914 followerTestKit.doCommit(initialWriteTx.ready());
916 // Wait for the commit to be replicated to the follower.
918 MemberNode.verifyRaftState(followerDistributedDataStore, "cars",
919 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
921 MemberNode.verifyRaftState(followerDistributedDataStore, "people",
922 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
924 // Prepare, ready and canCommit a WO tx that writes to 2 shards. This will become the current tx in
927 final DOMStoreWriteTransaction writeTx1 = followerDistributedDataStore.newWriteOnlyTransaction();
928 writeTx1.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
929 writeTx1.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
930 final DOMStoreThreePhaseCommitCohort writeTx1Cohort = writeTx1.ready();
931 final ListenableFuture<Boolean> writeTx1CanCommit = writeTx1Cohort.canCommit();
932 writeTx1CanCommit.get(5, TimeUnit.SECONDS);
934 // Prepare and ready another WO tx that writes to 2 shards but don't canCommit yet. This will be queued
935 // in the leader shard.
937 final DOMStoreWriteTransaction writeTx2 = followerDistributedDataStore.newWriteOnlyTransaction();
938 final LinkedList<MapEntryNode> cars = new LinkedList<>();
940 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
941 writeTx2.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
943 NormalizedNode people = ImmutableNodes.mapNodeBuilder(PeopleModel.PERSON_QNAME)
944 .withChild(PeopleModel.newPersonEntry("Dude")).build();
945 writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
946 final DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
948 // Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
949 // tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
950 // leader shard (with shardBatchedModificationCount set to 2). The 3rd BatchedModidifications will be
953 final DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
954 for (int i = 1; i <= 5; i++, carIndex++) {
955 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
956 writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
959 // Prepare another WO that writes to a single shard. This will send a single BatchedModidifications
962 final DOMStoreWriteTransaction writeTx4 = followerDistributedDataStore.newWriteOnlyTransaction();
963 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
964 writeTx4.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
967 // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaciton message to the
968 // leader shard on ready.
970 final DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
971 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
972 readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
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(() -> leaderCluster.readView().unreachableMembers().contains(follower2Member));
1270 await().atMost(10, TimeUnit.SECONDS)
1271 .until(() -> followerCluster.readView().unreachableMembers().contains(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());
1294 public void testInstallSnapshot() throws Exception {
1295 final String testName = "testInstallSnapshot";
1296 final String leaderCarShardName = "member-1-shard-cars-" + testName;
1297 final String followerCarShardName = "member-2-shard-cars-" + testName;
1299 // Setup a saved snapshot on the leader. The follower will startup with no data and the leader should
1300 // install a snapshot to sync the follower.
1302 DataTree tree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_CONFIGURATION,
1303 SchemaContextHelper.full());
1305 final ContainerNode carsNode = CarsModel.newCarsNode(
1306 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", Uint64.valueOf(20000))));
1307 AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
1309 final NormalizedNode snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.empty());
1310 final Snapshot initialSnapshot = Snapshot.create(
1311 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
1312 Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
1313 InMemorySnapshotStore.addSnapshot(leaderCarShardName, initialSnapshot);
1315 InMemorySnapshotStore.addSnapshotSavedLatch(leaderCarShardName);
1316 InMemorySnapshotStore.addSnapshotSavedLatch(followerCarShardName);
1318 initDatastoresWithCars(testName);
1320 assertEquals(Optional.of(carsNode), leaderDistributedDataStore.newReadOnlyTransaction().read(
1321 CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS));
1323 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(leaderCarShardName, Snapshot.class),
1324 initialSnapshot, snapshotRoot);
1326 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(followerCarShardName, Snapshot.class),
1327 initialSnapshot, snapshotRoot);
1331 public void testReadWriteMessageSlicing() throws Exception {
1332 // The slicing is only implemented for tell-based protocol
1333 assumeTrue(ClientBackedDataStore.class.isAssignableFrom(testParameter));
1335 leaderDatastoreContextBuilder.maximumMessageSliceSize(100);
1336 followerDatastoreContextBuilder.maximumMessageSliceSize(100);
1337 initDatastoresWithCars("testLargeReadReplySlicing");
1339 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1341 final NormalizedNode carsNode = CarsModel.create();
1342 rwTx.write(CarsModel.BASE_PATH, carsNode);
1344 verifyNode(rwTx, CarsModel.BASE_PATH, carsNode);
1347 @SuppressWarnings("IllegalCatch")
1349 public void testRaftCallbackDuringLeadershipDrop() throws Exception {
1350 final String testName = "testRaftCallbackDuringLeadershipDrop";
1351 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1353 final ExecutorService executor = Executors.newSingleThreadExecutor();
1355 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1356 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500)
1357 .shardLeaderElectionTimeoutInSeconds(3600),
1360 final DOMStoreWriteTransaction initialWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1361 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1362 leaderTestKit.doCommit(initialWriteTx.ready());
1364 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1365 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false)) {
1367 final ActorRef member3Cars = ((LocalShardStore) follower2DistributedDataStore).getLocalShards()
1368 .getLocalShards().get("cars").getActor();
1369 final ActorRef member2Cars = ((LocalShardStore)followerDistributedDataStore).getLocalShards()
1370 .getLocalShards().get("cars").getActor();
1371 member2Cars.tell(new StartDropMessages(AppendEntries.class), null);
1372 member3Cars.tell(new StartDropMessages(AppendEntries.class), null);
1374 final DOMStoreWriteTransaction newTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1375 newTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1376 final AtomicBoolean submitDone = new AtomicBoolean(false);
1377 executor.submit(() -> {
1379 leaderTestKit.doCommit(newTx.ready());
1380 submitDone.set(true);
1381 } catch (Exception e) {
1382 throw new RuntimeException(e);
1385 final ActorRef leaderCars = ((LocalShardStore) leaderDistributedDataStore).getLocalShards()
1386 .getLocalShards().get("cars").getActor();
1387 await().atMost(10, TimeUnit.SECONDS)
1388 .until(() -> ((OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1389 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE)).getLastIndex() >= 1);
1391 final OnDemandRaftState raftState = (OnDemandRaftState)leaderDistributedDataStore.getActorUtils()
1392 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE);
1394 // Simulate a follower not receiving heartbeats but still being able to send messages ie RequestVote with
1395 // new term(switching to candidate after election timeout)
1396 leaderCars.tell(new RequestVote(raftState.getCurrentTerm() + 1,
1397 "member-3-shard-cars-testRaftCallbackDuringLeadershipDrop", -1,
1400 member2Cars.tell(new StopDropMessages(AppendEntries.class), null);
1401 member3Cars.tell(new StopDropMessages(AppendEntries.class), null);
1403 await("Is tx stuck in COMMIT_PENDING")
1404 .atMost(10, TimeUnit.SECONDS).untilAtomic(submitDone, equalTo(true));
1408 executor.shutdownNow();
1412 public void testSnapshotOnRootOverwrite() throws Exception {
1413 // FIXME: ClientBackedDatastore does not have stable indexes/term, the snapshot index seems to fluctuate
1414 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1416 final String testName = "testSnapshotOnRootOverwrite";
1417 final String[] shards = {"cars", "default"};
1418 initDatastores(testName, "module-shards-default-cars-member1-and-2.conf", shards,
1419 leaderDatastoreContextBuilder.snapshotOnRootOverwrite(true),
1420 followerDatastoreContextBuilder.snapshotOnRootOverwrite(true));
1422 leaderTestKit.waitForMembersUp("member-2");
1423 final ContainerNode rootNode = ImmutableContainerNodeBuilder.create()
1424 .withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(SchemaContext.NAME))
1425 .withChild(CarsModel.create())
1428 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1430 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1431 state -> assertEquals(1, state.getSnapshotIndex()));
1433 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1434 state -> assertEquals(1, state.getSnapshotIndex()));
1436 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1437 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1439 for (int i = 0; i < 10; i++) {
1440 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, CarsModel.newCarPath("car " + i),
1441 CarsModel.newCarEntry("car " + i, Uint64.ONE));
1444 // fake snapshot causes the snapshotIndex to move
1445 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1446 state -> assertEquals(10, state.getSnapshotIndex()));
1447 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1448 state -> assertEquals(10, state.getSnapshotIndex()));
1450 // however the real snapshot still has not changed and was taken at index 1
1451 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1452 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1454 // root overwrite so expect a snapshot
1455 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1457 // this was a real snapshot so everything should be in it(1(DisableTrackingPayload) + 1 + 10 + 1)
1458 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1459 state -> assertEquals(12, state.getSnapshotIndex()));
1460 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1461 state -> assertEquals(12, state.getSnapshotIndex()));
1463 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 12);
1464 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 12);
1467 private void verifySnapshot(final String persistenceId, final long lastAppliedIndex) {
1468 await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
1469 List<Snapshot> snap = InMemorySnapshotStore.getSnapshots(persistenceId, Snapshot.class);
1470 assertEquals(1, snap.size());
1471 assertEquals(lastAppliedIndex, snap.get(0).getLastAppliedIndex());
1476 private static void verifySnapshot(final Snapshot actual, final Snapshot expected,
1477 final NormalizedNode expRoot) {
1478 assertEquals("Snapshot getLastAppliedTerm", expected.getLastAppliedTerm(), actual.getLastAppliedTerm());
1479 assertEquals("Snapshot getLastAppliedIndex", expected.getLastAppliedIndex(), actual.getLastAppliedIndex());
1480 assertEquals("Snapshot getLastTerm", expected.getLastTerm(), actual.getLastTerm());
1481 assertEquals("Snapshot getLastIndex", expected.getLastIndex(), actual.getLastIndex());
1482 assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
1483 MetadataShardDataTreeSnapshot shardSnapshot =
1484 (MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
1485 assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
1488 private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1489 final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1490 final DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
1491 final Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1492 doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1493 doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(anyString());
1494 dataStore.onDatastoreContextUpdated(mockContextFactory);