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.containsString;
12 import static org.hamcrest.CoreMatchers.instanceOf;
13 import static org.hamcrest.MatcherAssert.assertThat;
14 import static org.hamcrest.Matchers.equalTo;
15 import static org.junit.Assert.assertEquals;
16 import static org.junit.Assert.assertFalse;
17 import static org.junit.Assert.assertNotNull;
18 import static org.junit.Assert.assertThrows;
19 import static org.junit.Assert.assertTrue;
20 import static org.junit.Assume.assumeTrue;
21 import static org.mockito.ArgumentMatchers.any;
22 import static org.mockito.ArgumentMatchers.anyString;
23 import static org.mockito.ArgumentMatchers.eq;
24 import static org.mockito.Mockito.doAnswer;
25 import static org.mockito.Mockito.mock;
26 import static org.mockito.Mockito.timeout;
27 import static org.mockito.Mockito.verify;
29 import akka.actor.ActorRef;
30 import akka.actor.ActorSelection;
31 import akka.actor.ActorSystem;
32 import akka.actor.Address;
33 import akka.actor.AddressFromURIString;
34 import akka.cluster.Cluster;
35 import akka.cluster.Member;
36 import akka.dispatch.Futures;
37 import akka.pattern.Patterns;
38 import akka.testkit.javadsl.TestKit;
39 import com.google.common.base.Stopwatch;
40 import com.google.common.base.Throwables;
41 import com.google.common.collect.ImmutableMap;
42 import com.google.common.util.concurrent.ListenableFuture;
43 import com.google.common.util.concurrent.MoreExecutors;
44 import com.google.common.util.concurrent.Uninterruptibles;
45 import com.typesafe.config.ConfigFactory;
46 import java.util.Arrays;
47 import java.util.Collection;
48 import java.util.Collections;
49 import java.util.LinkedList;
50 import java.util.List;
51 import java.util.Optional;
52 import java.util.concurrent.ExecutionException;
53 import java.util.concurrent.ExecutorService;
54 import java.util.concurrent.Executors;
55 import java.util.concurrent.TimeUnit;
56 import java.util.concurrent.atomic.AtomicBoolean;
57 import java.util.concurrent.atomic.AtomicLong;
58 import org.junit.After;
59 import org.junit.Before;
60 import org.junit.Test;
61 import org.junit.runner.RunWith;
62 import org.junit.runners.Parameterized;
63 import org.junit.runners.Parameterized.Parameter;
64 import org.junit.runners.Parameterized.Parameters;
65 import org.mockito.stubbing.Answer;
66 import org.opendaylight.controller.cluster.access.client.RequestTimeoutException;
67 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
68 import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
69 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
70 import org.opendaylight.controller.cluster.databroker.TestClientBackedDataStore;
71 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
72 import org.opendaylight.controller.cluster.datastore.TestShard.RequestFrontendMetadata;
73 import org.opendaylight.controller.cluster.datastore.TestShard.StartDropMessages;
74 import org.opendaylight.controller.cluster.datastore.TestShard.StopDropMessages;
75 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
76 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
77 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
78 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
79 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
80 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
81 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
82 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
83 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
84 import org.opendaylight.controller.cluster.datastore.persisted.FrontendClientMetadata;
85 import org.opendaylight.controller.cluster.datastore.persisted.FrontendShardDataTreeSnapshotMetadata;
86 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
87 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
88 import org.opendaylight.controller.cluster.datastore.utils.UnsignedLongBitmap;
89 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
90 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
91 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
92 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
93 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
94 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
95 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
96 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
97 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
98 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
99 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
100 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
101 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
102 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
103 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
104 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
105 import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
106 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
107 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
108 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
109 import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
110 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
111 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
112 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
113 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
114 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
115 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
116 import org.opendaylight.yangtools.yang.common.Uint64;
117 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
118 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
119 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
120 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
121 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
122 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
123 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
124 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
125 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
126 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
127 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
128 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
129 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
130 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
131 import scala.collection.Set;
132 import scala.concurrent.Await;
133 import scala.concurrent.Future;
134 import scala.concurrent.duration.FiniteDuration;
137 * End-to-end distributed data store tests that exercise remote shards and transactions.
139 * @author Thomas Pantelis
141 @RunWith(Parameterized.class)
142 public class DistributedDataStoreRemotingIntegrationTest extends AbstractTest {
144 @Parameters(name = "{0}")
145 public static Collection<Object[]> data() {
146 return Arrays.asList(new Object[][] {
147 { TestDistributedDataStore.class, 7 }, { TestClientBackedDataStore.class, 12 }
152 public Class<? extends AbstractDataStore> testParameter;
154 public int commitTimeout;
156 private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
157 private static final String[] CARS = {"cars"};
159 private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse(
160 "akka://cluster-test@127.0.0.1:2558");
161 private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse(
162 "akka://cluster-test@127.0.0.1:2559");
164 private static final String MODULE_SHARDS_CARS_ONLY_1_2 = "module-shards-cars-member-1-and-2.conf";
165 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2 = "module-shards-member1-and-2.conf";
166 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2_3 = "module-shards-member1-and-2-and-3.conf";
167 private static final String MODULE_SHARDS_CARS_1_2_3 = "module-shards-cars-member-1-and-2-and-3.conf";
169 private ActorSystem leaderSystem;
170 private ActorSystem followerSystem;
171 private ActorSystem follower2System;
173 private final DatastoreContext.Builder leaderDatastoreContextBuilder =
174 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
176 private final DatastoreContext.Builder followerDatastoreContextBuilder =
177 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5)
178 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
179 private final TransactionIdentifier tx1 = nextTransactionId();
180 private final TransactionIdentifier tx2 = nextTransactionId();
182 private AbstractDataStore followerDistributedDataStore;
183 private AbstractDataStore leaderDistributedDataStore;
184 private IntegrationTestKit followerTestKit;
185 private IntegrationTestKit leaderTestKit;
188 public void setUp() {
189 InMemoryJournal.clear();
190 InMemorySnapshotStore.clear();
192 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
193 Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
195 followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
196 Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
198 follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
199 Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
203 public void tearDown() {
204 if (followerDistributedDataStore != null) {
205 leaderDistributedDataStore.close();
207 if (leaderDistributedDataStore != null) {
208 leaderDistributedDataStore.close();
211 TestKit.shutdownActorSystem(leaderSystem);
212 TestKit.shutdownActorSystem(followerSystem);
213 TestKit.shutdownActorSystem(follower2System);
215 InMemoryJournal.clear();
216 InMemorySnapshotStore.clear();
219 private void initDatastoresWithCars(final String type) throws Exception {
220 initDatastores(type, MODULE_SHARDS_CARS_ONLY_1_2, CARS);
223 private void initDatastoresWithCarsAndPeople(final String type) throws Exception {
224 initDatastores(type, MODULE_SHARDS_CARS_PEOPLE_1_2, CARS_AND_PEOPLE);
227 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards)
229 initDatastores(type, moduleShardsConfig, shards, leaderDatastoreContextBuilder,
230 followerDatastoreContextBuilder);
233 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards,
234 final DatastoreContext.Builder leaderBuilder, final DatastoreContext.Builder followerBuilder)
236 leaderTestKit = new IntegrationTestKit(leaderSystem, leaderBuilder, commitTimeout);
238 leaderDistributedDataStore = leaderTestKit.setupAbstractDataStore(
239 testParameter, type, moduleShardsConfig, false, shards);
241 followerTestKit = new IntegrationTestKit(followerSystem, followerBuilder, commitTimeout);
242 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
243 testParameter, type, moduleShardsConfig, false, shards);
245 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorUtils(), shards);
247 leaderTestKit.waitForMembersUp("member-2");
248 followerTestKit.waitForMembersUp("member-1");
251 private static void verifyCars(final DOMStoreReadTransaction readTx, final MapEntryNode... entries)
253 final Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
254 assertTrue("isPresent", optional.isPresent());
256 final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(
257 CarsModel.CAR_QNAME);
258 for (final NormalizedNode<?, ?> entry: entries) {
259 listBuilder.withChild((MapEntryNode) entry);
262 assertEquals("Car list node", listBuilder.build(), optional.get());
265 private static void verifyNode(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path,
266 final NormalizedNode<?, ?> expNode) throws Exception {
267 assertEquals(Optional.of(expNode), readTx.read(path).get(5, TimeUnit.SECONDS));
270 private static void verifyExists(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path)
272 assertEquals("exists", Boolean.TRUE, readTx.exists(path).get(5, TimeUnit.SECONDS));
276 public void testWriteTransactionWithSingleShard() throws Exception {
277 final String testName = "testWriteTransactionWithSingleShard";
278 initDatastoresWithCars(testName);
280 final String followerCarShardName = "member-2-shard-cars-" + testName;
282 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
283 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
285 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
286 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
288 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
289 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
290 writeTx.merge(car1Path, car1);
292 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
293 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
294 writeTx.merge(car2Path, car2);
296 followerTestKit.doCommit(writeTx.ready());
298 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
300 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
304 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
306 writeTx.delete(car1Path);
308 followerTestKit.doCommit(writeTx.ready());
310 verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
312 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
314 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
316 // Re-instate the follower member 2 as a single-node to verify replication and recovery.
318 // The following is a bit tricky. Before we reinstate the follower we need to ensure it has persisted and
319 // applied and all the log entries from the leader. Since we've verified the car data above we know that
320 // all the transactions have been applied on the leader so we first read and capture its lastAppliedIndex.
321 final AtomicLong leaderLastAppliedIndex = new AtomicLong();
322 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, CARS[0],
323 state -> leaderLastAppliedIndex.set(state.getLastApplied()));
325 // Now we need to make sure the follower has persisted the leader's lastAppliedIndex via ApplyJournalEntries.
326 // However we don't know exactly how many ApplyJournalEntries messages there will be as it can differ between
327 // the tell-based and ask-based front-ends. For ask-based there will be exactly 2 ApplyJournalEntries but
328 // tell-based persists additional payloads which could be replicated and applied in a batch resulting in
329 // either 2 or 3 ApplyJournalEntries. To handle this we read the follower's persisted ApplyJournalEntries
330 // until we find the one that encompasses the leader's lastAppliedIndex.
331 Stopwatch sw = Stopwatch.createStarted();
332 boolean done = false;
334 final List<ApplyJournalEntries> entries = InMemoryJournal.get(followerCarShardName,
335 ApplyJournalEntries.class);
336 for (ApplyJournalEntries aje: entries) {
337 if (aje.getToIndex() >= leaderLastAppliedIndex.get()) {
343 assertTrue("Follower did not persist ApplyJournalEntries containing leader's lastAppliedIndex "
344 + leaderLastAppliedIndex + ". Entries persisted: " + entries, sw.elapsed(TimeUnit.SECONDS) <= 5);
346 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
349 TestKit.shutdownActorSystem(leaderSystem, true);
350 TestKit.shutdownActorSystem(followerSystem, true);
352 final ActorSystem newSystem = newActorSystem("reinstated-member2", "Member2");
354 try (AbstractDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder,
356 .setupAbstractDataStore(testParameter, testName, "module-shards-member2", true, CARS)) {
357 verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
362 public void testSingleTransactionsWritesInQuickSuccession() throws Exception {
363 initDatastoresWithCars("testSingleTransactionsWritesInQuickSuccession");
365 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
367 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
368 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
369 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
370 followerTestKit.doCommit(writeTx.ready());
373 for (int i = 0; i < numCars; i++) {
374 writeTx = txChain.newWriteOnlyTransaction();
375 writeTx.write(CarsModel.newCarPath("car" + i), CarsModel.newCarEntry("car" + i, Uint64.valueOf(20000)));
376 followerTestKit.doCommit(writeTx.ready());
378 try (var tx = txChain.newReadOnlyTransaction()) {
379 tx.read(CarsModel.BASE_PATH).get();
383 // wait to let the shard catch up with purged
384 await("Range set leak test").atMost(5, TimeUnit.SECONDS)
385 .pollInterval(500, TimeUnit.MILLISECONDS)
386 .untilAsserted(() -> {
387 final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars")
389 final var frontendMetadata =
390 (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
391 .executeOperation(localShard, new RequestFrontendMetadata());
393 final var clientMeta = frontendMetadata.getClients().get(0);
394 if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
395 assertTellClientMetadata(clientMeta, numCars * 2);
397 assertAskClientMetadata(clientMeta);
401 try (var tx = txChain.newReadOnlyTransaction()) {
402 final var body = tx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS).orElseThrow().getValue();
403 assertThat(body, instanceOf(Collection.class));
404 assertEquals(numCars, ((Collection<?>) body).size());
408 private static void assertAskClientMetadata(final FrontendClientMetadata clientMeta) {
409 // ask based should track no metadata
410 assertEquals(List.of(), clientMeta.getCurrentHistories());
413 private static void assertTellClientMetadata(final FrontendClientMetadata clientMeta, final long lastPurged) {
414 final var iterator = clientMeta.getCurrentHistories().iterator();
415 var metadata = iterator.next();
416 while (iterator.hasNext() && metadata.getHistoryId() != 1) {
417 metadata = iterator.next();
420 assertEquals(UnsignedLongBitmap.of(), metadata.getClosedTransactions());
421 assertEquals("[[0.." + lastPurged + "]]", metadata.getPurgedTransactions().ranges().toString());
425 public void testCloseTransactionMetadataLeak() throws Exception {
426 // FIXME: Ask-based frontend seems to have some issues with back to back close
427 assumeTrue(testParameter.isAssignableFrom(TestClientBackedDataStore.class));
429 initDatastoresWithCars("testCloseTransactionMetadataLeak");
431 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
433 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
434 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
435 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
436 followerTestKit.doCommit(writeTx.ready());
439 for (int i = 0; i < numCars; i++) {
440 try (var tx = txChain.newWriteOnlyTransaction()) {
444 try (var tx = txChain.newReadOnlyTransaction()) {
445 tx.read(CarsModel.BASE_PATH).get();
449 // wait to let the shard catch up with purged
450 await("wait for purges to settle").atMost(5, TimeUnit.SECONDS)
451 .pollInterval(500, TimeUnit.MILLISECONDS)
452 .untilAsserted(() -> {
453 final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars")
455 final var frontendMetadata =
456 (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
457 .executeOperation(localShard, new RequestFrontendMetadata());
459 final var clientMeta = frontendMetadata.getClients().get(0);
460 if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
461 assertTellClientMetadata(clientMeta, numCars * 2);
463 assertAskClientMetadata(clientMeta);
469 public void testReadWriteTransactionWithSingleShard() throws Exception {
470 initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
472 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
473 assertNotNull("newReadWriteTransaction returned null", rwTx);
475 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
476 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
478 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
479 rwTx.merge(CarsModel.newCarPath("optima"), car1);
481 verifyCars(rwTx, car1);
483 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
484 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
485 rwTx.merge(car2Path, car2);
487 verifyExists(rwTx, car2Path);
489 followerTestKit.doCommit(rwTx.ready());
491 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
495 public void testWriteTransactionWithMultipleShards() throws Exception {
496 initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
498 final DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
499 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
501 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
502 final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
503 writeTx.write(carsPath, carsNode);
505 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
506 final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
507 writeTx.write(peoplePath, peopleNode);
509 followerTestKit.doCommit(writeTx.ready());
511 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
513 verifyNode(readTx, carsPath, carsNode);
514 verifyNode(readTx, peoplePath, peopleNode);
518 public void testReadWriteTransactionWithMultipleShards() throws Exception {
519 initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
521 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
522 assertNotNull("newReadWriteTransaction returned null", rwTx);
524 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
525 final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
526 rwTx.write(carsPath, carsNode);
528 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
529 final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
530 rwTx.write(peoplePath, peopleNode);
532 followerTestKit.doCommit(rwTx.ready());
534 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
536 verifyNode(readTx, carsPath, carsNode);
537 verifyNode(readTx, peoplePath, peopleNode);
541 public void testTransactionChainWithSingleShard() throws Exception {
542 initDatastoresWithCars("testTransactionChainWithSingleShard");
544 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
546 // Add the top-level cars container with write-only.
548 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
549 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
551 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
553 final DOMStoreThreePhaseCommitCohort writeTxReady = writeTx.ready();
555 // Verify the top-level cars container with read-only.
557 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
559 // Perform car operations with read-write.
561 final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
563 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
565 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
567 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
568 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
569 rwTx.write(car1Path, car1);
571 verifyExists(rwTx, car1Path);
573 verifyCars(rwTx, car1);
575 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
576 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
578 rwTx.delete(car1Path);
580 followerTestKit.doCommit(writeTxReady);
582 followerTestKit.doCommit(rwTx.ready());
586 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
590 public void testTransactionChainWithMultipleShards() throws Exception {
591 initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
593 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
595 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
596 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
598 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
599 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
601 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
602 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
604 followerTestKit.doCommit(writeTx.ready());
606 final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
608 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
609 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
610 readWriteTx.write(carPath, car);
612 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
613 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
614 readWriteTx.merge(personPath, person);
616 assertEquals(Optional.of(car), readWriteTx.read(carPath).get(5, TimeUnit.SECONDS));
617 assertEquals(Optional.of(person), readWriteTx.read(personPath).get(5, TimeUnit.SECONDS));
619 final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
621 writeTx = txChain.newWriteOnlyTransaction();
623 writeTx.delete(personPath);
625 final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
627 followerTestKit.doCommit(cohort2);
628 followerTestKit.doCommit(cohort3);
632 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
633 verifyCars(readTx, car);
635 assertEquals(Optional.empty(), readTx.read(personPath).get(5, TimeUnit.SECONDS));
639 public void testChainedTransactionFailureWithSingleShard() throws Exception {
640 initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
642 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
643 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
644 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
645 MoreExecutors.directExecutor());
647 final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
648 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
650 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
652 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
653 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
654 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
656 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
658 final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
660 assertThat(ex, instanceOf(TransactionCommitFailedException.class));
662 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
669 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
670 initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
672 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
673 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
674 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
675 MoreExecutors.directExecutor());
677 final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
678 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
680 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
682 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
684 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
685 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
686 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
688 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
689 // done for put for performance reasons.
690 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
692 final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
694 assertThat(ex, instanceOf(TransactionCommitFailedException.class));
696 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
703 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
704 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
705 final String testName = "testSingleShardTransactionsWithLeaderChanges";
706 initDatastoresWithCars(testName);
708 final String followerCarShardName = "member-2-shard-cars-" + testName;
709 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class);
711 // Write top-level car container from the follower so it uses a remote Tx.
713 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
715 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
716 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
718 followerTestKit.doCommit(writeTx.ready());
720 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
722 // Switch the leader to the follower
724 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
725 .shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
727 TestKit.shutdownActorSystem(leaderSystem, true);
728 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
730 followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorUtils(), CARS);
732 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
733 Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
735 final DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder()
736 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
737 IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder, commitTimeout);
739 try (AbstractDataStore ds =
740 newMember1TestKit.setupAbstractDataStore(
741 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS)) {
743 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), CARS);
745 // Write a car entry to the new leader - should switch to local Tx
747 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
749 MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
750 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
751 writeTx.merge(car1Path, car1);
753 followerTestKit.doCommit(writeTx.ready());
755 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
759 @SuppressWarnings("unchecked")
761 public void testReadyLocalTransactionForwardedToLeader() throws Exception {
762 initDatastoresWithCars("testReadyLocalTransactionForwardedToLeader");
763 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
765 final Optional<ActorRef> carsFollowerShard =
766 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
767 assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
769 final DataTree dataTree = new InMemoryDataTreeFactory().create(
770 DataTreeConfiguration.DEFAULT_OPERATIONAL, SchemaContextHelper.full());
772 // Send a tx with immediate commit.
774 DataTreeModification modification = dataTree.takeSnapshot().newModification();
775 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
776 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
778 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
779 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
780 modification.ready();
782 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(tx1 , modification, true, Optional.empty());
784 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
785 Object resp = followerTestKit.expectMsgClass(Object.class);
786 if (resp instanceof akka.actor.Status.Failure) {
787 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
790 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
792 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
794 // Send another tx without immediate commit.
796 modification = dataTree.takeSnapshot().newModification();
797 MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
798 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
799 modification.ready();
801 readyLocal = new ReadyLocalTransaction(tx2 , modification, false, Optional.empty());
803 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
804 resp = followerTestKit.expectMsgClass(Object.class);
805 if (resp instanceof akka.actor.Status.Failure) {
806 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
809 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
811 final ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
812 ((ReadyTransactionReply)resp).getCohortPath());
814 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(leaderDistributedDataStore.getActorUtils(),
815 List.of(new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor),
816 () -> DataStoreVersions.CURRENT_VERSION)), tx2);
817 cohort.canCommit().get(5, TimeUnit.SECONDS);
818 cohort.preCommit().get(5, TimeUnit.SECONDS);
819 cohort.commit().get(5, TimeUnit.SECONDS);
821 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
824 @SuppressWarnings("unchecked")
826 public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
827 initDatastoresWithCars("testForwardedReadyTransactionForwardedToLeader");
828 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
830 final Optional<ActorRef> carsFollowerShard =
831 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
832 assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
834 carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
835 final DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
837 // Send a tx with immediate commit.
839 DataTreeModification modification = dataTree.takeSnapshot().newModification();
840 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
841 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
843 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
844 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
846 ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction(tx1, DataStoreVersions.CURRENT_VERSION,
847 new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx1, modification),
848 true, Optional.empty());
850 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
851 Object resp = followerTestKit.expectMsgClass(Object.class);
852 if (resp instanceof akka.actor.Status.Failure) {
853 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
856 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
858 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
860 // Send another tx without immediate commit.
862 modification = dataTree.takeSnapshot().newModification();
863 MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
864 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
866 forwardedReady = new ForwardedReadyTransaction(tx2, DataStoreVersions.CURRENT_VERSION,
867 new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx2, modification),
868 false, Optional.empty());
870 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
871 resp = followerTestKit.expectMsgClass(Object.class);
872 if (resp instanceof akka.actor.Status.Failure) {
873 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
876 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
878 ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
879 ((ReadyTransactionReply)resp).getCohortPath());
881 final ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
882 leaderDistributedDataStore.getActorUtils(), List.of(
883 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor),
884 () -> DataStoreVersions.CURRENT_VERSION)), tx2);
885 cohort.canCommit().get(5, TimeUnit.SECONDS);
886 cohort.preCommit().get(5, TimeUnit.SECONDS);
887 cohort.commit().get(5, TimeUnit.SECONDS);
889 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
893 public void testTransactionForwardedToLeaderAfterRetry() throws Exception {
894 followerDatastoreContextBuilder.shardBatchedModificationCount(2);
895 leaderDatastoreContextBuilder.shardBatchedModificationCount(2);
896 initDatastoresWithCarsAndPeople("testTransactionForwardedToLeaderAfterRetry");
898 // Do an initial write to get the primary shard info cached.
900 final DOMStoreWriteTransaction initialWriteTx = followerDistributedDataStore.newWriteOnlyTransaction();
901 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
902 initialWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
903 followerTestKit.doCommit(initialWriteTx.ready());
905 // Wait for the commit to be replicated to the follower.
907 MemberNode.verifyRaftState(followerDistributedDataStore, "cars",
908 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
910 MemberNode.verifyRaftState(followerDistributedDataStore, "people",
911 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
913 // Prepare, ready and canCommit a WO tx that writes to 2 shards. This will become the current tx in
916 final DOMStoreWriteTransaction writeTx1 = followerDistributedDataStore.newWriteOnlyTransaction();
917 writeTx1.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
918 writeTx1.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
919 final DOMStoreThreePhaseCommitCohort writeTx1Cohort = writeTx1.ready();
920 final ListenableFuture<Boolean> writeTx1CanCommit = writeTx1Cohort.canCommit();
921 writeTx1CanCommit.get(5, TimeUnit.SECONDS);
923 // Prepare and ready another WO tx that writes to 2 shards but don't canCommit yet. This will be queued
924 // in the leader shard.
926 final DOMStoreWriteTransaction writeTx2 = followerDistributedDataStore.newWriteOnlyTransaction();
927 final LinkedList<MapEntryNode> cars = new LinkedList<>();
929 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
930 writeTx2.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
932 NormalizedNode<?, ?> people = ImmutableNodes.mapNodeBuilder(PeopleModel.PERSON_QNAME)
933 .withChild(PeopleModel.newPersonEntry("Dude")).build();
934 writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
935 final DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
937 // Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
938 // tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
939 // leader shard (with shardBatchedModificationCount set to 2). The 3rd BatchedModidifications will be
942 final DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
943 for (int i = 1; i <= 5; i++, carIndex++) {
944 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
945 writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
948 // Prepare another WO that writes to a single shard. This will send a single BatchedModidifications
951 final DOMStoreWriteTransaction writeTx4 = followerDistributedDataStore.newWriteOnlyTransaction();
952 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
953 writeTx4.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
956 // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaciton message to the
957 // leader shard on ready.
959 final DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
960 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
961 readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
963 // FIXME: CONTROLLER-2017: ClientBackedDataStore reports only 4 transactions
964 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
965 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
966 stats -> assertEquals("getReadWriteTransactionCount", 5, stats.getReadWriteTransactionCount()));
968 // Disable elections on the leader so it switches to follower.
970 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
971 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
972 .shardElectionTimeoutFactor(10));
974 leaderTestKit.waitUntilNoLeader(leaderDistributedDataStore.getActorUtils(), "cars");
976 // Submit all tx's - the messages should get queued for retry.
978 final ListenableFuture<Boolean> writeTx2CanCommit = writeTx2Cohort.canCommit();
979 final DOMStoreThreePhaseCommitCohort writeTx3Cohort = writeTx3.ready();
980 final DOMStoreThreePhaseCommitCohort writeTx4Cohort = writeTx4.ready();
981 final DOMStoreThreePhaseCommitCohort rwTxCohort = readWriteTx.ready();
983 // Enable elections on the other follower so it becomes the leader, at which point the
984 // tx's should get forwarded from the previous leader to the new leader to complete the commits.
986 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
987 .customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
988 IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorUtils(), "cars")
989 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
990 IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorUtils(), "people")
991 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
993 followerTestKit.doCommit(writeTx1CanCommit, writeTx1Cohort);
994 followerTestKit.doCommit(writeTx2CanCommit, writeTx2Cohort);
995 followerTestKit.doCommit(writeTx3Cohort);
996 followerTestKit.doCommit(writeTx4Cohort);
997 followerTestKit.doCommit(rwTxCohort);
999 DOMStoreReadTransaction readTx = leaderDistributedDataStore.newReadOnlyTransaction();
1000 verifyCars(readTx, cars.toArray(new MapEntryNode[cars.size()]));
1001 verifyNode(readTx, PeopleModel.PERSON_LIST_PATH, people);
1005 public void testLeadershipTransferOnShutdown() throws Exception {
1006 leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
1007 followerDatastoreContextBuilder.shardElectionTimeoutFactor(10).customRaftPolicyImplementation(null);
1008 final String testName = "testLeadershipTransferOnShutdown";
1009 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS_AND_PEOPLE);
1011 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1012 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500),
1014 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1015 testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
1017 followerTestKit.waitForMembersUp("member-3");
1018 follower2TestKit.waitForMembersUp("member-1", "member-2");
1020 // Create and submit a couple tx's so they're pending.
1022 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
1023 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1024 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1025 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
1026 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
1028 final var usesCohorts = DistributedDataStore.class.isAssignableFrom(testParameter);
1030 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1031 stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
1034 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
1035 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
1036 writeTx.write(CarsModel.newCarPath("optima"), car);
1037 final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
1040 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1041 stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
1044 // Gracefully stop the leader via a Shutdown message.
1046 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1047 .shardElectionTimeoutFactor(100));
1049 final FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
1050 final Future<ActorRef> future = leaderDistributedDataStore.getActorUtils().findLocalShardAsync("cars");
1051 final ActorRef leaderActor = Await.result(future, duration);
1053 final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);
1055 // Commit the 2 transactions. They should finish and succeed.
1057 followerTestKit.doCommit(cohort1);
1058 followerTestKit.doCommit(cohort2);
1060 // Wait for the leader actor stopped.
1062 final Boolean stopped = Await.result(stopFuture, duration);
1063 assertEquals("Stopped", Boolean.TRUE, stopped);
1065 // Verify leadership was transferred by reading the committed data from the other nodes.
1067 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
1068 verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
1073 public void testTransactionWithIsolatedLeader() throws Exception {
1074 // Set the isolated leader check interval high so we can control the switch to IsolatedLeader.
1075 leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(10000000);
1076 final String testName = "testTransactionWithIsolatedLeader";
1077 initDatastoresWithCars(testName);
1079 // Tx that is submitted after the follower is stopped but before the leader transitions to IsolatedLeader.
1080 final DOMStoreWriteTransaction preIsolatedLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1081 preIsolatedLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1083 // Tx that is submitted after the leader transitions to IsolatedLeader.
1084 final DOMStoreWriteTransaction noShardLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1085 noShardLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1087 // Tx that is submitted after the follower is reinstated.
1088 final DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1089 successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1091 // Stop the follower
1092 followerTestKit.watch(followerDistributedDataStore.getActorUtils().getShardManager());
1093 followerDistributedDataStore.close();
1094 followerTestKit.expectTerminated(followerDistributedDataStore.getActorUtils().getShardManager());
1096 // Submit the preIsolatedLeaderWriteTx so it's pending
1097 final DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
1099 // Change the isolated leader check interval low so it changes to IsolatedLeader.
1100 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1101 .shardIsolatedLeaderCheckIntervalInMillis(200));
1103 MemberNode.verifyRaftState(leaderDistributedDataStore, "cars",
1104 raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
1106 final var noShardLeaderCohort = noShardLeaderWriteTx.ready();
1107 final ListenableFuture<Boolean> canCommit;
1109 // There is difference in behavior here:
1110 if (!leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
1111 // ask-based canCommit() times out and aborts
1112 final var ex = assertThrows(ExecutionException.class,
1113 () -> leaderTestKit.doCommit(noShardLeaderCohort)).getCause();
1114 assertThat(ex, instanceOf(NoShardLeaderException.class));
1115 assertThat(ex.getMessage(), containsString(
1116 "Shard member-1-shard-cars-testTransactionWithIsolatedLeader currently has no leader."));
1119 // tell-based canCommit() does not have a real timeout and hence continues
1120 canCommit = noShardLeaderCohort.canCommit();
1121 Uninterruptibles.sleepUninterruptibly(commitTimeout, TimeUnit.SECONDS);
1122 assertFalse(canCommit.isDone());
1125 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1126 .shardElectionTimeoutFactor(100));
1128 final DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
1130 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
1131 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
1133 leaderTestKit.doCommit(preIsolatedLeaderTxCohort);
1134 leaderTestKit.doCommit(successTxCohort);
1136 // continuation of tell-based protocol: readied transaction will complete commit, but will report an OLFE
1137 if (canCommit != null) {
1138 final var ex = assertThrows(ExecutionException.class,
1139 () -> canCommit.get(commitTimeout, TimeUnit.SECONDS)).getCause();
1140 assertThat(ex, instanceOf(OptimisticLockFailedException.class));
1141 assertEquals("Optimistic lock failed for path " + CarsModel.BASE_PATH, ex.getMessage());
1142 final var cause = ex.getCause();
1143 assertThat(cause, instanceOf(ConflictingModificationAppliedException.class));
1144 final var cmae = (ConflictingModificationAppliedException) cause;
1145 assertEquals("Node was created by other transaction.", cmae.getMessage());
1146 assertEquals(CarsModel.BASE_PATH, cmae.getPath());
1151 public void testTransactionWithShardLeaderNotResponding() throws Exception {
1152 followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1153 followerDatastoreContextBuilder.shardElectionTimeoutFactor(50);
1154 initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
1156 // Do an initial read to get the primary shard info cached.
1158 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1159 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1161 // Shutdown the leader and try to create a new tx.
1163 TestKit.shutdownActorSystem(leaderSystem, true);
1165 followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
1166 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
1168 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1170 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1172 final var ex = assertThrows(ExecutionException.class, () -> followerTestKit.doCommit(rwTx.ready()));
1173 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause());
1174 if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
1175 assertTrue(msg, Throwables.getRootCause(ex) instanceof NoShardLeaderException
1176 || ex.getCause() instanceof ShardLeaderNotRespondingException);
1178 assertThat(msg, Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
1183 public void testTransactionWithCreateTxFailureDueToNoLeader() throws Exception {
1184 followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1185 initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
1187 // Do an initial read to get the primary shard info cached.
1189 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1190 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1192 // Shutdown the leader and try to create a new tx.
1194 TestKit.shutdownActorSystem(leaderSystem, true);
1196 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1198 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
1200 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1201 .operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1203 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1205 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1207 final var ex = assertThrows(ExecutionException.class, () -> followerTestKit.doCommit(rwTx.ready()));
1208 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause());
1209 if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
1210 assertThat(msg, Throwables.getRootCause(ex), instanceOf(NoShardLeaderException.class));
1212 assertThat(msg, Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
1217 public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
1218 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
1219 String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
1220 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1222 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1223 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1224 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1225 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1227 try (AbstractDataStore ds =
1228 follower2TestKit.setupAbstractDataStore(
1229 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS)) {
1231 followerTestKit.waitForMembersUp("member-1", "member-3");
1232 follower2TestKit.waitForMembersUp("member-1", "member-2");
1234 // Do an initial read to get the primary shard info cached.
1236 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1237 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1239 // Shutdown the leader and try to create a new tx.
1241 TestKit.shutdownActorSystem(leaderSystem, true);
1243 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1245 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1246 .operationTimeoutInMillis(500).shardElectionTimeoutFactor(5).customRaftPolicyImplementation(null));
1248 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1250 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1252 followerTestKit.doCommit(rwTx.ready());
1257 public void testSemiReachableCandidateNotDroppingLeader() throws Exception {
1258 final String testName = "testSemiReachableCandidateNotDroppingLeader";
1259 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1261 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1262 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1263 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1264 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1266 final AbstractDataStore ds2 =
1267 follower2TestKit.setupAbstractDataStore(
1268 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS);
1270 followerTestKit.waitForMembersUp("member-1", "member-3");
1271 follower2TestKit.waitForMembersUp("member-1", "member-2");
1273 TestKit.shutdownActorSystem(follower2System);
1275 ActorRef cars = leaderDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1276 OnDemandRaftState initialState = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1277 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1279 Cluster leaderCluster = Cluster.get(leaderSystem);
1280 Cluster followerCluster = Cluster.get(followerSystem);
1281 Cluster follower2Cluster = Cluster.get(follower2System);
1283 Member follower2Member = follower2Cluster.readView().self();
1285 await().atMost(10, TimeUnit.SECONDS)
1286 .until(() -> containsUnreachable(leaderCluster, follower2Member));
1287 await().atMost(10, TimeUnit.SECONDS)
1288 .until(() -> containsUnreachable(followerCluster, follower2Member));
1290 ActorRef followerCars = followerDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1292 // to simulate a follower not being able to receive messages, but still being able to send messages and becoming
1293 // candidate, we can just send a couple of RequestVotes to both leader and follower.
1294 cars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1295 followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1296 cars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1297 followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1299 OnDemandRaftState stateAfter = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1300 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1301 OnDemandRaftState followerState = (OnDemandRaftState) followerDistributedDataStore.getActorUtils()
1302 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1304 assertEquals(initialState.getCurrentTerm(), stateAfter.getCurrentTerm());
1305 assertEquals(initialState.getCurrentTerm(), followerState.getCurrentTerm());
1310 private static Boolean containsUnreachable(final Cluster cluster, final Member member) {
1311 // unreachableMembers() returns scala.collection.immutable.Set, but we are using scala.collection.Set to fix JDT
1312 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=468276#c32
1313 final Set<Member> members = cluster.readView().unreachableMembers();
1314 return members.contains(member);
1318 public void testInstallSnapshot() throws Exception {
1319 final String testName = "testInstallSnapshot";
1320 final String leaderCarShardName = "member-1-shard-cars-" + testName;
1321 final String followerCarShardName = "member-2-shard-cars-" + testName;
1323 // Setup a saved snapshot on the leader. The follower will startup with no data and the leader should
1324 // install a snapshot to sync the follower.
1326 DataTree tree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_CONFIGURATION,
1327 SchemaContextHelper.full());
1329 final ContainerNode carsNode = CarsModel.newCarsNode(
1330 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", Uint64.valueOf(20000))));
1331 AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
1333 final NormalizedNode<?, ?> snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.empty());
1334 final Snapshot initialSnapshot = Snapshot.create(
1335 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
1336 Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
1337 InMemorySnapshotStore.addSnapshot(leaderCarShardName, initialSnapshot);
1339 InMemorySnapshotStore.addSnapshotSavedLatch(leaderCarShardName);
1340 InMemorySnapshotStore.addSnapshotSavedLatch(followerCarShardName);
1342 initDatastoresWithCars(testName);
1344 assertEquals(Optional.of(carsNode), leaderDistributedDataStore.newReadOnlyTransaction().read(
1345 CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS));
1347 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(leaderCarShardName, Snapshot.class),
1348 initialSnapshot, snapshotRoot);
1350 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(followerCarShardName, Snapshot.class),
1351 initialSnapshot, snapshotRoot);
1355 public void testReadWriteMessageSlicing() throws Exception {
1356 // The slicing is only implemented for tell-based protocol
1357 assumeTrue(ClientBackedDataStore.class.isAssignableFrom(testParameter));
1359 leaderDatastoreContextBuilder.maximumMessageSliceSize(100);
1360 followerDatastoreContextBuilder.maximumMessageSliceSize(100);
1361 initDatastoresWithCars("testLargeReadReplySlicing");
1363 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1365 final NormalizedNode<?, ?> carsNode = CarsModel.create();
1366 rwTx.write(CarsModel.BASE_PATH, carsNode);
1368 verifyNode(rwTx, CarsModel.BASE_PATH, carsNode);
1371 @SuppressWarnings("IllegalCatch")
1373 public void testRaftCallbackDuringLeadershipDrop() throws Exception {
1374 final String testName = "testRaftCallbackDuringLeadershipDrop";
1375 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1377 final ExecutorService executor = Executors.newSingleThreadExecutor();
1379 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1380 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500)
1381 .shardLeaderElectionTimeoutInSeconds(3600),
1384 final DOMStoreWriteTransaction initialWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1385 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1386 leaderTestKit.doCommit(initialWriteTx.ready());
1388 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1389 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false)) {
1391 final ActorRef member3Cars = ((LocalShardStore) follower2DistributedDataStore).getLocalShards()
1392 .getLocalShards().get("cars").getActor();
1393 final ActorRef member2Cars = ((LocalShardStore)followerDistributedDataStore).getLocalShards()
1394 .getLocalShards().get("cars").getActor();
1395 member2Cars.tell(new StartDropMessages(AppendEntries.class), null);
1396 member3Cars.tell(new StartDropMessages(AppendEntries.class), null);
1398 final DOMStoreWriteTransaction newTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1399 newTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1400 final AtomicBoolean submitDone = new AtomicBoolean(false);
1401 executor.submit(() -> {
1403 leaderTestKit.doCommit(newTx.ready());
1404 submitDone.set(true);
1405 } catch (Exception e) {
1406 throw new RuntimeException(e);
1409 final ActorRef leaderCars = ((LocalShardStore) leaderDistributedDataStore).getLocalShards()
1410 .getLocalShards().get("cars").getActor();
1411 await().atMost(10, TimeUnit.SECONDS)
1412 .until(() -> ((OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1413 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE)).getLastIndex() >= 1);
1415 final OnDemandRaftState raftState = (OnDemandRaftState)leaderDistributedDataStore.getActorUtils()
1416 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE);
1418 // Simulate a follower not receiving heartbeats but still being able to send messages ie RequestVote with
1419 // new term(switching to candidate after election timeout)
1420 leaderCars.tell(new RequestVote(raftState.getCurrentTerm() + 1,
1421 "member-3-shard-cars-testRaftCallbackDuringLeadershipDrop", -1,
1424 member2Cars.tell(new StopDropMessages(AppendEntries.class), null);
1425 member3Cars.tell(new StopDropMessages(AppendEntries.class), null);
1427 await("Is tx stuck in COMMIT_PENDING")
1428 .atMost(10, TimeUnit.SECONDS).untilAtomic(submitDone, equalTo(true));
1432 executor.shutdownNow();
1436 public void testSnapshotOnRootOverwrite() throws Exception {
1437 // FIXME: ClientBackedDatastore does not have stable indexes/term, the snapshot index seems to fluctuate
1438 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1440 final String testName = "testSnapshotOnRootOverwrite";
1441 final String[] shards = {"cars", "default"};
1442 initDatastores(testName, "module-shards-default-cars-member1-and-2.conf", shards,
1443 leaderDatastoreContextBuilder.snapshotOnRootOverwrite(true),
1444 followerDatastoreContextBuilder.snapshotOnRootOverwrite(true));
1446 leaderTestKit.waitForMembersUp("member-2");
1447 final ContainerNode rootNode = ImmutableContainerNodeBuilder.create()
1448 .withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(SchemaContext.NAME))
1449 .withChild((ContainerNode) CarsModel.create())
1452 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1454 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1455 state -> assertEquals(1, state.getSnapshotIndex()));
1457 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1458 state -> assertEquals(1, state.getSnapshotIndex()));
1460 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1461 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1463 for (int i = 0; i < 10; i++) {
1464 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, CarsModel.newCarPath("car " + i),
1465 CarsModel.newCarEntry("car " + i, Uint64.ONE));
1468 // fake snapshot causes the snapshotIndex to move
1469 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1470 state -> assertEquals(10, state.getSnapshotIndex()));
1471 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1472 state -> assertEquals(10, state.getSnapshotIndex()));
1474 // however the real snapshot still has not changed and was taken at index 1
1475 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1476 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1478 // root overwrite so expect a snapshot
1479 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1481 // this was a real snapshot so everything should be in it(1(DisableTrackingPayload) + 1 + 10 + 1)
1482 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1483 state -> assertEquals(12, state.getSnapshotIndex()));
1484 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1485 state -> assertEquals(12, state.getSnapshotIndex()));
1487 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 12);
1488 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 12);
1491 private void verifySnapshot(final String persistenceId, final long lastAppliedIndex) {
1492 await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
1493 List<Snapshot> snap = InMemorySnapshotStore.getSnapshots(persistenceId, Snapshot.class);
1494 assertEquals(1, snap.size());
1495 assertEquals(lastAppliedIndex, snap.get(0).getLastAppliedIndex());
1500 private static void verifySnapshot(final Snapshot actual, final Snapshot expected,
1501 final NormalizedNode<?, ?> expRoot) {
1502 assertEquals("Snapshot getLastAppliedTerm", expected.getLastAppliedTerm(), actual.getLastAppliedTerm());
1503 assertEquals("Snapshot getLastAppliedIndex", expected.getLastAppliedIndex(), actual.getLastAppliedIndex());
1504 assertEquals("Snapshot getLastTerm", expected.getLastTerm(), actual.getLastTerm());
1505 assertEquals("Snapshot getLastIndex", expected.getLastIndex(), actual.getLastIndex());
1506 assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
1507 MetadataShardDataTreeSnapshot shardSnapshot =
1508 (MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
1509 assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
1512 private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1513 final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1514 final DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
1515 final Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1516 doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1517 doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(anyString());
1518 dataStore.onDatastoreContextUpdated(mockContextFactory);