2 * Copyright (c) 2015, 2017 Brocade Communications Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.datastore;
10 import static org.awaitility.Awaitility.await;
11 import static org.hamcrest.CoreMatchers.instanceOf;
12 import static org.hamcrest.MatcherAssert.assertThat;
13 import static org.hamcrest.Matchers.equalTo;
14 import static org.junit.Assert.assertEquals;
15 import static org.junit.Assert.assertNotNull;
16 import static org.junit.Assert.assertThrows;
17 import static org.junit.Assert.assertTrue;
18 import static org.junit.Assume.assumeTrue;
19 import static org.mockito.ArgumentMatchers.any;
20 import static org.mockito.ArgumentMatchers.anyString;
21 import static org.mockito.ArgumentMatchers.eq;
22 import static org.mockito.Mockito.doAnswer;
23 import static org.mockito.Mockito.mock;
24 import static org.mockito.Mockito.timeout;
25 import static org.mockito.Mockito.verify;
27 import akka.actor.ActorRef;
28 import akka.actor.ActorSelection;
29 import akka.actor.ActorSystem;
30 import akka.actor.Address;
31 import akka.actor.AddressFromURIString;
32 import akka.cluster.Cluster;
33 import akka.cluster.Member;
34 import akka.dispatch.Futures;
35 import akka.pattern.Patterns;
36 import akka.testkit.javadsl.TestKit;
37 import com.google.common.base.Stopwatch;
38 import com.google.common.base.Throwables;
39 import com.google.common.collect.ImmutableMap;
40 import com.google.common.util.concurrent.ListenableFuture;
41 import com.google.common.util.concurrent.MoreExecutors;
42 import com.google.common.util.concurrent.Uninterruptibles;
43 import com.typesafe.config.ConfigFactory;
44 import java.util.Arrays;
45 import java.util.Collection;
46 import java.util.Collections;
47 import java.util.LinkedList;
48 import java.util.List;
49 import java.util.Optional;
50 import java.util.concurrent.ExecutionException;
51 import java.util.concurrent.ExecutorService;
52 import java.util.concurrent.Executors;
53 import java.util.concurrent.TimeUnit;
54 import java.util.concurrent.atomic.AtomicBoolean;
55 import java.util.concurrent.atomic.AtomicLong;
56 import org.junit.After;
57 import org.junit.Before;
58 import org.junit.Test;
59 import org.junit.runner.RunWith;
60 import org.junit.runners.Parameterized;
61 import org.junit.runners.Parameterized.Parameter;
62 import org.junit.runners.Parameterized.Parameters;
63 import org.mockito.stubbing.Answer;
64 import org.opendaylight.controller.cluster.access.client.RequestTimeoutException;
65 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
66 import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
67 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
68 import org.opendaylight.controller.cluster.databroker.TestClientBackedDataStore;
69 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
70 import org.opendaylight.controller.cluster.datastore.TestShard.RequestFrontendMetadata;
71 import org.opendaylight.controller.cluster.datastore.TestShard.StartDropMessages;
72 import org.opendaylight.controller.cluster.datastore.TestShard.StopDropMessages;
73 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
74 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
75 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
76 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
77 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
78 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
79 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
80 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
81 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
82 import org.opendaylight.controller.cluster.datastore.persisted.FrontendClientMetadata;
83 import org.opendaylight.controller.cluster.datastore.persisted.FrontendShardDataTreeSnapshotMetadata;
84 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
85 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
86 import org.opendaylight.controller.cluster.datastore.utils.UnsignedLongBitmap;
87 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
88 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
89 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
90 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
91 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
92 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
93 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
94 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
95 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
96 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
97 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
98 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
99 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
100 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
101 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
102 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
103 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
104 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
105 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
106 import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
107 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
108 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
109 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
110 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
111 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
112 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
113 import org.opendaylight.yangtools.yang.common.Uint64;
114 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
115 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
117 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
119 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
120 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
121 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
122 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
123 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
124 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
125 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
126 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
127 import scala.collection.Set;
128 import scala.concurrent.Await;
129 import scala.concurrent.Future;
130 import scala.concurrent.duration.FiniteDuration;
133 * End-to-end distributed data store tests that exercise remote shards and transactions.
135 * @author Thomas Pantelis
137 @RunWith(Parameterized.class)
138 public class DistributedDataStoreRemotingIntegrationTest extends AbstractTest {
140 @Parameters(name = "{0}")
141 public static Collection<Object[]> data() {
142 return Arrays.asList(new Object[][] {
143 { TestDistributedDataStore.class, 7}, { TestClientBackedDataStore.class, 12 }
148 public Class<? extends AbstractDataStore> testParameter;
150 public int commitTimeout;
152 private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
153 private static final String[] CARS = {"cars"};
155 private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse(
156 "akka://cluster-test@127.0.0.1:2558");
157 private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse(
158 "akka://cluster-test@127.0.0.1:2559");
160 private static final String MODULE_SHARDS_CARS_ONLY_1_2 = "module-shards-cars-member-1-and-2.conf";
161 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2 = "module-shards-member1-and-2.conf";
162 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2_3 = "module-shards-member1-and-2-and-3.conf";
163 private static final String MODULE_SHARDS_CARS_1_2_3 = "module-shards-cars-member-1-and-2-and-3.conf";
165 private ActorSystem leaderSystem;
166 private ActorSystem followerSystem;
167 private ActorSystem follower2System;
169 private final DatastoreContext.Builder leaderDatastoreContextBuilder =
170 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
172 private final DatastoreContext.Builder followerDatastoreContextBuilder =
173 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5)
174 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
175 private final TransactionIdentifier tx1 = nextTransactionId();
176 private final TransactionIdentifier tx2 = nextTransactionId();
178 private AbstractDataStore followerDistributedDataStore;
179 private AbstractDataStore leaderDistributedDataStore;
180 private IntegrationTestKit followerTestKit;
181 private IntegrationTestKit leaderTestKit;
184 public void setUp() {
185 InMemoryJournal.clear();
186 InMemorySnapshotStore.clear();
188 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
189 Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
191 followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
192 Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
194 follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
195 Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
199 public void tearDown() {
200 if (followerDistributedDataStore != null) {
201 leaderDistributedDataStore.close();
203 if (leaderDistributedDataStore != null) {
204 leaderDistributedDataStore.close();
207 TestKit.shutdownActorSystem(leaderSystem, true);
208 TestKit.shutdownActorSystem(followerSystem, true);
209 TestKit.shutdownActorSystem(follower2System,true);
211 InMemoryJournal.clear();
212 InMemorySnapshotStore.clear();
215 private void initDatastoresWithCars(final String type) throws Exception {
216 initDatastores(type, MODULE_SHARDS_CARS_ONLY_1_2, CARS);
219 private void initDatastoresWithCarsAndPeople(final String type) throws Exception {
220 initDatastores(type, MODULE_SHARDS_CARS_PEOPLE_1_2, CARS_AND_PEOPLE);
223 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards)
225 initDatastores(type, moduleShardsConfig, shards, leaderDatastoreContextBuilder,
226 followerDatastoreContextBuilder);
229 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards,
230 final DatastoreContext.Builder leaderBuilder, final DatastoreContext.Builder followerBuilder)
232 leaderTestKit = new IntegrationTestKit(leaderSystem, leaderBuilder, commitTimeout);
234 leaderDistributedDataStore = leaderTestKit.setupAbstractDataStore(
235 testParameter, type, moduleShardsConfig, false, shards);
237 followerTestKit = new IntegrationTestKit(followerSystem, followerBuilder, commitTimeout);
238 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
239 testParameter, type, moduleShardsConfig, false, shards);
241 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorUtils(), shards);
243 leaderTestKit.waitForMembersUp("member-2");
244 followerTestKit.waitForMembersUp("member-1");
247 private static void verifyCars(final DOMStoreReadTransaction readTx, final MapEntryNode... entries)
249 final Optional<NormalizedNode> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
250 assertTrue("isPresent", optional.isPresent());
252 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> listBuilder = ImmutableNodes.mapNodeBuilder(
253 CarsModel.CAR_QNAME);
254 for (final NormalizedNode entry: entries) {
255 listBuilder.withChild((MapEntryNode) entry);
258 assertEquals("Car list node", listBuilder.build(), optional.get());
261 private static void verifyNode(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path,
262 final NormalizedNode expNode) throws Exception {
263 assertEquals(Optional.of(expNode), readTx.read(path).get(5, TimeUnit.SECONDS));
266 private static void verifyExists(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path)
268 assertEquals("exists", Boolean.TRUE, readTx.exists(path).get(5, TimeUnit.SECONDS));
272 public void testWriteTransactionWithSingleShard() throws Exception {
273 final String testName = "testWriteTransactionWithSingleShard";
274 initDatastoresWithCars(testName);
276 final String followerCarShardName = "member-2-shard-cars-" + testName;
278 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
279 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
281 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
282 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
284 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
285 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
286 writeTx.merge(car1Path, car1);
288 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
289 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
290 writeTx.merge(car2Path, car2);
292 followerTestKit.doCommit(writeTx.ready());
294 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
296 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
300 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
302 writeTx.delete(car1Path);
304 followerTestKit.doCommit(writeTx.ready());
306 verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
308 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
310 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
312 // Re-instate the follower member 2 as a single-node to verify replication and recovery.
314 // The following is a bit tricky. Before we reinstate the follower we need to ensure it has persisted and
315 // applied and all the log entries from the leader. Since we've verified the car data above we know that
316 // all the transactions have been applied on the leader so we first read and capture its lastAppliedIndex.
317 final AtomicLong leaderLastAppliedIndex = new AtomicLong();
318 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, CARS[0],
319 state -> leaderLastAppliedIndex.set(state.getLastApplied()));
321 // Now we need to make sure the follower has persisted the leader's lastAppliedIndex via ApplyJournalEntries.
322 // However we don't know exactly how many ApplyJournalEntries messages there will be as it can differ between
323 // the tell-based and ask-based front-ends. For ask-based there will be exactly 2 ApplyJournalEntries but
324 // tell-based persists additional payloads which could be replicated and applied in a batch resulting in
325 // either 2 or 3 ApplyJournalEntries. To handle this we read the follower's persisted ApplyJournalEntries
326 // until we find the one that encompasses the leader's lastAppliedIndex.
327 Stopwatch sw = Stopwatch.createStarted();
328 boolean done = false;
330 final List<ApplyJournalEntries> entries = InMemoryJournal.get(followerCarShardName,
331 ApplyJournalEntries.class);
332 for (ApplyJournalEntries aje: entries) {
333 if (aje.getToIndex() >= leaderLastAppliedIndex.get()) {
339 assertTrue("Follower did not persist ApplyJournalEntries containing leader's lastAppliedIndex "
340 + leaderLastAppliedIndex + ". Entries persisted: " + entries, sw.elapsed(TimeUnit.SECONDS) <= 5);
342 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
345 TestKit.shutdownActorSystem(leaderSystem, true);
346 TestKit.shutdownActorSystem(followerSystem, true);
348 final ActorSystem newSystem = newActorSystem("reinstated-member2", "Member2");
350 try (AbstractDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder,
352 .setupAbstractDataStore(testParameter, testName, "module-shards-member2", true, CARS)) {
353 verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
358 public void testSingleTransactionsWritesInQuickSuccession() throws Exception {
359 initDatastoresWithCars("testSingleTransactionsWritesInQuickSuccession");
361 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
363 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
364 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
365 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
366 followerTestKit.doCommit(writeTx.ready());
369 for (int i = 0; i < numCars; i++) {
370 writeTx = txChain.newWriteOnlyTransaction();
371 writeTx.write(CarsModel.newCarPath("car" + i), CarsModel.newCarEntry("car" + i, Uint64.valueOf(20000)));
372 followerTestKit.doCommit(writeTx.ready());
374 try (var tx = txChain.newReadOnlyTransaction()) {
375 tx.read(CarsModel.BASE_PATH).get();
379 // wait to let the shard catch up with purged
380 await("Range set leak test").atMost(5, TimeUnit.SECONDS)
381 .pollInterval(500, TimeUnit.MILLISECONDS)
382 .untilAsserted(() -> {
383 final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars")
385 final var frontendMetadata =
386 (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
387 .executeOperation(localShard, new RequestFrontendMetadata());
389 final var clientMeta = frontendMetadata.getClients().get(0);
390 if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
391 assertTellClientMetadata(clientMeta, numCars * 2);
393 assertAskClientMetadata(clientMeta);
397 try (var tx = txChain.newReadOnlyTransaction()) {
398 final var body = tx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS).orElseThrow().body();
399 assertThat(body, instanceOf(Collection.class));
400 assertEquals(numCars, ((Collection<?>) body).size());
404 private static void assertAskClientMetadata(final FrontendClientMetadata clientMeta) {
405 // ask based should track no metadata
406 assertEquals(List.of(), clientMeta.getCurrentHistories());
409 private static void assertTellClientMetadata(final FrontendClientMetadata clientMeta, final long lastPurged) {
410 final var iterator = clientMeta.getCurrentHistories().iterator();
411 var metadata = iterator.next();
412 while (iterator.hasNext() && metadata.getHistoryId() != 1) {
413 metadata = iterator.next();
416 assertEquals(UnsignedLongBitmap.of(), metadata.getClosedTransactions());
417 assertEquals("[[0.." + lastPurged + "]]", metadata.getPurgedTransactions().ranges().toString());
421 public void testCloseTransactionMetadataLeak() throws Exception {
422 // FIXME: CONTROLLER-2016: ask-based frontend triggers this:
424 // java.lang.IllegalStateException: Previous transaction
425 // member-2-datastore-testCloseTransactionMetadataLeak-fe-0-chn-1-txn-1-0 is not ready yet
426 // at org.opendaylight.controller.cluster.datastore.TransactionChainProxy$Allocated.checkReady()
427 // at org.opendaylight.controller.cluster.datastore.TransactionChainProxy.newReadOnlyTransaction()
428 assumeTrue(testParameter.isAssignableFrom(ClientBackedDataStore.class));
430 initDatastoresWithCars("testCloseTransactionMetadataLeak");
432 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
434 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
435 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
436 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
437 followerTestKit.doCommit(writeTx.ready());
440 for (int i = 0; i < numCars; i++) {
441 try (var tx = txChain.newWriteOnlyTransaction()) {
445 try (var tx = txChain.newReadOnlyTransaction()) {
446 tx.read(CarsModel.BASE_PATH).get();
450 // wait to let the shard catch up with purged
451 await("wait for purges to settle").atMost(5, TimeUnit.SECONDS)
452 .pollInterval(500, TimeUnit.MILLISECONDS)
453 .untilAsserted(() -> {
454 final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars")
456 final var frontendMetadata =
457 (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
458 .executeOperation(localShard, new RequestFrontendMetadata());
460 final var clientMeta = frontendMetadata.getClients().get(0);
461 if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
462 assertTellClientMetadata(clientMeta, numCars * 2);
464 assertAskClientMetadata(clientMeta);
470 public void testReadWriteTransactionWithSingleShard() throws Exception {
471 initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
473 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
474 assertNotNull("newReadWriteTransaction returned null", rwTx);
476 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
477 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
479 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
480 rwTx.merge(CarsModel.newCarPath("optima"), car1);
482 verifyCars(rwTx, car1);
484 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
485 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
486 rwTx.merge(car2Path, car2);
488 verifyExists(rwTx, car2Path);
490 followerTestKit.doCommit(rwTx.ready());
492 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
496 public void testWriteTransactionWithMultipleShards() throws Exception {
497 initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
499 final DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
500 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
502 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
503 final NormalizedNode carsNode = CarsModel.emptyContainer();
504 writeTx.write(carsPath, carsNode);
506 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
507 final NormalizedNode peopleNode = PeopleModel.emptyContainer();
508 writeTx.write(peoplePath, peopleNode);
510 followerTestKit.doCommit(writeTx.ready());
512 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
514 verifyNode(readTx, carsPath, carsNode);
515 verifyNode(readTx, peoplePath, peopleNode);
519 public void testReadWriteTransactionWithMultipleShards() throws Exception {
520 initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
522 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
523 assertNotNull("newReadWriteTransaction returned null", rwTx);
525 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
526 final NormalizedNode carsNode = CarsModel.emptyContainer();
527 rwTx.write(carsPath, carsNode);
529 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
530 final NormalizedNode peopleNode = PeopleModel.emptyContainer();
531 rwTx.write(peoplePath, peopleNode);
533 followerTestKit.doCommit(rwTx.ready());
535 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
537 verifyNode(readTx, carsPath, carsNode);
538 verifyNode(readTx, peoplePath, peopleNode);
542 public void testTransactionChainWithSingleShard() throws Exception {
543 initDatastoresWithCars("testTransactionChainWithSingleShard");
545 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
547 // Add the top-level cars container with write-only.
549 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
550 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
552 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
554 final DOMStoreThreePhaseCommitCohort writeTxReady = writeTx.ready();
556 // Verify the top-level cars container with read-only.
558 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
560 // Perform car operations with read-write.
562 final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
564 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
566 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
568 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
569 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
570 rwTx.write(car1Path, car1);
572 verifyExists(rwTx, car1Path);
574 verifyCars(rwTx, car1);
576 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
577 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
579 rwTx.delete(car1Path);
581 followerTestKit.doCommit(writeTxReady);
583 followerTestKit.doCommit(rwTx.ready());
587 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
591 public void testTransactionChainWithMultipleShards() throws Exception {
592 initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
594 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
596 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
597 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
599 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
600 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
602 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
603 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
605 followerTestKit.doCommit(writeTx.ready());
607 final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
609 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
610 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
611 readWriteTx.write(carPath, car);
613 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
614 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
615 readWriteTx.merge(personPath, person);
617 assertEquals(Optional.of(car), readWriteTx.read(carPath).get(5, TimeUnit.SECONDS));
618 assertEquals(Optional.of(person), readWriteTx.read(personPath).get(5, TimeUnit.SECONDS));
620 final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
622 writeTx = txChain.newWriteOnlyTransaction();
624 writeTx.delete(personPath);
626 final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
628 followerTestKit.doCommit(cohort2);
629 followerTestKit.doCommit(cohort3);
633 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
634 verifyCars(readTx, car);
636 assertEquals(Optional.empty(), readTx.read(personPath).get(5, TimeUnit.SECONDS));
640 public void testChainedTransactionFailureWithSingleShard() throws Exception {
641 initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
643 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
644 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
645 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
646 MoreExecutors.directExecutor());
648 final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
649 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
651 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
653 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
654 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
655 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
657 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
659 final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
661 assertThat(ex, instanceOf(TransactionCommitFailedException.class));
663 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
670 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
671 initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
673 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
674 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
675 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
676 MoreExecutors.directExecutor());
678 final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
679 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
681 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
683 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
685 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
686 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
687 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
689 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
690 // done for put for performance reasons.
691 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
693 final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
695 assertThat(ex, instanceOf(TransactionCommitFailedException.class));
697 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
704 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
705 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
706 final String testName = "testSingleShardTransactionsWithLeaderChanges";
707 initDatastoresWithCars(testName);
709 final String followerCarShardName = "member-2-shard-cars-" + testName;
710 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class);
712 // Write top-level car container from the follower so it uses a remote Tx.
714 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
716 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
717 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
719 followerTestKit.doCommit(writeTx.ready());
721 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
723 // Switch the leader to the follower
725 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
726 .shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
728 TestKit.shutdownActorSystem(leaderSystem, true);
729 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
731 followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorUtils(), CARS);
733 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
734 Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
736 final DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder()
737 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
738 IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder, commitTimeout);
740 try (AbstractDataStore ds =
741 newMember1TestKit.setupAbstractDataStore(
742 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS)) {
744 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), CARS);
746 // Write a car entry to the new leader - should switch to local Tx
748 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
750 MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
751 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
752 writeTx.merge(car1Path, car1);
754 followerTestKit.doCommit(writeTx.ready());
756 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
760 @SuppressWarnings("unchecked")
762 public void testReadyLocalTransactionForwardedToLeader() throws Exception {
763 initDatastoresWithCars("testReadyLocalTransactionForwardedToLeader");
764 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
766 final Optional<ActorRef> carsFollowerShard =
767 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
768 assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
770 final DataTree dataTree = new InMemoryDataTreeFactory().create(
771 DataTreeConfiguration.DEFAULT_OPERATIONAL, SchemaContextHelper.full());
773 // Send a tx with immediate commit.
775 DataTreeModification modification = dataTree.takeSnapshot().newModification();
776 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
777 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
779 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
780 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
781 modification.ready();
783 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(tx1 , modification, true, Optional.empty());
785 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
786 Object resp = followerTestKit.expectMsgClass(Object.class);
787 if (resp instanceof akka.actor.Status.Failure) {
788 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
791 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
793 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
795 // Send another tx without immediate commit.
797 modification = dataTree.takeSnapshot().newModification();
798 MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
799 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
800 modification.ready();
802 readyLocal = new ReadyLocalTransaction(tx2 , modification, false, Optional.empty());
804 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
805 resp = followerTestKit.expectMsgClass(Object.class);
806 if (resp instanceof akka.actor.Status.Failure) {
807 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
810 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
812 final ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
813 ((ReadyTransactionReply)resp).getCohortPath());
815 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(leaderDistributedDataStore.getActorUtils(),
816 List.of(new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor),
817 () -> DataStoreVersions.CURRENT_VERSION)), tx2);
818 cohort.canCommit().get(5, TimeUnit.SECONDS);
819 cohort.preCommit().get(5, TimeUnit.SECONDS);
820 cohort.commit().get(5, TimeUnit.SECONDS);
822 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
825 @SuppressWarnings("unchecked")
827 public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
828 initDatastoresWithCars("testForwardedReadyTransactionForwardedToLeader");
829 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
831 final Optional<ActorRef> carsFollowerShard =
832 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
833 assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
835 carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
836 final DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
838 // Send a tx with immediate commit.
840 DataTreeModification modification = dataTree.takeSnapshot().newModification();
841 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
842 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
844 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
845 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
847 ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction(tx1, DataStoreVersions.CURRENT_VERSION,
848 new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx1, modification),
849 true, Optional.empty());
851 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
852 Object resp = followerTestKit.expectMsgClass(Object.class);
853 if (resp instanceof akka.actor.Status.Failure) {
854 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
857 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
859 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
861 // Send another tx without immediate commit.
863 modification = dataTree.takeSnapshot().newModification();
864 MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
865 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
867 forwardedReady = new ForwardedReadyTransaction(tx2, DataStoreVersions.CURRENT_VERSION,
868 new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx2, modification),
869 false, Optional.empty());
871 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
872 resp = followerTestKit.expectMsgClass(Object.class);
873 if (resp instanceof akka.actor.Status.Failure) {
874 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
877 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
879 ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
880 ((ReadyTransactionReply)resp).getCohortPath());
882 final ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
883 leaderDistributedDataStore.getActorUtils(), List.of(
884 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor),
885 () -> DataStoreVersions.CURRENT_VERSION)), tx2);
886 cohort.canCommit().get(5, TimeUnit.SECONDS);
887 cohort.preCommit().get(5, TimeUnit.SECONDS);
888 cohort.commit().get(5, TimeUnit.SECONDS);
890 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
894 public void testTransactionForwardedToLeaderAfterRetry() throws Exception {
895 followerDatastoreContextBuilder.shardBatchedModificationCount(2);
896 leaderDatastoreContextBuilder.shardBatchedModificationCount(2);
897 initDatastoresWithCarsAndPeople("testTransactionForwardedToLeaderAfterRetry");
899 // Do an initial write to get the primary shard info cached.
901 final DOMStoreWriteTransaction initialWriteTx = followerDistributedDataStore.newWriteOnlyTransaction();
902 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
903 initialWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
904 followerTestKit.doCommit(initialWriteTx.ready());
906 // Wait for the commit to be replicated to the follower.
908 MemberNode.verifyRaftState(followerDistributedDataStore, "cars",
909 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
911 MemberNode.verifyRaftState(followerDistributedDataStore, "people",
912 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
914 // Prepare, ready and canCommit a WO tx that writes to 2 shards. This will become the current tx in
917 final DOMStoreWriteTransaction writeTx1 = followerDistributedDataStore.newWriteOnlyTransaction();
918 writeTx1.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
919 writeTx1.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
920 final DOMStoreThreePhaseCommitCohort writeTx1Cohort = writeTx1.ready();
921 final ListenableFuture<Boolean> writeTx1CanCommit = writeTx1Cohort.canCommit();
922 writeTx1CanCommit.get(5, TimeUnit.SECONDS);
924 // Prepare and ready another WO tx that writes to 2 shards but don't canCommit yet. This will be queued
925 // in the leader shard.
927 final DOMStoreWriteTransaction writeTx2 = followerDistributedDataStore.newWriteOnlyTransaction();
928 final LinkedList<MapEntryNode> cars = new LinkedList<>();
930 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
931 writeTx2.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
933 NormalizedNode people = ImmutableNodes.mapNodeBuilder(PeopleModel.PERSON_QNAME)
934 .withChild(PeopleModel.newPersonEntry("Dude")).build();
935 writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
936 final DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
938 // Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
939 // tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
940 // leader shard (with shardBatchedModificationCount set to 2). The 3rd BatchedModidifications will be
943 final DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
944 for (int i = 1; i <= 5; i++, carIndex++) {
945 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
946 writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
949 // Prepare another WO that writes to a single shard. This will send a single BatchedModidifications
952 final DOMStoreWriteTransaction writeTx4 = followerDistributedDataStore.newWriteOnlyTransaction();
953 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
954 writeTx4.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
957 // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaciton message to the
958 // leader shard on ready.
960 final DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
961 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
962 readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
964 // FIXME: CONTROLLER-2017: ClientBackedDataStore reports only 4 transactions
965 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
966 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
967 stats -> assertEquals("getReadWriteTransactionCount", 5, stats.getReadWriteTransactionCount()));
969 // Disable elections on the leader so it switches to follower.
971 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
972 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
973 .shardElectionTimeoutFactor(10));
975 leaderTestKit.waitUntilNoLeader(leaderDistributedDataStore.getActorUtils(), "cars");
977 // Submit all tx's - the messages should get queued for retry.
979 final ListenableFuture<Boolean> writeTx2CanCommit = writeTx2Cohort.canCommit();
980 final DOMStoreThreePhaseCommitCohort writeTx3Cohort = writeTx3.ready();
981 final DOMStoreThreePhaseCommitCohort writeTx4Cohort = writeTx4.ready();
982 final DOMStoreThreePhaseCommitCohort rwTxCohort = readWriteTx.ready();
984 // Enable elections on the other follower so it becomes the leader, at which point the
985 // tx's should get forwarded from the previous leader to the new leader to complete the commits.
987 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
988 .customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
989 IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorUtils(), "cars")
990 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
991 IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorUtils(), "people")
992 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
994 followerTestKit.doCommit(writeTx1CanCommit, writeTx1Cohort);
995 followerTestKit.doCommit(writeTx2CanCommit, writeTx2Cohort);
996 followerTestKit.doCommit(writeTx3Cohort);
997 followerTestKit.doCommit(writeTx4Cohort);
998 followerTestKit.doCommit(rwTxCohort);
1000 DOMStoreReadTransaction readTx = leaderDistributedDataStore.newReadOnlyTransaction();
1001 verifyCars(readTx, cars.toArray(new MapEntryNode[cars.size()]));
1002 verifyNode(readTx, PeopleModel.PERSON_LIST_PATH, people);
1006 public void testLeadershipTransferOnShutdown() throws Exception {
1007 leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
1008 followerDatastoreContextBuilder.shardElectionTimeoutFactor(10).customRaftPolicyImplementation(null);
1009 final String testName = "testLeadershipTransferOnShutdown";
1010 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS_AND_PEOPLE);
1012 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1013 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500),
1015 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1016 testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
1018 followerTestKit.waitForMembersUp("member-3");
1019 follower2TestKit.waitForMembersUp("member-1", "member-2");
1021 // Create and submit a couple tx's so they're pending.
1023 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
1024 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1025 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1026 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
1027 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
1029 final var usesCohorts = DistributedDataStore.class.isAssignableFrom(testParameter);
1031 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1032 stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
1035 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
1036 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
1037 writeTx.write(CarsModel.newCarPath("optima"), car);
1038 final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
1041 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1042 stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
1045 // Gracefully stop the leader via a Shutdown message.
1047 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1048 .shardElectionTimeoutFactor(100));
1050 final FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
1051 final Future<ActorRef> future = leaderDistributedDataStore.getActorUtils().findLocalShardAsync("cars");
1052 final ActorRef leaderActor = Await.result(future, duration);
1054 final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);
1056 // Commit the 2 transactions. They should finish and succeed.
1058 followerTestKit.doCommit(cohort1);
1059 followerTestKit.doCommit(cohort2);
1061 // Wait for the leader actor stopped.
1063 final Boolean stopped = Await.result(stopFuture, duration);
1064 assertEquals("Stopped", Boolean.TRUE, stopped);
1066 // Verify leadership was transferred by reading the committed data from the other nodes.
1068 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
1069 verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
1074 public void testTransactionWithIsolatedLeader() throws Exception {
1075 // FIXME: CONTROLLER-2018: remove when test passes also for ClientBackedDataStore
1076 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1078 // Set the isolated leader check interval high so we can control the switch to IsolatedLeader.
1079 leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(10000000);
1080 final String testName = "testTransactionWithIsolatedLeader";
1081 initDatastoresWithCars(testName);
1083 // Tx that is submitted after the follower is stopped but before the leader transitions to IsolatedLeader.
1084 final DOMStoreWriteTransaction preIsolatedLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1085 preIsolatedLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1087 // Tx that is submitted after the leader transitions to IsolatedLeader.
1088 final DOMStoreWriteTransaction noShardLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1089 noShardLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1091 // Tx that is submitted after the follower is reinstated.
1092 final DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1093 successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1095 // Stop the follower
1096 followerTestKit.watch(followerDistributedDataStore.getActorUtils().getShardManager());
1097 followerDistributedDataStore.close();
1098 followerTestKit.expectTerminated(followerDistributedDataStore.getActorUtils().getShardManager());
1100 // Submit the preIsolatedLeaderWriteTx so it's pending
1101 final DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
1103 // Change the isolated leader check interval low so it changes to IsolatedLeader.
1104 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1105 .shardIsolatedLeaderCheckIntervalInMillis(200));
1107 MemberNode.verifyRaftState(leaderDistributedDataStore, "cars",
1108 raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
1110 final var ex = assertThrows(ExecutionException.class,
1111 () -> leaderTestKit.doCommit(noShardLeaderWriteTx.ready()));
1112 assertEquals(NoShardLeaderException.class, Throwables.getRootCause(ex).getClass());
1114 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1115 .shardElectionTimeoutFactor(100));
1117 final DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
1119 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
1120 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
1122 leaderTestKit.doCommit(preIsolatedLeaderTxCohort);
1123 leaderTestKit.doCommit(successTxCohort);
1127 public void testTransactionWithShardLeaderNotResponding() throws Exception {
1128 followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1129 followerDatastoreContextBuilder.shardElectionTimeoutFactor(50);
1130 initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
1132 // Do an initial read to get the primary shard info cached.
1134 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1135 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1137 // Shutdown the leader and try to create a new tx.
1139 TestKit.shutdownActorSystem(leaderSystem, true);
1141 followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
1142 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
1144 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1146 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1148 final var ex = assertThrows(ExecutionException.class, () -> followerTestKit.doCommit(rwTx.ready()));
1149 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause());
1150 if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
1151 assertTrue(msg, Throwables.getRootCause(ex) instanceof NoShardLeaderException
1152 || ex.getCause() instanceof ShardLeaderNotRespondingException);
1154 assertThat(msg, Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
1159 public void testTransactionWithCreateTxFailureDueToNoLeader() throws Exception {
1160 followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1161 initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
1163 // Do an initial read to get the primary shard info cached.
1165 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1166 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1168 // Shutdown the leader and try to create a new tx.
1170 TestKit.shutdownActorSystem(leaderSystem, true);
1172 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1174 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
1176 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1177 .operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1179 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1181 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1183 final var ex = assertThrows(ExecutionException.class, () -> followerTestKit.doCommit(rwTx.ready()));
1184 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause());
1185 if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
1186 assertThat(msg, Throwables.getRootCause(ex), instanceOf(NoShardLeaderException.class));
1188 assertThat(msg, Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
1193 public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
1194 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
1195 String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
1196 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1198 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1199 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1200 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1201 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1203 try (AbstractDataStore ds =
1204 follower2TestKit.setupAbstractDataStore(
1205 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS)) {
1207 followerTestKit.waitForMembersUp("member-1", "member-3");
1208 follower2TestKit.waitForMembersUp("member-1", "member-2");
1210 // Do an initial read to get the primary shard info cached.
1212 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1213 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1215 // Shutdown the leader and try to create a new tx.
1217 TestKit.shutdownActorSystem(leaderSystem, true);
1219 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1221 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1222 .operationTimeoutInMillis(500).shardElectionTimeoutFactor(5).customRaftPolicyImplementation(null));
1224 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1226 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1228 followerTestKit.doCommit(rwTx.ready());
1233 public void testSemiReachableCandidateNotDroppingLeader() throws Exception {
1234 final String testName = "testSemiReachableCandidateNotDroppingLeader";
1235 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1237 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1238 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1239 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1240 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1242 final AbstractDataStore ds2 =
1243 follower2TestKit.setupAbstractDataStore(
1244 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS);
1246 followerTestKit.waitForMembersUp("member-1", "member-3");
1247 follower2TestKit.waitForMembersUp("member-1", "member-2");
1249 // behavior is controlled by akka.coordinated-shutdown.run-by-actor-system-terminate configuration option
1250 TestKit.shutdownActorSystem(follower2System, true);
1252 ActorRef cars = leaderDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1253 final OnDemandRaftState initialState = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1254 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1256 Cluster leaderCluster = Cluster.get(leaderSystem);
1257 Cluster followerCluster = Cluster.get(followerSystem);
1258 Cluster follower2Cluster = Cluster.get(follower2System);
1260 Member follower2Member = follower2Cluster.readView().self();
1262 await().atMost(10, TimeUnit.SECONDS)
1263 .until(() -> containsUnreachable(leaderCluster, follower2Member));
1264 await().atMost(10, TimeUnit.SECONDS)
1265 .until(() -> containsUnreachable(followerCluster, follower2Member));
1267 ActorRef followerCars = followerDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1269 // to simulate a follower not being able to receive messages, but still being able to send messages and becoming
1270 // candidate, we can just send a couple of RequestVotes to both leader and follower.
1271 cars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1272 followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1273 cars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1274 followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1276 OnDemandRaftState stateAfter = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1277 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1278 OnDemandRaftState followerState = (OnDemandRaftState) followerDistributedDataStore.getActorUtils()
1279 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1281 assertEquals(initialState.getCurrentTerm(), stateAfter.getCurrentTerm());
1282 assertEquals(initialState.getCurrentTerm(), followerState.getCurrentTerm());
1287 private static Boolean containsUnreachable(final Cluster cluster, final Member member) {
1288 // unreachableMembers() returns scala.collection.immutable.Set, but we are using scala.collection.Set to fix JDT
1289 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=468276#c32
1290 final Set<Member> members = cluster.readView().unreachableMembers();
1291 return members.contains(member);
1295 public void testInstallSnapshot() throws Exception {
1296 final String testName = "testInstallSnapshot";
1297 final String leaderCarShardName = "member-1-shard-cars-" + testName;
1298 final String followerCarShardName = "member-2-shard-cars-" + testName;
1300 // Setup a saved snapshot on the leader. The follower will startup with no data and the leader should
1301 // install a snapshot to sync the follower.
1303 DataTree tree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_CONFIGURATION,
1304 SchemaContextHelper.full());
1306 final ContainerNode carsNode = CarsModel.newCarsNode(
1307 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", Uint64.valueOf(20000))));
1308 AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
1310 final NormalizedNode snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.empty());
1311 final Snapshot initialSnapshot = Snapshot.create(
1312 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
1313 Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
1314 InMemorySnapshotStore.addSnapshot(leaderCarShardName, initialSnapshot);
1316 InMemorySnapshotStore.addSnapshotSavedLatch(leaderCarShardName);
1317 InMemorySnapshotStore.addSnapshotSavedLatch(followerCarShardName);
1319 initDatastoresWithCars(testName);
1321 assertEquals(Optional.of(carsNode), leaderDistributedDataStore.newReadOnlyTransaction().read(
1322 CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS));
1324 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(leaderCarShardName, Snapshot.class),
1325 initialSnapshot, snapshotRoot);
1327 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(followerCarShardName, Snapshot.class),
1328 initialSnapshot, snapshotRoot);
1332 public void testReadWriteMessageSlicing() throws Exception {
1333 // The slicing is only implemented for tell-based protocol
1334 assumeTrue(ClientBackedDataStore.class.isAssignableFrom(testParameter));
1336 leaderDatastoreContextBuilder.maximumMessageSliceSize(100);
1337 followerDatastoreContextBuilder.maximumMessageSliceSize(100);
1338 initDatastoresWithCars("testLargeReadReplySlicing");
1340 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1342 final NormalizedNode carsNode = CarsModel.create();
1343 rwTx.write(CarsModel.BASE_PATH, carsNode);
1345 verifyNode(rwTx, CarsModel.BASE_PATH, carsNode);
1348 @SuppressWarnings("IllegalCatch")
1350 public void testRaftCallbackDuringLeadershipDrop() throws Exception {
1351 final String testName = "testRaftCallbackDuringLeadershipDrop";
1352 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1354 final ExecutorService executor = Executors.newSingleThreadExecutor();
1356 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1357 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500)
1358 .shardLeaderElectionTimeoutInSeconds(3600),
1361 final DOMStoreWriteTransaction initialWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1362 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1363 leaderTestKit.doCommit(initialWriteTx.ready());
1365 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1366 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false)) {
1368 final ActorRef member3Cars = ((LocalShardStore) follower2DistributedDataStore).getLocalShards()
1369 .getLocalShards().get("cars").getActor();
1370 final ActorRef member2Cars = ((LocalShardStore)followerDistributedDataStore).getLocalShards()
1371 .getLocalShards().get("cars").getActor();
1372 member2Cars.tell(new StartDropMessages(AppendEntries.class), null);
1373 member3Cars.tell(new StartDropMessages(AppendEntries.class), null);
1375 final DOMStoreWriteTransaction newTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1376 newTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1377 final AtomicBoolean submitDone = new AtomicBoolean(false);
1378 executor.submit(() -> {
1380 leaderTestKit.doCommit(newTx.ready());
1381 submitDone.set(true);
1382 } catch (Exception e) {
1383 throw new RuntimeException(e);
1386 final ActorRef leaderCars = ((LocalShardStore) leaderDistributedDataStore).getLocalShards()
1387 .getLocalShards().get("cars").getActor();
1388 await().atMost(10, TimeUnit.SECONDS)
1389 .until(() -> ((OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1390 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE)).getLastIndex() >= 1);
1392 final OnDemandRaftState raftState = (OnDemandRaftState)leaderDistributedDataStore.getActorUtils()
1393 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE);
1395 // Simulate a follower not receiving heartbeats but still being able to send messages ie RequestVote with
1396 // new term(switching to candidate after election timeout)
1397 leaderCars.tell(new RequestVote(raftState.getCurrentTerm() + 1,
1398 "member-3-shard-cars-testRaftCallbackDuringLeadershipDrop", -1,
1401 member2Cars.tell(new StopDropMessages(AppendEntries.class), null);
1402 member3Cars.tell(new StopDropMessages(AppendEntries.class), null);
1404 await("Is tx stuck in COMMIT_PENDING")
1405 .atMost(10, TimeUnit.SECONDS).untilAtomic(submitDone, equalTo(true));
1409 executor.shutdownNow();
1413 public void testSnapshotOnRootOverwrite() throws Exception {
1414 initDatastores("testSnapshotOnRootOverwrite", "module-shards-default-cars-member1-and-2.conf",
1415 new String[] {"cars", "default"},
1416 leaderDatastoreContextBuilder.snapshotOnRootOverwrite(true),
1417 followerDatastoreContextBuilder.snapshotOnRootOverwrite(true));
1419 leaderTestKit.waitForMembersUp("member-2");
1420 final ContainerNode rootNode = ImmutableContainerNodeBuilder.create()
1421 .withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(SchemaContext.NAME))
1422 .withChild(CarsModel.create())
1425 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1427 // FIXME: CONTROLLER-2020: ClientBackedDatastore does not have stable indexes/term,
1428 // the snapshot index seems to fluctuate
1429 assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1430 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1431 state -> assertEquals(1, state.getSnapshotIndex()));
1433 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1434 state -> assertEquals(1, state.getSnapshotIndex()));
1436 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1437 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1439 for (int i = 0; i < 10; i++) {
1440 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, CarsModel.newCarPath("car " + i),
1441 CarsModel.newCarEntry("car " + i, Uint64.ONE));
1444 // fake snapshot causes the snapshotIndex to move
1445 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1446 state -> assertEquals(10, state.getSnapshotIndex()));
1447 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1448 state -> assertEquals(10, state.getSnapshotIndex()));
1450 // however the real snapshot still has not changed and was taken at index 1
1451 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1452 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1454 // root overwrite so expect a snapshot
1455 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1457 // this was a real snapshot so everything should be in it(1(DisableTrackingPayload) + 1 + 10 + 1)
1458 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1459 state -> assertEquals(12, state.getSnapshotIndex()));
1460 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1461 state -> assertEquals(12, state.getSnapshotIndex()));
1463 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 12);
1464 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 12);
1467 private static void verifySnapshot(final String persistenceId, final long lastAppliedIndex) {
1468 await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
1469 List<Snapshot> snap = InMemorySnapshotStore.getSnapshots(persistenceId, Snapshot.class);
1470 assertEquals(1, snap.size());
1471 assertEquals(lastAppliedIndex, snap.get(0).getLastAppliedIndex());
1476 private static void verifySnapshot(final Snapshot actual, final Snapshot expected,
1477 final NormalizedNode expRoot) {
1478 assertEquals("Snapshot getLastAppliedTerm", expected.getLastAppliedTerm(), actual.getLastAppliedTerm());
1479 assertEquals("Snapshot getLastAppliedIndex", expected.getLastAppliedIndex(), actual.getLastAppliedIndex());
1480 assertEquals("Snapshot getLastTerm", expected.getLastTerm(), actual.getLastTerm());
1481 assertEquals("Snapshot getLastIndex", expected.getLastIndex(), actual.getLastIndex());
1482 assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
1483 MetadataShardDataTreeSnapshot shardSnapshot =
1484 (MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
1485 assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
1488 private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1489 final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1490 final DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
1491 final Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1492 doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1493 doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(anyString());
1494 dataStore.onDatastoreContextUpdated(mockContextFactory);