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.NormalizedNode;
121 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
122 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
123 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
124 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
125 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
126 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
127 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
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, true);
212 TestKit.shutdownActorSystem(followerSystem, true);
213 TestKit.shutdownActorSystem(follower2System,true);
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, SystemMapNode> 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().body();
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: CONTROLLER-2016: ask-based frontend triggers this:
428 // java.lang.IllegalStateException: Previous transaction
429 // member-2-datastore-testCloseTransactionMetadataLeak-fe-0-chn-1-txn-1-0 is not ready yet
430 // at org.opendaylight.controller.cluster.datastore.TransactionChainProxy$Allocated.checkReady()
431 // at org.opendaylight.controller.cluster.datastore.TransactionChainProxy.newReadOnlyTransaction()
432 assumeTrue(testParameter.isAssignableFrom(ClientBackedDataStore.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 try (var tx = txChain.newWriteOnlyTransaction()) {
449 try (var tx = txChain.newReadOnlyTransaction()) {
450 tx.read(CarsModel.BASE_PATH).get();
454 // wait to let the shard catch up with purged
455 await("wait for purges to settle").atMost(5, TimeUnit.SECONDS)
456 .pollInterval(500, TimeUnit.MILLISECONDS)
457 .untilAsserted(() -> {
458 final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars")
460 final var frontendMetadata =
461 (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
462 .executeOperation(localShard, new RequestFrontendMetadata());
464 final var clientMeta = frontendMetadata.getClients().get(0);
465 if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
466 assertTellClientMetadata(clientMeta, numCars * 2);
468 assertAskClientMetadata(clientMeta);
474 public void testReadWriteTransactionWithSingleShard() throws Exception {
475 initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
477 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
478 assertNotNull("newReadWriteTransaction returned null", rwTx);
480 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
481 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
483 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
484 rwTx.merge(CarsModel.newCarPath("optima"), car1);
486 verifyCars(rwTx, car1);
488 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
489 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
490 rwTx.merge(car2Path, car2);
492 verifyExists(rwTx, car2Path);
494 followerTestKit.doCommit(rwTx.ready());
496 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
500 public void testWriteTransactionWithMultipleShards() throws Exception {
501 initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
503 final DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
504 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
506 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
507 final NormalizedNode carsNode = CarsModel.emptyContainer();
508 writeTx.write(carsPath, carsNode);
510 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
511 final NormalizedNode peopleNode = PeopleModel.emptyContainer();
512 writeTx.write(peoplePath, peopleNode);
514 followerTestKit.doCommit(writeTx.ready());
516 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
518 verifyNode(readTx, carsPath, carsNode);
519 verifyNode(readTx, peoplePath, peopleNode);
523 public void testReadWriteTransactionWithMultipleShards() throws Exception {
524 initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
526 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
527 assertNotNull("newReadWriteTransaction returned null", rwTx);
529 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
530 final NormalizedNode carsNode = CarsModel.emptyContainer();
531 rwTx.write(carsPath, carsNode);
533 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
534 final NormalizedNode peopleNode = PeopleModel.emptyContainer();
535 rwTx.write(peoplePath, peopleNode);
537 followerTestKit.doCommit(rwTx.ready());
539 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
541 verifyNode(readTx, carsPath, carsNode);
542 verifyNode(readTx, peoplePath, peopleNode);
546 public void testTransactionChainWithSingleShard() throws Exception {
547 initDatastoresWithCars("testTransactionChainWithSingleShard");
549 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
551 // Add the top-level cars container with write-only.
553 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
554 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
556 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
558 final DOMStoreThreePhaseCommitCohort writeTxReady = writeTx.ready();
560 // Verify the top-level cars container with read-only.
562 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
564 // Perform car operations with read-write.
566 final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
568 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
570 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
572 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
573 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
574 rwTx.write(car1Path, car1);
576 verifyExists(rwTx, car1Path);
578 verifyCars(rwTx, car1);
580 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
581 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
583 rwTx.delete(car1Path);
585 followerTestKit.doCommit(writeTxReady);
587 followerTestKit.doCommit(rwTx.ready());
591 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
595 public void testTransactionChainWithMultipleShards() throws Exception {
596 initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
598 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
600 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
601 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
603 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
604 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
606 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
607 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
609 followerTestKit.doCommit(writeTx.ready());
611 final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
613 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
614 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
615 readWriteTx.write(carPath, car);
617 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
618 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
619 readWriteTx.merge(personPath, person);
621 assertEquals(Optional.of(car), readWriteTx.read(carPath).get(5, TimeUnit.SECONDS));
622 assertEquals(Optional.of(person), readWriteTx.read(personPath).get(5, TimeUnit.SECONDS));
624 final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
626 writeTx = txChain.newWriteOnlyTransaction();
628 writeTx.delete(personPath);
630 final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
632 followerTestKit.doCommit(cohort2);
633 followerTestKit.doCommit(cohort3);
637 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
638 verifyCars(readTx, car);
640 assertEquals(Optional.empty(), readTx.read(personPath).get(5, TimeUnit.SECONDS));
644 public void testChainedTransactionFailureWithSingleShard() throws Exception {
645 initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
647 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
648 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
649 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
650 MoreExecutors.directExecutor());
652 final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
653 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
655 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
657 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
658 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
659 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
661 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
663 final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
665 assertThat(ex, instanceOf(TransactionCommitFailedException.class));
667 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
674 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
675 initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
677 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
678 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
679 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
680 MoreExecutors.directExecutor());
682 final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
683 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
685 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
687 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
689 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
690 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
691 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
693 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
694 // done for put for performance reasons.
695 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
697 final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
699 assertThat(ex, instanceOf(TransactionCommitFailedException.class));
701 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
708 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
709 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
710 final String testName = "testSingleShardTransactionsWithLeaderChanges";
711 initDatastoresWithCars(testName);
713 final String followerCarShardName = "member-2-shard-cars-" + testName;
714 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class);
716 // Write top-level car container from the follower so it uses a remote Tx.
718 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
720 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
721 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
723 followerTestKit.doCommit(writeTx.ready());
725 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
727 // Switch the leader to the follower
729 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
730 .shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
732 TestKit.shutdownActorSystem(leaderSystem, true);
733 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
735 followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorUtils(), CARS);
737 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
738 Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
740 final DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder()
741 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
742 IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder, commitTimeout);
744 try (AbstractDataStore ds =
745 newMember1TestKit.setupAbstractDataStore(
746 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS)) {
748 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), CARS);
750 // Write a car entry to the new leader - should switch to local Tx
752 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
754 MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
755 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
756 writeTx.merge(car1Path, car1);
758 followerTestKit.doCommit(writeTx.ready());
760 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
764 @SuppressWarnings("unchecked")
766 public void testReadyLocalTransactionForwardedToLeader() throws Exception {
767 initDatastoresWithCars("testReadyLocalTransactionForwardedToLeader");
768 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
770 final Optional<ActorRef> carsFollowerShard =
771 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
772 assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
774 final DataTree dataTree = new InMemoryDataTreeFactory().create(
775 DataTreeConfiguration.DEFAULT_OPERATIONAL, SchemaContextHelper.full());
777 // Send a tx with immediate commit.
779 DataTreeModification modification = dataTree.takeSnapshot().newModification();
780 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
781 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
783 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
784 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
785 modification.ready();
787 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(tx1 , modification, true, Optional.empty());
789 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
790 Object resp = followerTestKit.expectMsgClass(Object.class);
791 if (resp instanceof akka.actor.Status.Failure) {
792 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
795 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
797 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
799 // Send another tx without immediate commit.
801 modification = dataTree.takeSnapshot().newModification();
802 MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
803 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
804 modification.ready();
806 readyLocal = new ReadyLocalTransaction(tx2 , modification, false, Optional.empty());
808 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
809 resp = followerTestKit.expectMsgClass(Object.class);
810 if (resp instanceof akka.actor.Status.Failure) {
811 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
814 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
816 final ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
817 ((ReadyTransactionReply)resp).getCohortPath());
819 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(leaderDistributedDataStore.getActorUtils(),
820 List.of(new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor),
821 () -> DataStoreVersions.CURRENT_VERSION)), tx2);
822 cohort.canCommit().get(5, TimeUnit.SECONDS);
823 cohort.preCommit().get(5, TimeUnit.SECONDS);
824 cohort.commit().get(5, TimeUnit.SECONDS);
826 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
829 @SuppressWarnings("unchecked")
831 public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
832 initDatastoresWithCars("testForwardedReadyTransactionForwardedToLeader");
833 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
835 final Optional<ActorRef> carsFollowerShard =
836 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
837 assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
839 carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
840 final DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
842 // Send a tx with immediate commit.
844 DataTreeModification modification = dataTree.takeSnapshot().newModification();
845 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
846 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
848 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
849 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
851 ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction(tx1, DataStoreVersions.CURRENT_VERSION,
852 new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx1, modification),
853 true, Optional.empty());
855 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
856 Object resp = followerTestKit.expectMsgClass(Object.class);
857 if (resp instanceof akka.actor.Status.Failure) {
858 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
861 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
863 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
865 // Send another tx without immediate commit.
867 modification = dataTree.takeSnapshot().newModification();
868 MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
869 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
871 forwardedReady = new ForwardedReadyTransaction(tx2, DataStoreVersions.CURRENT_VERSION,
872 new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx2, modification),
873 false, Optional.empty());
875 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
876 resp = followerTestKit.expectMsgClass(Object.class);
877 if (resp instanceof akka.actor.Status.Failure) {
878 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
881 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
883 ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
884 ((ReadyTransactionReply)resp).getCohortPath());
886 final ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
887 leaderDistributedDataStore.getActorUtils(), List.of(
888 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor),
889 () -> DataStoreVersions.CURRENT_VERSION)), tx2);
890 cohort.canCommit().get(5, TimeUnit.SECONDS);
891 cohort.preCommit().get(5, TimeUnit.SECONDS);
892 cohort.commit().get(5, TimeUnit.SECONDS);
894 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
898 public void testTransactionForwardedToLeaderAfterRetry() throws Exception {
899 followerDatastoreContextBuilder.shardBatchedModificationCount(2);
900 leaderDatastoreContextBuilder.shardBatchedModificationCount(2);
901 initDatastoresWithCarsAndPeople("testTransactionForwardedToLeaderAfterRetry");
903 // Do an initial write to get the primary shard info cached.
905 final DOMStoreWriteTransaction initialWriteTx = followerDistributedDataStore.newWriteOnlyTransaction();
906 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
907 initialWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
908 followerTestKit.doCommit(initialWriteTx.ready());
910 // Wait for the commit to be replicated to the follower.
912 MemberNode.verifyRaftState(followerDistributedDataStore, "cars",
913 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
915 MemberNode.verifyRaftState(followerDistributedDataStore, "people",
916 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
918 // Prepare, ready and canCommit a WO tx that writes to 2 shards. This will become the current tx in
921 final DOMStoreWriteTransaction writeTx1 = followerDistributedDataStore.newWriteOnlyTransaction();
922 writeTx1.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
923 writeTx1.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
924 final DOMStoreThreePhaseCommitCohort writeTx1Cohort = writeTx1.ready();
925 final ListenableFuture<Boolean> writeTx1CanCommit = writeTx1Cohort.canCommit();
926 writeTx1CanCommit.get(5, TimeUnit.SECONDS);
928 // Prepare and ready another WO tx that writes to 2 shards but don't canCommit yet. This will be queued
929 // in the leader shard.
931 final DOMStoreWriteTransaction writeTx2 = followerDistributedDataStore.newWriteOnlyTransaction();
932 final LinkedList<MapEntryNode> cars = new LinkedList<>();
934 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
935 writeTx2.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
937 NormalizedNode people = ImmutableNodes.mapNodeBuilder(PeopleModel.PERSON_QNAME)
938 .withChild(PeopleModel.newPersonEntry("Dude")).build();
939 writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
940 final DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
942 // Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
943 // tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
944 // leader shard (with shardBatchedModificationCount set to 2). The 3rd BatchedModidifications will be
947 final DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
948 for (int i = 1; i <= 5; i++, carIndex++) {
949 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
950 writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
953 // Prepare another WO that writes to a single shard. This will send a single BatchedModidifications
956 final DOMStoreWriteTransaction writeTx4 = followerDistributedDataStore.newWriteOnlyTransaction();
957 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
958 writeTx4.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
961 // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaciton message to the
962 // leader shard on ready.
964 final DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
965 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
966 readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
968 // FIXME: CONTROLLER-2017: ClientBackedDataStore reports only 4 transactions
969 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
970 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
971 stats -> assertEquals("getReadWriteTransactionCount", 5, stats.getReadWriteTransactionCount()));
973 // Disable elections on the leader so it switches to follower.
975 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
976 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
977 .shardElectionTimeoutFactor(10));
979 leaderTestKit.waitUntilNoLeader(leaderDistributedDataStore.getActorUtils(), "cars");
981 // Submit all tx's - the messages should get queued for retry.
983 final ListenableFuture<Boolean> writeTx2CanCommit = writeTx2Cohort.canCommit();
984 final DOMStoreThreePhaseCommitCohort writeTx3Cohort = writeTx3.ready();
985 final DOMStoreThreePhaseCommitCohort writeTx4Cohort = writeTx4.ready();
986 final DOMStoreThreePhaseCommitCohort rwTxCohort = readWriteTx.ready();
988 // Enable elections on the other follower so it becomes the leader, at which point the
989 // tx's should get forwarded from the previous leader to the new leader to complete the commits.
991 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
992 .customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
993 IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorUtils(), "cars")
994 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
995 IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorUtils(), "people")
996 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
998 followerTestKit.doCommit(writeTx1CanCommit, writeTx1Cohort);
999 followerTestKit.doCommit(writeTx2CanCommit, writeTx2Cohort);
1000 followerTestKit.doCommit(writeTx3Cohort);
1001 followerTestKit.doCommit(writeTx4Cohort);
1002 followerTestKit.doCommit(rwTxCohort);
1004 DOMStoreReadTransaction readTx = leaderDistributedDataStore.newReadOnlyTransaction();
1005 verifyCars(readTx, cars.toArray(new MapEntryNode[cars.size()]));
1006 verifyNode(readTx, PeopleModel.PERSON_LIST_PATH, people);
1010 public void testLeadershipTransferOnShutdown() throws Exception {
1011 leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
1012 followerDatastoreContextBuilder.shardElectionTimeoutFactor(10).customRaftPolicyImplementation(null);
1013 final String testName = "testLeadershipTransferOnShutdown";
1014 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS_AND_PEOPLE);
1016 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1017 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500),
1019 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1020 testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
1022 followerTestKit.waitForMembersUp("member-3");
1023 follower2TestKit.waitForMembersUp("member-1", "member-2");
1025 // Create and submit a couple tx's so they're pending.
1027 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
1028 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1029 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1030 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
1031 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
1033 final var usesCohorts = DistributedDataStore.class.isAssignableFrom(testParameter);
1035 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1036 stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
1039 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
1040 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
1041 writeTx.write(CarsModel.newCarPath("optima"), car);
1042 final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
1045 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1046 stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
1049 // Gracefully stop the leader via a Shutdown message.
1051 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1052 .shardElectionTimeoutFactor(100));
1054 final FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
1055 final Future<ActorRef> future = leaderDistributedDataStore.getActorUtils().findLocalShardAsync("cars");
1056 final ActorRef leaderActor = Await.result(future, duration);
1058 final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);
1060 // Commit the 2 transactions. They should finish and succeed.
1062 followerTestKit.doCommit(cohort1);
1063 followerTestKit.doCommit(cohort2);
1065 // Wait for the leader actor stopped.
1067 final Boolean stopped = Await.result(stopFuture, duration);
1068 assertEquals("Stopped", Boolean.TRUE, stopped);
1070 // Verify leadership was transferred by reading the committed data from the other nodes.
1072 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
1073 verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
1078 public void testTransactionWithIsolatedLeader() throws Exception {
1079 // Set the isolated leader check interval high so we can control the switch to IsolatedLeader.
1080 leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(10000000);
1081 final String testName = "testTransactionWithIsolatedLeader";
1082 initDatastoresWithCars(testName);
1084 // Tx that is submitted after the follower is stopped but before the leader transitions to IsolatedLeader.
1085 final DOMStoreWriteTransaction preIsolatedLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1086 preIsolatedLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1088 // Tx that is submitted after the leader transitions to IsolatedLeader.
1089 final DOMStoreWriteTransaction noShardLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1090 noShardLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1092 // Tx that is submitted after the follower is reinstated.
1093 final DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1094 successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1096 // Stop the follower
1097 followerTestKit.watch(followerDistributedDataStore.getActorUtils().getShardManager());
1098 followerDistributedDataStore.close();
1099 followerTestKit.expectTerminated(followerDistributedDataStore.getActorUtils().getShardManager());
1101 // Submit the preIsolatedLeaderWriteTx so it's pending
1102 final DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
1104 // Change the isolated leader check interval low so it changes to IsolatedLeader.
1105 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1106 .shardIsolatedLeaderCheckIntervalInMillis(200));
1108 MemberNode.verifyRaftState(leaderDistributedDataStore, "cars",
1109 raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
1111 final var noShardLeaderCohort = noShardLeaderWriteTx.ready();
1112 final ListenableFuture<Boolean> canCommit;
1114 // There is difference in behavior here:
1115 if (!leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
1116 // ask-based canCommit() times out and aborts
1117 final var ex = assertThrows(ExecutionException.class,
1118 () -> leaderTestKit.doCommit(noShardLeaderCohort)).getCause();
1119 assertThat(ex, instanceOf(NoShardLeaderException.class));
1120 assertThat(ex.getMessage(), containsString(
1121 "Shard member-1-shard-cars-testTransactionWithIsolatedLeader currently has no leader."));
1124 // tell-based canCommit() does not have a real timeout and hence continues
1125 canCommit = noShardLeaderCohort.canCommit();
1126 Uninterruptibles.sleepUninterruptibly(commitTimeout, TimeUnit.SECONDS);
1127 assertFalse(canCommit.isDone());
1130 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1131 .shardElectionTimeoutFactor(100));
1133 final DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
1135 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
1136 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
1138 leaderTestKit.doCommit(preIsolatedLeaderTxCohort);
1139 leaderTestKit.doCommit(successTxCohort);
1141 // continuation of tell-based protocol: readied transaction will complete commit, but will report an OLFE
1142 if (canCommit != null) {
1143 final var ex = assertThrows(ExecutionException.class,
1144 () -> canCommit.get(commitTimeout, TimeUnit.SECONDS)).getCause();
1145 assertThat(ex, instanceOf(OptimisticLockFailedException.class));
1146 assertEquals("Optimistic lock failed for path " + CarsModel.BASE_PATH, ex.getMessage());
1147 final var cause = ex.getCause();
1148 assertThat(cause, instanceOf(ConflictingModificationAppliedException.class));
1149 final var cmae = (ConflictingModificationAppliedException) cause;
1150 assertEquals("Node was created by other transaction.", cmae.getMessage());
1151 assertEquals(CarsModel.BASE_PATH, cmae.getPath());
1156 public void testTransactionWithShardLeaderNotResponding() throws Exception {
1157 followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1158 followerDatastoreContextBuilder.shardElectionTimeoutFactor(50);
1159 initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
1161 // Do an initial read to get the primary shard info cached.
1163 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1164 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1166 // Shutdown the leader and try to create a new tx.
1168 TestKit.shutdownActorSystem(leaderSystem, true);
1170 followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
1171 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
1173 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1175 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1177 final var ex = assertThrows(ExecutionException.class, () -> followerTestKit.doCommit(rwTx.ready()));
1178 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause());
1179 if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
1180 assertTrue(msg, Throwables.getRootCause(ex) instanceof NoShardLeaderException
1181 || ex.getCause() instanceof ShardLeaderNotRespondingException);
1183 assertThat(msg, Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
1188 public void testTransactionWithCreateTxFailureDueToNoLeader() throws Exception {
1189 followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1190 initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
1192 // Do an initial read to get the primary shard info cached.
1194 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1195 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1197 // Shutdown the leader and try to create a new tx.
1199 TestKit.shutdownActorSystem(leaderSystem, true);
1201 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1203 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
1205 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1206 .operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1208 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1210 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1212 final var ex = assertThrows(ExecutionException.class, () -> followerTestKit.doCommit(rwTx.ready()));
1213 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause());
1214 if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
1215 assertThat(msg, Throwables.getRootCause(ex), instanceOf(NoShardLeaderException.class));
1217 assertThat(msg, Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
1222 public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
1223 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
1224 String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
1225 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1227 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1228 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1229 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1230 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1232 try (AbstractDataStore ds =
1233 follower2TestKit.setupAbstractDataStore(
1234 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS)) {
1236 followerTestKit.waitForMembersUp("member-1", "member-3");
1237 follower2TestKit.waitForMembersUp("member-1", "member-2");
1239 // Do an initial read to get the primary shard info cached.
1241 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1242 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1244 // Shutdown the leader and try to create a new tx.
1246 TestKit.shutdownActorSystem(leaderSystem, true);
1248 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1250 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1251 .operationTimeoutInMillis(500).shardElectionTimeoutFactor(5).customRaftPolicyImplementation(null));
1253 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1255 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1257 followerTestKit.doCommit(rwTx.ready());
1262 public void testSemiReachableCandidateNotDroppingLeader() throws Exception {
1263 final String testName = "testSemiReachableCandidateNotDroppingLeader";
1264 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1266 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1267 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1268 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1269 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1271 final AbstractDataStore ds2 =
1272 follower2TestKit.setupAbstractDataStore(
1273 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS);
1275 followerTestKit.waitForMembersUp("member-1", "member-3");
1276 follower2TestKit.waitForMembersUp("member-1", "member-2");
1278 // behavior is controlled by akka.coordinated-shutdown.run-by-actor-system-terminate configuration option
1279 TestKit.shutdownActorSystem(follower2System, true);
1281 ActorRef cars = leaderDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1282 final OnDemandRaftState initialState = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1283 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1285 Cluster leaderCluster = Cluster.get(leaderSystem);
1286 Cluster followerCluster = Cluster.get(followerSystem);
1287 Cluster follower2Cluster = Cluster.get(follower2System);
1289 Member follower2Member = follower2Cluster.readView().self();
1291 await().atMost(10, TimeUnit.SECONDS)
1292 .until(() -> containsUnreachable(leaderCluster, follower2Member));
1293 await().atMost(10, TimeUnit.SECONDS)
1294 .until(() -> containsUnreachable(followerCluster, follower2Member));
1296 ActorRef followerCars = followerDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1298 // to simulate a follower not being able to receive messages, but still being able to send messages and becoming
1299 // candidate, we can just send a couple of RequestVotes to both leader and follower.
1300 cars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1301 followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1302 cars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1303 followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1305 OnDemandRaftState stateAfter = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1306 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1307 OnDemandRaftState followerState = (OnDemandRaftState) followerDistributedDataStore.getActorUtils()
1308 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1310 assertEquals(initialState.getCurrentTerm(), stateAfter.getCurrentTerm());
1311 assertEquals(initialState.getCurrentTerm(), followerState.getCurrentTerm());
1316 private static Boolean containsUnreachable(final Cluster cluster, final Member member) {
1317 // unreachableMembers() returns scala.collection.immutable.Set, but we are using scala.collection.Set to fix JDT
1318 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=468276#c32
1319 final Set<Member> members = cluster.readView().unreachableMembers();
1320 return members.contains(member);
1324 public void testInstallSnapshot() throws Exception {
1325 final String testName = "testInstallSnapshot";
1326 final String leaderCarShardName = "member-1-shard-cars-" + testName;
1327 final String followerCarShardName = "member-2-shard-cars-" + testName;
1329 // Setup a saved snapshot on the leader. The follower will startup with no data and the leader should
1330 // install a snapshot to sync the follower.
1332 DataTree tree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_CONFIGURATION,
1333 SchemaContextHelper.full());
1335 final ContainerNode carsNode = CarsModel.newCarsNode(
1336 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", Uint64.valueOf(20000))));
1337 AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
1339 final NormalizedNode snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.empty());
1340 final Snapshot initialSnapshot = Snapshot.create(
1341 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
1342 Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
1343 InMemorySnapshotStore.addSnapshot(leaderCarShardName, initialSnapshot);
1345 InMemorySnapshotStore.addSnapshotSavedLatch(leaderCarShardName);
1346 InMemorySnapshotStore.addSnapshotSavedLatch(followerCarShardName);
1348 initDatastoresWithCars(testName);
1350 assertEquals(Optional.of(carsNode), leaderDistributedDataStore.newReadOnlyTransaction().read(
1351 CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS));
1353 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(leaderCarShardName, Snapshot.class),
1354 initialSnapshot, snapshotRoot);
1356 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(followerCarShardName, Snapshot.class),
1357 initialSnapshot, snapshotRoot);
1361 public void testReadWriteMessageSlicing() throws Exception {
1362 // The slicing is only implemented for tell-based protocol
1363 assumeTrue(ClientBackedDataStore.class.isAssignableFrom(testParameter));
1365 leaderDatastoreContextBuilder.maximumMessageSliceSize(100);
1366 followerDatastoreContextBuilder.maximumMessageSliceSize(100);
1367 initDatastoresWithCars("testLargeReadReplySlicing");
1369 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1371 final NormalizedNode carsNode = CarsModel.create();
1372 rwTx.write(CarsModel.BASE_PATH, carsNode);
1374 verifyNode(rwTx, CarsModel.BASE_PATH, carsNode);
1377 @SuppressWarnings("IllegalCatch")
1379 public void testRaftCallbackDuringLeadershipDrop() throws Exception {
1380 final String testName = "testRaftCallbackDuringLeadershipDrop";
1381 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1383 final ExecutorService executor = Executors.newSingleThreadExecutor();
1385 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1386 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500)
1387 .shardLeaderElectionTimeoutInSeconds(3600),
1390 final DOMStoreWriteTransaction initialWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1391 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1392 leaderTestKit.doCommit(initialWriteTx.ready());
1394 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1395 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false)) {
1397 final ActorRef member3Cars = ((LocalShardStore) follower2DistributedDataStore).getLocalShards()
1398 .getLocalShards().get("cars").getActor();
1399 final ActorRef member2Cars = ((LocalShardStore)followerDistributedDataStore).getLocalShards()
1400 .getLocalShards().get("cars").getActor();
1401 member2Cars.tell(new StartDropMessages(AppendEntries.class), null);
1402 member3Cars.tell(new StartDropMessages(AppendEntries.class), null);
1404 final DOMStoreWriteTransaction newTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1405 newTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1406 final AtomicBoolean submitDone = new AtomicBoolean(false);
1407 executor.submit(() -> {
1409 leaderTestKit.doCommit(newTx.ready());
1410 submitDone.set(true);
1411 } catch (Exception e) {
1412 throw new RuntimeException(e);
1415 final ActorRef leaderCars = ((LocalShardStore) leaderDistributedDataStore).getLocalShards()
1416 .getLocalShards().get("cars").getActor();
1417 await().atMost(10, TimeUnit.SECONDS)
1418 .until(() -> ((OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1419 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE)).getLastIndex() >= 1);
1421 final OnDemandRaftState raftState = (OnDemandRaftState)leaderDistributedDataStore.getActorUtils()
1422 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE);
1424 // Simulate a follower not receiving heartbeats but still being able to send messages ie RequestVote with
1425 // new term(switching to candidate after election timeout)
1426 leaderCars.tell(new RequestVote(raftState.getCurrentTerm() + 1,
1427 "member-3-shard-cars-testRaftCallbackDuringLeadershipDrop", -1,
1430 member2Cars.tell(new StopDropMessages(AppendEntries.class), null);
1431 member3Cars.tell(new StopDropMessages(AppendEntries.class), null);
1433 await("Is tx stuck in COMMIT_PENDING")
1434 .atMost(10, TimeUnit.SECONDS).untilAtomic(submitDone, equalTo(true));
1438 executor.shutdownNow();
1442 public void testSnapshotOnRootOverwrite() throws Exception {
1443 initDatastores("testSnapshotOnRootOverwrite", "module-shards-default-cars-member1-and-2.conf",
1444 new String[] {"cars", "default"},
1445 leaderDatastoreContextBuilder.snapshotOnRootOverwrite(true),
1446 followerDatastoreContextBuilder.snapshotOnRootOverwrite(true));
1448 leaderTestKit.waitForMembersUp("member-2");
1449 final ContainerNode rootNode = ImmutableContainerNodeBuilder.create()
1450 .withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(SchemaContext.NAME))
1451 .withChild(CarsModel.create())
1454 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1456 // FIXME: CONTROLLER-2020: ClientBackedDatastore does not have stable indexes/term,
1457 // the snapshot index seems to fluctuate
1458 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1459 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1460 state -> assertEquals(1, state.getSnapshotIndex()));
1462 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1463 state -> assertEquals(1, state.getSnapshotIndex()));
1465 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1466 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1468 for (int i = 0; i < 10; i++) {
1469 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, CarsModel.newCarPath("car " + i),
1470 CarsModel.newCarEntry("car " + i, Uint64.ONE));
1473 // fake snapshot causes the snapshotIndex to move
1474 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1475 state -> assertEquals(10, state.getSnapshotIndex()));
1476 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1477 state -> assertEquals(10, state.getSnapshotIndex()));
1479 // however the real snapshot still has not changed and was taken at index 1
1480 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1481 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1483 // root overwrite so expect a snapshot
1484 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1486 // this was a real snapshot so everything should be in it(1(DisableTrackingPayload) + 1 + 10 + 1)
1487 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1488 state -> assertEquals(12, state.getSnapshotIndex()));
1489 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1490 state -> assertEquals(12, state.getSnapshotIndex()));
1492 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 12);
1493 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 12);
1496 private static void verifySnapshot(final String persistenceId, final long lastAppliedIndex) {
1497 await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
1498 List<Snapshot> snap = InMemorySnapshotStore.getSnapshots(persistenceId, Snapshot.class);
1499 assertEquals(1, snap.size());
1500 assertEquals(lastAppliedIndex, snap.get(0).getLastAppliedIndex());
1505 private static void verifySnapshot(final Snapshot actual, final Snapshot expected,
1506 final NormalizedNode expRoot) {
1507 assertEquals("Snapshot getLastAppliedTerm", expected.getLastAppliedTerm(), actual.getLastAppliedTerm());
1508 assertEquals("Snapshot getLastAppliedIndex", expected.getLastAppliedIndex(), actual.getLastAppliedIndex());
1509 assertEquals("Snapshot getLastTerm", expected.getLastTerm(), actual.getLastTerm());
1510 assertEquals("Snapshot getLastIndex", expected.getLastIndex(), actual.getLastIndex());
1511 assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
1512 MetadataShardDataTreeSnapshot shardSnapshot =
1513 (MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
1514 assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
1517 private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1518 final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1519 final DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
1520 final Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1521 doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1522 doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(anyString());
1523 dataStore.onDatastoreContextUpdated(mockContextFactory);