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.primitives.UnsignedLong;
41 import com.google.common.util.concurrent.ListenableFuture;
42 import com.google.common.util.concurrent.MoreExecutors;
43 import com.google.common.util.concurrent.Uninterruptibles;
44 import com.typesafe.config.ConfigFactory;
45 import java.util.Arrays;
46 import java.util.Collection;
47 import java.util.Collections;
48 import java.util.LinkedList;
49 import java.util.List;
50 import java.util.Optional;
51 import java.util.concurrent.ExecutionException;
52 import java.util.concurrent.ExecutorService;
53 import java.util.concurrent.Executors;
54 import java.util.concurrent.TimeUnit;
55 import java.util.concurrent.atomic.AtomicBoolean;
56 import java.util.concurrent.atomic.AtomicLong;
57 import org.junit.After;
58 import org.junit.Before;
59 import org.junit.Test;
60 import org.junit.runner.RunWith;
61 import org.junit.runners.Parameterized;
62 import org.junit.runners.Parameterized.Parameter;
63 import org.junit.runners.Parameterized.Parameters;
64 import org.mockito.stubbing.Answer;
65 import org.opendaylight.controller.cluster.access.client.RequestTimeoutException;
66 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
67 import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
68 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
69 import org.opendaylight.controller.cluster.databroker.TestClientBackedDataStore;
70 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
71 import org.opendaylight.controller.cluster.datastore.TestShard.RequestFrontendMetadata;
72 import org.opendaylight.controller.cluster.datastore.TestShard.StartDropMessages;
73 import org.opendaylight.controller.cluster.datastore.TestShard.StopDropMessages;
74 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
75 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
76 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
77 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
78 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
79 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
80 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
81 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
82 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
83 import org.opendaylight.controller.cluster.datastore.persisted.FrontendClientMetadata;
84 import org.opendaylight.controller.cluster.datastore.persisted.FrontendShardDataTreeSnapshotMetadata;
85 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
86 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
87 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
88 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
89 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
90 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
91 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
92 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
93 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
94 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
95 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
96 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
97 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
98 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
99 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
100 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
101 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
102 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
103 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
104 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
105 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
106 import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
107 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
108 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
109 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
110 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
111 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
112 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
113 import org.opendaylight.yangtools.yang.common.Uint64;
114 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
115 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
117 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
119 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
120 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
121 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
122 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
123 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
124 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
125 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
126 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
127 import scala.concurrent.Await;
128 import scala.concurrent.Future;
129 import scala.concurrent.duration.FiniteDuration;
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 DOMStoreReadTransaction domStoreReadTransaction = txChain.newReadOnlyTransaction();
374 domStoreReadTransaction.read(CarsModel.BASE_PATH).get();
376 domStoreReadTransaction.close();
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);
393 assertAskClientMetadata(clientMeta);
397 try (var tx = txChain.newReadOnlyTransaction()) {
398 final var body = tx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS).orElseThrow().body();
399 assertThat(body, instanceOf(Collection.class));
400 assertEquals(numCars, ((Collection<?>) body).size());
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 int numCars) {
410 final var iterator = clientMeta.getCurrentHistories().iterator();
411 var metadata = iterator.next();
412 while (iterator.hasNext() && metadata.getHistoryId() != 1) {
413 metadata = iterator.next();
416 assertEquals(0, metadata.getClosedTransactions().size());
418 final var purgedRanges = metadata.getPurgedTransactions().ranges();
420 // FIXME: CONTROLLER-1991: remove this assumption
423 assertEquals(1, purgedRanges.size());
424 final var purgedRange = purgedRanges.first();
425 assertEquals(UnsignedLong.ZERO, purgedRange.lower());
426 assertEquals(UnsignedLong.valueOf(10), purgedRange.upper());
430 public void testCloseTransactionMetadataLeak() throws Exception {
431 // FIXME: Ask-based frontend seems to have some issues with back to back close
432 assumeTrue(testParameter.isAssignableFrom(TestClientBackedDataStore.class));
434 initDatastoresWithCars("testCloseTransactionMetadataLeak");
436 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
438 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
439 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
440 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
441 followerTestKit.doCommit(writeTx.ready());
444 for (int i = 0; i < numCars; i++) {
445 writeTx = txChain.newWriteOnlyTransaction();
448 DOMStoreReadTransaction domStoreReadTransaction = txChain.newReadOnlyTransaction();
449 domStoreReadTransaction.read(CarsModel.BASE_PATH).get();
451 domStoreReadTransaction.close();
454 writeTx = txChain.newWriteOnlyTransaction();
455 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
456 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
457 followerTestKit.doCommit(writeTx.ready());
459 // wait to let the shard catch up with purged
460 await("Close transaction purge leak test.").atMost(5, TimeUnit.SECONDS)
461 .pollInterval(500, TimeUnit.MILLISECONDS)
462 .untilAsserted(() -> {
463 final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars")
465 final var frontendMetadata =
466 (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
467 .executeOperation(localShard, new RequestFrontendMetadata());
469 final var clientMeta = frontendMetadata.getClients().get(0);
470 if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
471 assertTellClientMetadata(clientMeta, numCars);
473 assertAskClientMetadata(clientMeta);
477 try (var tx = txChain.newReadOnlyTransaction()) {
478 final var body = tx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS).orElseThrow().body();
479 assertThat(body, instanceOf(Collection.class));
480 assertEquals(numCars, ((Collection<?>) body).size());
485 public void testReadWriteTransactionWithSingleShard() throws Exception {
486 initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
488 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
489 assertNotNull("newReadWriteTransaction returned null", rwTx);
491 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
492 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
494 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
495 rwTx.merge(CarsModel.newCarPath("optima"), car1);
497 verifyCars(rwTx, car1);
499 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
500 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
501 rwTx.merge(car2Path, car2);
503 verifyExists(rwTx, car2Path);
505 followerTestKit.doCommit(rwTx.ready());
507 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
511 public void testWriteTransactionWithMultipleShards() throws Exception {
512 initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
514 final DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
515 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
517 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
518 final NormalizedNode carsNode = CarsModel.emptyContainer();
519 writeTx.write(carsPath, carsNode);
521 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
522 final NormalizedNode peopleNode = PeopleModel.emptyContainer();
523 writeTx.write(peoplePath, peopleNode);
525 followerTestKit.doCommit(writeTx.ready());
527 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
529 verifyNode(readTx, carsPath, carsNode);
530 verifyNode(readTx, peoplePath, peopleNode);
534 public void testReadWriteTransactionWithMultipleShards() throws Exception {
535 initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
537 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
538 assertNotNull("newReadWriteTransaction returned null", rwTx);
540 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
541 final NormalizedNode carsNode = CarsModel.emptyContainer();
542 rwTx.write(carsPath, carsNode);
544 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
545 final NormalizedNode peopleNode = PeopleModel.emptyContainer();
546 rwTx.write(peoplePath, peopleNode);
548 followerTestKit.doCommit(rwTx.ready());
550 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
552 verifyNode(readTx, carsPath, carsNode);
553 verifyNode(readTx, peoplePath, peopleNode);
557 public void testTransactionChainWithSingleShard() throws Exception {
558 initDatastoresWithCars("testTransactionChainWithSingleShard");
560 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
562 // Add the top-level cars container with write-only.
564 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
565 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
567 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
569 final DOMStoreThreePhaseCommitCohort writeTxReady = writeTx.ready();
571 // Verify the top-level cars container with read-only.
573 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
575 // Perform car operations with read-write.
577 final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
579 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
581 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
583 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
584 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
585 rwTx.write(car1Path, car1);
587 verifyExists(rwTx, car1Path);
589 verifyCars(rwTx, car1);
591 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
592 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
594 rwTx.delete(car1Path);
596 followerTestKit.doCommit(writeTxReady);
598 followerTestKit.doCommit(rwTx.ready());
602 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
606 public void testTransactionChainWithMultipleShards() throws Exception {
607 initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
609 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
611 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
612 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
614 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
615 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
617 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
618 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
620 followerTestKit.doCommit(writeTx.ready());
622 final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
624 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
625 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
626 readWriteTx.write(carPath, car);
628 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
629 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
630 readWriteTx.merge(personPath, person);
632 assertEquals(Optional.of(car), readWriteTx.read(carPath).get(5, TimeUnit.SECONDS));
633 assertEquals(Optional.of(person), readWriteTx.read(personPath).get(5, TimeUnit.SECONDS));
635 final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
637 writeTx = txChain.newWriteOnlyTransaction();
639 writeTx.delete(personPath);
641 final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
643 followerTestKit.doCommit(cohort2);
644 followerTestKit.doCommit(cohort3);
648 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
649 verifyCars(readTx, car);
651 assertEquals(Optional.empty(), readTx.read(personPath).get(5, TimeUnit.SECONDS));
655 public void testChainedTransactionFailureWithSingleShard() throws Exception {
656 initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
658 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
659 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
660 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
661 MoreExecutors.directExecutor());
663 final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
664 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
666 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
668 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
669 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
670 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
672 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
674 final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
676 assertThat(ex, instanceOf(TransactionCommitFailedException.class));
678 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
685 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
686 initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
688 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
689 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
690 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
691 MoreExecutors.directExecutor());
693 final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
694 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
696 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
698 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
700 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
701 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
702 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
704 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
705 // done for put for performance reasons.
706 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
708 final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
710 assertThat(ex, instanceOf(TransactionCommitFailedException.class));
712 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
719 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
720 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
721 final String testName = "testSingleShardTransactionsWithLeaderChanges";
722 initDatastoresWithCars(testName);
724 final String followerCarShardName = "member-2-shard-cars-" + testName;
725 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class);
727 // Write top-level car container from the follower so it uses a remote Tx.
729 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
731 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
732 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
734 followerTestKit.doCommit(writeTx.ready());
736 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
738 // Switch the leader to the follower
740 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
741 .shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
743 TestKit.shutdownActorSystem(leaderSystem, true);
744 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
746 followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorUtils(), CARS);
748 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
749 Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
751 final DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder()
752 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
753 IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder, commitTimeout);
755 try (AbstractDataStore ds =
756 newMember1TestKit.setupAbstractDataStore(
757 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS)) {
759 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), CARS);
761 // Write a car entry to the new leader - should switch to local Tx
763 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
765 MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
766 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
767 writeTx.merge(car1Path, car1);
769 followerTestKit.doCommit(writeTx.ready());
771 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
775 @SuppressWarnings("unchecked")
777 public void testReadyLocalTransactionForwardedToLeader() throws Exception {
778 initDatastoresWithCars("testReadyLocalTransactionForwardedToLeader");
779 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
781 final Optional<ActorRef> carsFollowerShard =
782 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
783 assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
785 final DataTree dataTree = new InMemoryDataTreeFactory().create(
786 DataTreeConfiguration.DEFAULT_OPERATIONAL, SchemaContextHelper.full());
788 // Send a tx with immediate commit.
790 DataTreeModification modification = dataTree.takeSnapshot().newModification();
791 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
792 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
794 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
795 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
796 modification.ready();
798 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(tx1 , modification, true, Optional.empty());
800 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
801 Object resp = followerTestKit.expectMsgClass(Object.class);
802 if (resp instanceof akka.actor.Status.Failure) {
803 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
806 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
808 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
810 // Send another tx without immediate commit.
812 modification = dataTree.takeSnapshot().newModification();
813 MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
814 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
815 modification.ready();
817 readyLocal = new ReadyLocalTransaction(tx2 , modification, false, Optional.empty());
819 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
820 resp = followerTestKit.expectMsgClass(Object.class);
821 if (resp instanceof akka.actor.Status.Failure) {
822 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
825 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
827 final ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
828 ((ReadyTransactionReply)resp).getCohortPath());
830 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(leaderDistributedDataStore.getActorUtils(),
831 List.of(new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor),
832 () -> DataStoreVersions.CURRENT_VERSION)), tx2);
833 cohort.canCommit().get(5, TimeUnit.SECONDS);
834 cohort.preCommit().get(5, TimeUnit.SECONDS);
835 cohort.commit().get(5, TimeUnit.SECONDS);
837 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
840 @SuppressWarnings("unchecked")
842 public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
843 initDatastoresWithCars("testForwardedReadyTransactionForwardedToLeader");
844 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
846 final Optional<ActorRef> carsFollowerShard =
847 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
848 assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
850 carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
851 final DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
853 // Send a tx with immediate commit.
855 DataTreeModification modification = dataTree.takeSnapshot().newModification();
856 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
857 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
859 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
860 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
862 ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction(tx1, DataStoreVersions.CURRENT_VERSION,
863 new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx1, modification),
864 true, Optional.empty());
866 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
867 Object resp = followerTestKit.expectMsgClass(Object.class);
868 if (resp instanceof akka.actor.Status.Failure) {
869 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
872 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
874 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
876 // Send another tx without immediate commit.
878 modification = dataTree.takeSnapshot().newModification();
879 MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
880 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
882 forwardedReady = new ForwardedReadyTransaction(tx2, DataStoreVersions.CURRENT_VERSION,
883 new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx2, modification),
884 false, Optional.empty());
886 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
887 resp = followerTestKit.expectMsgClass(Object.class);
888 if (resp instanceof akka.actor.Status.Failure) {
889 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
892 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
894 ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
895 ((ReadyTransactionReply)resp).getCohortPath());
897 final ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
898 leaderDistributedDataStore.getActorUtils(), List.of(
899 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor),
900 () -> DataStoreVersions.CURRENT_VERSION)), tx2);
901 cohort.canCommit().get(5, TimeUnit.SECONDS);
902 cohort.preCommit().get(5, TimeUnit.SECONDS);
903 cohort.commit().get(5, TimeUnit.SECONDS);
905 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
909 public void testTransactionForwardedToLeaderAfterRetry() throws Exception {
910 // FIXME: remove when test passes also for ClientBackedDataStore
911 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
913 followerDatastoreContextBuilder.shardBatchedModificationCount(2);
914 leaderDatastoreContextBuilder.shardBatchedModificationCount(2);
915 initDatastoresWithCarsAndPeople("testTransactionForwardedToLeaderAfterRetry");
917 // Do an initial write to get the primary shard info cached.
919 final DOMStoreWriteTransaction initialWriteTx = followerDistributedDataStore.newWriteOnlyTransaction();
920 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
921 initialWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
922 followerTestKit.doCommit(initialWriteTx.ready());
924 // Wait for the commit to be replicated to the follower.
926 MemberNode.verifyRaftState(followerDistributedDataStore, "cars",
927 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
929 MemberNode.verifyRaftState(followerDistributedDataStore, "people",
930 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
932 // Prepare, ready and canCommit a WO tx that writes to 2 shards. This will become the current tx in
935 final DOMStoreWriteTransaction writeTx1 = followerDistributedDataStore.newWriteOnlyTransaction();
936 writeTx1.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
937 writeTx1.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
938 final DOMStoreThreePhaseCommitCohort writeTx1Cohort = writeTx1.ready();
939 final ListenableFuture<Boolean> writeTx1CanCommit = writeTx1Cohort.canCommit();
940 writeTx1CanCommit.get(5, TimeUnit.SECONDS);
942 // Prepare and ready another WO tx that writes to 2 shards but don't canCommit yet. This will be queued
943 // in the leader shard.
945 final DOMStoreWriteTransaction writeTx2 = followerDistributedDataStore.newWriteOnlyTransaction();
946 final LinkedList<MapEntryNode> cars = new LinkedList<>();
948 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
949 writeTx2.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
951 NormalizedNode people = ImmutableNodes.mapNodeBuilder(PeopleModel.PERSON_QNAME)
952 .withChild(PeopleModel.newPersonEntry("Dude")).build();
953 writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
954 final DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
956 // Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
957 // tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
958 // leader shard (with shardBatchedModificationCount set to 2). The 3rd BatchedModidifications will be
961 final DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
962 for (int i = 1; i <= 5; i++, carIndex++) {
963 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
964 writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
967 // Prepare another WO that writes to a single shard. This will send a single BatchedModidifications
970 final DOMStoreWriteTransaction writeTx4 = followerDistributedDataStore.newWriteOnlyTransaction();
971 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
972 writeTx4.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
975 // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaciton message to the
976 // leader shard on ready.
978 final DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
979 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
980 readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
982 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
983 stats -> assertEquals("getReadWriteTransactionCount", 5, stats.getReadWriteTransactionCount()));
985 // Disable elections on the leader so it switches to follower.
987 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
988 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
989 .shardElectionTimeoutFactor(10));
991 leaderTestKit.waitUntilNoLeader(leaderDistributedDataStore.getActorUtils(), "cars");
993 // Submit all tx's - the messages should get queued for retry.
995 final ListenableFuture<Boolean> writeTx2CanCommit = writeTx2Cohort.canCommit();
996 final DOMStoreThreePhaseCommitCohort writeTx3Cohort = writeTx3.ready();
997 final DOMStoreThreePhaseCommitCohort writeTx4Cohort = writeTx4.ready();
998 final DOMStoreThreePhaseCommitCohort rwTxCohort = readWriteTx.ready();
1000 // Enable elections on the other follower so it becomes the leader, at which point the
1001 // tx's should get forwarded from the previous leader to the new leader to complete the commits.
1003 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1004 .customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
1005 IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorUtils(), "cars")
1006 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
1007 IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorUtils(), "people")
1008 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
1010 followerTestKit.doCommit(writeTx1CanCommit, writeTx1Cohort);
1011 followerTestKit.doCommit(writeTx2CanCommit, writeTx2Cohort);
1012 followerTestKit.doCommit(writeTx3Cohort);
1013 followerTestKit.doCommit(writeTx4Cohort);
1014 followerTestKit.doCommit(rwTxCohort);
1016 DOMStoreReadTransaction readTx = leaderDistributedDataStore.newReadOnlyTransaction();
1017 verifyCars(readTx, cars.toArray(new MapEntryNode[cars.size()]));
1018 verifyNode(readTx, PeopleModel.PERSON_LIST_PATH, people);
1022 public void testLeadershipTransferOnShutdown() throws Exception {
1023 // FIXME: remove when test passes also for ClientBackedDataStore
1024 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1026 leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
1027 followerDatastoreContextBuilder.shardElectionTimeoutFactor(10).customRaftPolicyImplementation(null);
1028 final String testName = "testLeadershipTransferOnShutdown";
1029 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS_AND_PEOPLE);
1031 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1032 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500),
1034 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1035 testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
1037 followerTestKit.waitForMembersUp("member-3");
1038 follower2TestKit.waitForMembersUp("member-1", "member-2");
1040 // Create and submit a couple tx's so they're pending.
1042 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
1043 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1044 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1045 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
1046 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
1048 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1049 stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
1051 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
1052 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
1053 writeTx.write(CarsModel.newCarPath("optima"), car);
1054 final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
1056 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1057 stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
1059 // Gracefully stop the leader via a Shutdown message.
1061 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1062 .shardElectionTimeoutFactor(100));
1064 final FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
1065 final Future<ActorRef> future = leaderDistributedDataStore.getActorUtils().findLocalShardAsync("cars");
1066 final ActorRef leaderActor = Await.result(future, duration);
1068 final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);
1070 // Commit the 2 transactions. They should finish and succeed.
1072 followerTestKit.doCommit(cohort1);
1073 followerTestKit.doCommit(cohort2);
1075 // Wait for the leader actor stopped.
1077 final Boolean stopped = Await.result(stopFuture, duration);
1078 assertEquals("Stopped", Boolean.TRUE, stopped);
1080 // Verify leadership was transferred by reading the committed data from the other nodes.
1082 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
1083 verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
1088 public void testTransactionWithIsolatedLeader() throws Exception {
1089 // FIXME: remove when test passes also for ClientBackedDataStore
1090 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1092 // Set the isolated leader check interval high so we can control the switch to IsolatedLeader.
1093 leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(10000000);
1094 final String testName = "testTransactionWithIsolatedLeader";
1095 initDatastoresWithCars(testName);
1097 // Tx that is submitted after the follower is stopped but before the leader transitions to IsolatedLeader.
1098 final DOMStoreWriteTransaction preIsolatedLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1099 preIsolatedLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1101 // Tx that is submitted after the leader transitions to IsolatedLeader.
1102 final DOMStoreWriteTransaction noShardLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1103 noShardLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1105 // Tx that is submitted after the follower is reinstated.
1106 final DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1107 successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1109 // Stop the follower
1110 followerTestKit.watch(followerDistributedDataStore.getActorUtils().getShardManager());
1111 followerDistributedDataStore.close();
1112 followerTestKit.expectTerminated(followerDistributedDataStore.getActorUtils().getShardManager());
1114 // Submit the preIsolatedLeaderWriteTx so it's pending
1115 final DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
1117 // Change the isolated leader check interval low so it changes to IsolatedLeader.
1118 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1119 .shardIsolatedLeaderCheckIntervalInMillis(200));
1121 MemberNode.verifyRaftState(leaderDistributedDataStore, "cars",
1122 raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
1124 final var ex = assertThrows(ExecutionException.class,
1125 () -> leaderTestKit.doCommit(noShardLeaderWriteTx.ready()));
1126 assertEquals(NoShardLeaderException.class, Throwables.getRootCause(ex).getClass());
1128 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1129 .shardElectionTimeoutFactor(100));
1131 final DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
1133 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
1134 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
1136 leaderTestKit.doCommit(preIsolatedLeaderTxCohort);
1137 leaderTestKit.doCommit(successTxCohort);
1141 public void testTransactionWithShardLeaderNotResponding() throws Exception {
1142 followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1143 followerDatastoreContextBuilder.shardElectionTimeoutFactor(50);
1144 initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
1146 // Do an initial read to get the primary shard info cached.
1148 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1149 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1151 // Shutdown the leader and try to create a new tx.
1153 TestKit.shutdownActorSystem(leaderSystem, true);
1155 followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
1156 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
1158 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1160 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1162 final var ex = assertThrows(ExecutionException.class, () -> followerTestKit.doCommit(rwTx.ready()));
1163 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause());
1164 if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
1165 assertTrue(msg, Throwables.getRootCause(ex) instanceof NoShardLeaderException
1166 || ex.getCause() instanceof ShardLeaderNotRespondingException);
1168 assertThat(msg, Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
1173 public void testTransactionWithCreateTxFailureDueToNoLeader() throws Exception {
1174 followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1175 initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
1177 // Do an initial read to get the primary shard info cached.
1179 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1180 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1182 // Shutdown the leader and try to create a new tx.
1184 TestKit.shutdownActorSystem(leaderSystem, true);
1186 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1188 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
1190 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1191 .operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1193 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1195 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1197 final var ex = assertThrows(ExecutionException.class, () -> followerTestKit.doCommit(rwTx.ready()));
1198 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause());
1199 if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
1200 assertThat(msg, Throwables.getRootCause(ex), instanceOf(NoShardLeaderException.class));
1202 assertThat(msg, Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
1207 public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
1208 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
1209 String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
1210 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1212 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1213 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1214 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1215 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1217 try (AbstractDataStore ds =
1218 follower2TestKit.setupAbstractDataStore(
1219 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS)) {
1221 followerTestKit.waitForMembersUp("member-1", "member-3");
1222 follower2TestKit.waitForMembersUp("member-1", "member-2");
1224 // Do an initial read to get the primary shard info cached.
1226 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1227 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1229 // Shutdown the leader and try to create a new tx.
1231 TestKit.shutdownActorSystem(leaderSystem, true);
1233 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1235 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1236 .operationTimeoutInMillis(500).shardElectionTimeoutFactor(5).customRaftPolicyImplementation(null));
1238 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1240 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1242 followerTestKit.doCommit(rwTx.ready());
1247 public void testSemiReachableCandidateNotDroppingLeader() throws Exception {
1248 final String testName = "testSemiReachableCandidateNotDroppingLeader";
1249 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1251 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1252 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1253 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1254 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1256 final AbstractDataStore ds2 =
1257 follower2TestKit.setupAbstractDataStore(
1258 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS);
1260 followerTestKit.waitForMembersUp("member-1", "member-3");
1261 follower2TestKit.waitForMembersUp("member-1", "member-2");
1263 // behavior is controlled by akka.coordinated-shutdown.run-by-actor-system-terminate configuration option
1264 TestKit.shutdownActorSystem(follower2System, true);
1266 ActorRef cars = leaderDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1267 final OnDemandRaftState initialState = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1268 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1270 Cluster leaderCluster = Cluster.get(leaderSystem);
1271 Cluster followerCluster = Cluster.get(followerSystem);
1272 Cluster follower2Cluster = Cluster.get(follower2System);
1274 Member follower2Member = follower2Cluster.readView().self();
1276 await().atMost(10, TimeUnit.SECONDS)
1277 .until(() -> leaderCluster.readView().unreachableMembers().contains(follower2Member));
1278 await().atMost(10, TimeUnit.SECONDS)
1279 .until(() -> followerCluster.readView().unreachableMembers().contains(follower2Member));
1281 ActorRef followerCars = followerDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1283 // to simulate a follower not being able to receive messages, but still being able to send messages and becoming
1284 // candidate, we can just send a couple of RequestVotes to both leader and follower.
1285 cars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1286 followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1287 cars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1288 followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1290 OnDemandRaftState stateAfter = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1291 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1292 OnDemandRaftState followerState = (OnDemandRaftState) followerDistributedDataStore.getActorUtils()
1293 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1295 assertEquals(initialState.getCurrentTerm(), stateAfter.getCurrentTerm());
1296 assertEquals(initialState.getCurrentTerm(), followerState.getCurrentTerm());
1302 public void testInstallSnapshot() throws Exception {
1303 final String testName = "testInstallSnapshot";
1304 final String leaderCarShardName = "member-1-shard-cars-" + testName;
1305 final String followerCarShardName = "member-2-shard-cars-" + testName;
1307 // Setup a saved snapshot on the leader. The follower will startup with no data and the leader should
1308 // install a snapshot to sync the follower.
1310 DataTree tree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_CONFIGURATION,
1311 SchemaContextHelper.full());
1313 final ContainerNode carsNode = CarsModel.newCarsNode(
1314 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", Uint64.valueOf(20000))));
1315 AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
1317 final NormalizedNode snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.empty());
1318 final Snapshot initialSnapshot = Snapshot.create(
1319 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
1320 Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
1321 InMemorySnapshotStore.addSnapshot(leaderCarShardName, initialSnapshot);
1323 InMemorySnapshotStore.addSnapshotSavedLatch(leaderCarShardName);
1324 InMemorySnapshotStore.addSnapshotSavedLatch(followerCarShardName);
1326 initDatastoresWithCars(testName);
1328 assertEquals(Optional.of(carsNode), leaderDistributedDataStore.newReadOnlyTransaction().read(
1329 CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS));
1331 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(leaderCarShardName, Snapshot.class),
1332 initialSnapshot, snapshotRoot);
1334 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(followerCarShardName, Snapshot.class),
1335 initialSnapshot, snapshotRoot);
1339 public void testReadWriteMessageSlicing() throws Exception {
1340 // The slicing is only implemented for tell-based protocol
1341 assumeTrue(ClientBackedDataStore.class.isAssignableFrom(testParameter));
1343 leaderDatastoreContextBuilder.maximumMessageSliceSize(100);
1344 followerDatastoreContextBuilder.maximumMessageSliceSize(100);
1345 initDatastoresWithCars("testLargeReadReplySlicing");
1347 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1349 final NormalizedNode carsNode = CarsModel.create();
1350 rwTx.write(CarsModel.BASE_PATH, carsNode);
1352 verifyNode(rwTx, CarsModel.BASE_PATH, carsNode);
1355 @SuppressWarnings("IllegalCatch")
1357 public void testRaftCallbackDuringLeadershipDrop() throws Exception {
1358 final String testName = "testRaftCallbackDuringLeadershipDrop";
1359 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1361 final ExecutorService executor = Executors.newSingleThreadExecutor();
1363 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1364 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500)
1365 .shardLeaderElectionTimeoutInSeconds(3600),
1368 final DOMStoreWriteTransaction initialWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1369 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1370 leaderTestKit.doCommit(initialWriteTx.ready());
1372 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1373 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false)) {
1375 final ActorRef member3Cars = ((LocalShardStore) follower2DistributedDataStore).getLocalShards()
1376 .getLocalShards().get("cars").getActor();
1377 final ActorRef member2Cars = ((LocalShardStore)followerDistributedDataStore).getLocalShards()
1378 .getLocalShards().get("cars").getActor();
1379 member2Cars.tell(new StartDropMessages(AppendEntries.class), null);
1380 member3Cars.tell(new StartDropMessages(AppendEntries.class), null);
1382 final DOMStoreWriteTransaction newTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1383 newTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1384 final AtomicBoolean submitDone = new AtomicBoolean(false);
1385 executor.submit(() -> {
1387 leaderTestKit.doCommit(newTx.ready());
1388 submitDone.set(true);
1389 } catch (Exception e) {
1390 throw new RuntimeException(e);
1393 final ActorRef leaderCars = ((LocalShardStore) leaderDistributedDataStore).getLocalShards()
1394 .getLocalShards().get("cars").getActor();
1395 await().atMost(10, TimeUnit.SECONDS)
1396 .until(() -> ((OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1397 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE)).getLastIndex() >= 1);
1399 final OnDemandRaftState raftState = (OnDemandRaftState)leaderDistributedDataStore.getActorUtils()
1400 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE);
1402 // Simulate a follower not receiving heartbeats but still being able to send messages ie RequestVote with
1403 // new term(switching to candidate after election timeout)
1404 leaderCars.tell(new RequestVote(raftState.getCurrentTerm() + 1,
1405 "member-3-shard-cars-testRaftCallbackDuringLeadershipDrop", -1,
1408 member2Cars.tell(new StopDropMessages(AppendEntries.class), null);
1409 member3Cars.tell(new StopDropMessages(AppendEntries.class), null);
1411 await("Is tx stuck in COMMIT_PENDING")
1412 .atMost(10, TimeUnit.SECONDS).untilAtomic(submitDone, equalTo(true));
1416 executor.shutdownNow();
1420 public void testSnapshotOnRootOverwrite() throws Exception {
1421 // FIXME: ClientBackedDatastore does not have stable indexes/term, the snapshot index seems to fluctuate
1422 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1424 final String testName = "testSnapshotOnRootOverwrite";
1425 final String[] shards = {"cars", "default"};
1426 initDatastores(testName, "module-shards-default-cars-member1-and-2.conf", shards,
1427 leaderDatastoreContextBuilder.snapshotOnRootOverwrite(true),
1428 followerDatastoreContextBuilder.snapshotOnRootOverwrite(true));
1430 leaderTestKit.waitForMembersUp("member-2");
1431 final ContainerNode rootNode = ImmutableContainerNodeBuilder.create()
1432 .withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(SchemaContext.NAME))
1433 .withChild(CarsModel.create())
1436 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1438 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1439 state -> assertEquals(1, state.getSnapshotIndex()));
1441 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1442 state -> assertEquals(1, state.getSnapshotIndex()));
1444 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1445 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1447 for (int i = 0; i < 10; i++) {
1448 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, CarsModel.newCarPath("car " + i),
1449 CarsModel.newCarEntry("car " + i, Uint64.ONE));
1452 // fake snapshot causes the snapshotIndex to move
1453 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1454 state -> assertEquals(10, state.getSnapshotIndex()));
1455 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1456 state -> assertEquals(10, state.getSnapshotIndex()));
1458 // however the real snapshot still has not changed and was taken at index 1
1459 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1460 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1462 // root overwrite so expect a snapshot
1463 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1465 // this was a real snapshot so everything should be in it(1(DisableTrackingPayload) + 1 + 10 + 1)
1466 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1467 state -> assertEquals(12, state.getSnapshotIndex()));
1468 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1469 state -> assertEquals(12, state.getSnapshotIndex()));
1471 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 12);
1472 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 12);
1475 private void verifySnapshot(final String persistenceId, final long lastAppliedIndex) {
1476 await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
1477 List<Snapshot> snap = InMemorySnapshotStore.getSnapshots(persistenceId, Snapshot.class);
1478 assertEquals(1, snap.size());
1479 assertEquals(lastAppliedIndex, snap.get(0).getLastAppliedIndex());
1484 private static void verifySnapshot(final Snapshot actual, final Snapshot expected,
1485 final NormalizedNode expRoot) {
1486 assertEquals("Snapshot getLastAppliedTerm", expected.getLastAppliedTerm(), actual.getLastAppliedTerm());
1487 assertEquals("Snapshot getLastAppliedIndex", expected.getLastAppliedIndex(), actual.getLastAppliedIndex());
1488 assertEquals("Snapshot getLastTerm", expected.getLastTerm(), actual.getLastTerm());
1489 assertEquals("Snapshot getLastIndex", expected.getLastIndex(), actual.getLastIndex());
1490 assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
1491 MetadataShardDataTreeSnapshot shardSnapshot =
1492 (MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
1493 assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
1496 private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1497 final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1498 final DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
1499 final Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1500 doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1501 doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(anyString());
1502 dataStore.onDatastoreContextUpdated(mockContextFactory);