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.Matchers.equalTo;
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertFalse;
14 import static org.junit.Assert.assertNotNull;
15 import static org.junit.Assert.assertTrue;
16 import static org.junit.Assert.fail;
17 import static org.mockito.ArgumentMatchers.any;
18 import static org.mockito.ArgumentMatchers.eq;
19 import static org.mockito.Mockito.timeout;
20 import static org.mockito.Mockito.verify;
22 import akka.actor.ActorRef;
23 import akka.actor.ActorSelection;
24 import akka.actor.ActorSystem;
25 import akka.actor.Address;
26 import akka.actor.AddressFromURIString;
27 import akka.cluster.Cluster;
28 import akka.cluster.Member;
29 import akka.dispatch.Futures;
30 import akka.pattern.Patterns;
31 import akka.testkit.javadsl.TestKit;
32 import com.google.common.base.Stopwatch;
33 import com.google.common.base.Throwables;
34 import com.google.common.collect.ImmutableMap;
35 import com.google.common.primitives.UnsignedLong;
36 import com.google.common.util.concurrent.ListenableFuture;
37 import com.google.common.util.concurrent.MoreExecutors;
38 import com.google.common.util.concurrent.Uninterruptibles;
39 import com.typesafe.config.ConfigFactory;
40 import java.util.Arrays;
41 import java.util.Collection;
42 import java.util.Collections;
43 import java.util.Iterator;
44 import java.util.LinkedList;
45 import java.util.List;
46 import java.util.Optional;
47 import java.util.concurrent.ExecutionException;
48 import java.util.concurrent.ExecutorService;
49 import java.util.concurrent.Executors;
50 import java.util.concurrent.TimeUnit;
51 import java.util.concurrent.atomic.AtomicBoolean;
52 import java.util.concurrent.atomic.AtomicLong;
53 import java.util.function.Supplier;
54 import org.junit.After;
55 import org.junit.Assume;
56 import org.junit.Before;
57 import org.junit.Ignore;
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.Mockito;
64 import org.mockito.stubbing.Answer;
65 import org.opendaylight.controller.cluster.access.client.RequestTimeoutException;
66 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
67 import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
68 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
69 import org.opendaylight.controller.cluster.databroker.TestClientBackedDataStore;
70 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
71 import org.opendaylight.controller.cluster.datastore.TestShard.RequestFrontendMetadata;
72 import org.opendaylight.controller.cluster.datastore.TestShard.StartDropMessages;
73 import org.opendaylight.controller.cluster.datastore.TestShard.StopDropMessages;
74 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
75 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
76 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
77 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
78 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
79 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
80 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
81 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
82 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
83 import org.opendaylight.controller.cluster.datastore.persisted.FrontendHistoryMetadata;
84 import org.opendaylight.controller.cluster.datastore.persisted.FrontendShardDataTreeSnapshotMetadata;
85 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
86 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
87 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
88 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
89 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
90 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
91 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
92 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
93 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
94 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
95 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
96 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
97 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
98 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
99 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
100 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
101 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
102 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
103 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
104 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
105 import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
106 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
107 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
108 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
109 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
110 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
111 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
112 import org.opendaylight.yangtools.yang.common.Uint64;
113 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
114 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
117 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
119 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
120 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
121 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
122 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
123 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
124 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
125 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
126 import scala.concurrent.Await;
127 import scala.concurrent.Future;
128 import scala.concurrent.duration.FiniteDuration;
131 * End-to-end distributed data store tests that exercise remote shards and transactions.
133 * @author Thomas Pantelis
135 @RunWith(Parameterized.class)
136 public class DistributedDataStoreRemotingIntegrationTest extends AbstractTest {
138 @Parameters(name = "{0}")
139 public static Collection<Object[]> data() {
140 return Arrays.asList(new Object[][] {
141 { TestDistributedDataStore.class, 7}, { TestClientBackedDataStore.class, 12 }
146 public Class<? extends AbstractDataStore> testParameter;
148 public int commitTimeout;
150 private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
151 private static final String[] CARS = {"cars"};
153 private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse(
154 "akka://cluster-test@127.0.0.1:2558");
155 private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse(
156 "akka://cluster-test@127.0.0.1:2559");
158 private static final String MODULE_SHARDS_CARS_ONLY_1_2 = "module-shards-cars-member-1-and-2.conf";
159 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2 = "module-shards-member1-and-2.conf";
160 private static final String MODULE_SHARDS_CARS_PEOPLE_1_2_3 = "module-shards-member1-and-2-and-3.conf";
161 private static final String MODULE_SHARDS_CARS_1_2_3 = "module-shards-cars-member-1-and-2-and-3.conf";
163 private ActorSystem leaderSystem;
164 private ActorSystem followerSystem;
165 private ActorSystem follower2System;
167 private final DatastoreContext.Builder leaderDatastoreContextBuilder =
168 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
170 private final DatastoreContext.Builder followerDatastoreContextBuilder =
171 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5)
172 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
173 private final TransactionIdentifier tx1 = nextTransactionId();
174 private final TransactionIdentifier tx2 = nextTransactionId();
176 private AbstractDataStore followerDistributedDataStore;
177 private AbstractDataStore leaderDistributedDataStore;
178 private IntegrationTestKit followerTestKit;
179 private IntegrationTestKit leaderTestKit;
182 public void setUp() {
183 InMemoryJournal.clear();
184 InMemorySnapshotStore.clear();
186 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
187 Cluster.get(leaderSystem).join(MEMBER_1_ADDRESS);
189 followerSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member2"));
190 Cluster.get(followerSystem).join(MEMBER_1_ADDRESS);
192 follower2System = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member3"));
193 Cluster.get(follower2System).join(MEMBER_1_ADDRESS);
197 public void tearDown() {
198 if (followerDistributedDataStore != null) {
199 leaderDistributedDataStore.close();
201 if (leaderDistributedDataStore != null) {
202 leaderDistributedDataStore.close();
205 TestKit.shutdownActorSystem(leaderSystem, true);
206 TestKit.shutdownActorSystem(followerSystem, true);
207 TestKit.shutdownActorSystem(follower2System,true);
209 InMemoryJournal.clear();
210 InMemorySnapshotStore.clear();
213 private void initDatastoresWithCars(final String type) throws Exception {
214 initDatastores(type, MODULE_SHARDS_CARS_ONLY_1_2, CARS);
217 private void initDatastoresWithCarsAndPeople(final String type) throws Exception {
218 initDatastores(type, MODULE_SHARDS_CARS_PEOPLE_1_2, CARS_AND_PEOPLE);
221 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards)
223 initDatastores(type, moduleShardsConfig, shards, leaderDatastoreContextBuilder,
224 followerDatastoreContextBuilder);
227 private void initDatastores(final String type, final String moduleShardsConfig, final String[] shards,
228 final DatastoreContext.Builder leaderBuilder, final DatastoreContext.Builder followerBuilder)
230 leaderTestKit = new IntegrationTestKit(leaderSystem, leaderBuilder, commitTimeout);
232 leaderDistributedDataStore = leaderTestKit.setupAbstractDataStore(
233 testParameter, type, moduleShardsConfig, false, shards);
235 followerTestKit = new IntegrationTestKit(followerSystem, followerBuilder, commitTimeout);
236 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
237 testParameter, type, moduleShardsConfig, false, shards);
239 leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorUtils(), shards);
241 leaderTestKit.waitForMembersUp("member-2");
242 followerTestKit.waitForMembersUp("member-1");
245 private static void verifyCars(final DOMStoreReadTransaction readTx, final MapEntryNode... entries)
247 final Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
248 assertTrue("isPresent", optional.isPresent());
250 final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(
251 CarsModel.CAR_QNAME);
252 for (final NormalizedNode<?, ?> entry: entries) {
253 listBuilder.withChild((MapEntryNode) entry);
256 assertEquals("Car list node", listBuilder.build(), optional.get());
259 private static void verifyNode(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path,
260 final NormalizedNode<?, ?> expNode) throws Exception {
261 final Optional<NormalizedNode<?, ?>> optional = readTx.read(path).get(5, TimeUnit.SECONDS);
262 assertTrue("isPresent", optional.isPresent());
263 assertEquals("Data node", expNode, optional.get());
266 private static void verifyExists(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path)
268 final Boolean exists = readTx.exists(path).get(5, TimeUnit.SECONDS);
269 assertEquals("exists", Boolean.TRUE, exists);
273 public void testWriteTransactionWithSingleShard() throws Exception {
274 final String testName = "testWriteTransactionWithSingleShard";
275 initDatastoresWithCars(testName);
277 final String followerCarShardName = "member-2-shard-cars-" + testName;
279 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
280 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
282 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
283 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
285 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
286 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
287 writeTx.merge(car1Path, car1);
289 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
290 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
291 writeTx.merge(car2Path, car2);
293 followerTestKit.doCommit(writeTx.ready());
295 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
297 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
301 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
303 writeTx.delete(car1Path);
305 followerTestKit.doCommit(writeTx.ready());
307 verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
309 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
311 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
313 // Re-instate the follower member 2 as a single-node to verify replication and recovery.
315 // The following is a bit tricky. Before we reinstate the follower we need to ensure it has persisted and
316 // applied and all the log entries from the leader. Since we've verified the car data above we know that
317 // all the transactions have been applied on the leader so we first read and capture its lastAppliedIndex.
318 final AtomicLong leaderLastAppliedIndex = new AtomicLong();
319 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, CARS[0],
320 state -> leaderLastAppliedIndex.set(state.getLastApplied()));
322 // Now we need to make sure the follower has persisted the leader's lastAppliedIndex via ApplyJournalEntries.
323 // However we don't know exactly how many ApplyJournalEntries messages there will be as it can differ between
324 // the tell-based and ask-based front-ends. For ask-based there will be exactly 2 ApplyJournalEntries but
325 // tell-based persists additional payloads which could be replicated and applied in a batch resulting in
326 // either 2 or 3 ApplyJournalEntries. To handle this we read the follower's persisted ApplyJournalEntries
327 // until we find the one that encompasses the leader's lastAppliedIndex.
328 Stopwatch sw = Stopwatch.createStarted();
329 boolean done = false;
331 final List<ApplyJournalEntries> entries = InMemoryJournal.get(followerCarShardName,
332 ApplyJournalEntries.class);
333 for (ApplyJournalEntries aje: entries) {
334 if (aje.getToIndex() >= leaderLastAppliedIndex.get()) {
340 assertTrue("Follower did not persist ApplyJournalEntries containing leader's lastAppliedIndex "
341 + leaderLastAppliedIndex + ". Entries persisted: " + entries, sw.elapsed(TimeUnit.SECONDS) <= 5);
343 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
346 TestKit.shutdownActorSystem(leaderSystem, true);
347 TestKit.shutdownActorSystem(followerSystem, true);
349 final ActorSystem newSystem = newActorSystem("reinstated-member2", "Member2");
351 try (AbstractDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder,
353 .setupAbstractDataStore(testParameter, testName, "module-shards-member2", true, CARS)) {
354 verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
359 public void testSingleTransactionsWritesInQuickSuccession() throws Exception {
360 final String testName = "testWriteTransactionWithSingleShard";
361 initDatastoresWithCars(testName);
363 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
365 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
366 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
367 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
368 followerTestKit.doCommit(writeTx.ready());
371 for (int i = 0; i < numCars; i++) {
372 writeTx = txChain.newWriteOnlyTransaction();
373 writeTx.write(CarsModel.newCarPath("car" + i),
374 CarsModel.newCarEntry("car" + i, Uint64.valueOf(20000)));
376 followerTestKit.doCommit(writeTx.ready());
378 DOMStoreReadTransaction domStoreReadTransaction = txChain.newReadOnlyTransaction();
379 domStoreReadTransaction.read(CarsModel.BASE_PATH).get();
381 domStoreReadTransaction.close();
384 // wait to let the shard catch up with purged
385 await("Range set leak test").atMost(5, TimeUnit.SECONDS)
386 .pollInterval(500, TimeUnit.MILLISECONDS)
387 .untilAsserted(() -> {
388 Optional<ActorRef> localShard =
389 leaderDistributedDataStore.getActorUtils().findLocalShard("cars");
390 FrontendShardDataTreeSnapshotMetadata frontendMetadata =
391 (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
392 .executeOperation(localShard.get(), new RequestFrontendMetadata());
394 if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
395 Iterator<FrontendHistoryMetadata> iterator =
396 frontendMetadata.getClients().get(0).getCurrentHistories().iterator();
397 FrontendHistoryMetadata metadata = iterator.next();
398 while (iterator.hasNext() && metadata.getHistoryId() != 1) {
399 metadata = iterator.next();
402 assertEquals(0, metadata.getClosedTransactions().size());
404 final var purgedRanges = metadata.getPurgedTransactions().ranges();
405 assertEquals(1, purgedRanges.size());
406 final var purgedRange = purgedRanges.first();
407 assertEquals(UnsignedLong.ZERO, purgedRange.lower());
408 assertEquals(UnsignedLong.valueOf(10), purgedRange.upper());
410 // ask based should track no metadata
411 assertTrue(frontendMetadata.getClients().get(0).getCurrentHistories().isEmpty());
415 final Optional<NormalizedNode<?, ?>> optional = txChain.newReadOnlyTransaction()
416 .read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
417 assertTrue("isPresent", optional.isPresent());
418 assertEquals("# cars", numCars, ((Collection<?>) optional.get().getValue()).size());
422 @Ignore("Flushes out tell based leak needs to be handled separately")
423 public void testCloseTransactionMetadataLeak() throws Exception {
424 // Ask based frontend seems to have some issues with back to back close
425 Assume.assumeTrue(testParameter.isAssignableFrom(TestClientBackedDataStore.class));
427 final String testName = "testWriteTransactionWithSingleShard";
428 initDatastoresWithCars(testName);
430 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
432 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
433 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
434 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
435 followerTestKit.doCommit(writeTx.ready());
438 for (int i = 0; i < numCars; i++) {
439 writeTx = txChain.newWriteOnlyTransaction();
442 DOMStoreReadTransaction domStoreReadTransaction = txChain.newReadOnlyTransaction();
443 domStoreReadTransaction.read(CarsModel.BASE_PATH).get();
445 domStoreReadTransaction.close();
448 writeTx = txChain.newWriteOnlyTransaction();
449 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
450 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
451 followerTestKit.doCommit(writeTx.ready());
453 // wait to let the shard catch up with purged
454 await("Close transaction purge leak test.").atMost(5, TimeUnit.SECONDS)
455 .pollInterval(500, TimeUnit.MILLISECONDS)
456 .untilAsserted(() -> {
457 Optional<ActorRef> localShard =
458 leaderDistributedDataStore.getActorUtils().findLocalShard("cars");
459 FrontendShardDataTreeSnapshotMetadata frontendMetadata =
460 (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
461 .executeOperation(localShard.get(), new RequestFrontendMetadata());
463 if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
464 Iterator<FrontendHistoryMetadata> iterator =
465 frontendMetadata.getClients().get(0).getCurrentHistories().iterator();
466 FrontendHistoryMetadata metadata = iterator.next();
467 while (iterator.hasNext() && metadata.getHistoryId() != 1) {
468 metadata = iterator.next();
471 assertEquals(0, metadata.getClosedTransactions().size());
472 assertEquals(1, metadata.getPurgedTransactions().size());
474 // ask based should track no metadata
475 assertTrue(frontendMetadata.getClients().get(0).getCurrentHistories().isEmpty());
479 final Optional<NormalizedNode<?, ?>> optional = txChain.newReadOnlyTransaction()
480 .read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
481 assertTrue("isPresent", optional.isPresent());
482 assertEquals("# cars", numCars, ((Collection<?>) optional.get().getValue()).size());
486 public void testReadWriteTransactionWithSingleShard() throws Exception {
487 initDatastoresWithCars("testReadWriteTransactionWithSingleShard");
489 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
490 assertNotNull("newReadWriteTransaction returned null", rwTx);
492 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
493 rwTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
495 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
496 rwTx.merge(CarsModel.newCarPath("optima"), car1);
498 verifyCars(rwTx, car1);
500 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
501 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
502 rwTx.merge(car2Path, car2);
504 verifyExists(rwTx, car2Path);
506 followerTestKit.doCommit(rwTx.ready());
508 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
512 public void testWriteTransactionWithMultipleShards() throws Exception {
513 initDatastoresWithCarsAndPeople("testWriteTransactionWithMultipleShards");
515 final DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
516 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
518 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
519 final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
520 writeTx.write(carsPath, carsNode);
522 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
523 final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
524 writeTx.write(peoplePath, peopleNode);
526 followerTestKit.doCommit(writeTx.ready());
528 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
530 verifyNode(readTx, carsPath, carsNode);
531 verifyNode(readTx, peoplePath, peopleNode);
535 public void testReadWriteTransactionWithMultipleShards() throws Exception {
536 initDatastoresWithCarsAndPeople("testReadWriteTransactionWithMultipleShards");
538 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
539 assertNotNull("newReadWriteTransaction returned null", rwTx);
541 final YangInstanceIdentifier carsPath = CarsModel.BASE_PATH;
542 final NormalizedNode<?, ?> carsNode = CarsModel.emptyContainer();
543 rwTx.write(carsPath, carsNode);
545 final YangInstanceIdentifier peoplePath = PeopleModel.BASE_PATH;
546 final NormalizedNode<?, ?> peopleNode = PeopleModel.emptyContainer();
547 rwTx.write(peoplePath, peopleNode);
549 followerTestKit.doCommit(rwTx.ready());
551 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
553 verifyNode(readTx, carsPath, carsNode);
554 verifyNode(readTx, peoplePath, peopleNode);
558 public void testTransactionChainWithSingleShard() throws Exception {
559 initDatastoresWithCars("testTransactionChainWithSingleShard");
561 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
563 // Add the top-level cars container with write-only.
565 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
566 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
568 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
570 final DOMStoreThreePhaseCommitCohort writeTxReady = writeTx.ready();
572 // Verify the top-level cars container with read-only.
574 verifyNode(txChain.newReadOnlyTransaction(), CarsModel.BASE_PATH, CarsModel.emptyContainer());
576 // Perform car operations with read-write.
578 final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
580 verifyNode(rwTx, CarsModel.BASE_PATH, CarsModel.emptyContainer());
582 rwTx.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
584 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
585 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
586 rwTx.write(car1Path, car1);
588 verifyExists(rwTx, car1Path);
590 verifyCars(rwTx, car1);
592 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
593 rwTx.merge(CarsModel.newCarPath("sportage"), car2);
595 rwTx.delete(car1Path);
597 followerTestKit.doCommit(writeTxReady);
599 followerTestKit.doCommit(rwTx.ready());
603 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
607 public void testTransactionChainWithMultipleShards() throws Exception {
608 initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
610 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
612 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
613 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
615 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
616 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
618 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
619 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
621 followerTestKit.doCommit(writeTx.ready());
623 final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
625 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
626 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
627 readWriteTx.write(carPath, car);
629 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
630 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
631 readWriteTx.merge(personPath, person);
633 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
634 assertTrue("isPresent", optional.isPresent());
635 assertEquals("Data node", car, optional.get());
637 optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
638 assertTrue("isPresent", optional.isPresent());
639 assertEquals("Data node", person, optional.get());
641 final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
643 writeTx = txChain.newWriteOnlyTransaction();
645 writeTx.delete(personPath);
647 final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
649 followerTestKit.doCommit(cohort2);
650 followerTestKit.doCommit(cohort3);
654 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
655 verifyCars(readTx, car);
657 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
658 assertFalse("isPresent", optional.isPresent());
662 public void testChainedTransactionFailureWithSingleShard() throws Exception {
663 initDatastoresWithCars("testChainedTransactionFailureWithSingleShard");
665 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
666 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
667 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
668 MoreExecutors.directExecutor());
670 final DOMTransactionChainListener listener = Mockito.mock(DOMTransactionChainListener.class);
671 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
673 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
675 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
676 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
677 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
679 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
682 writeTx.commit().get(5, TimeUnit.SECONDS);
683 fail("Expected TransactionCommitFailedException");
684 } catch (final ExecutionException e) {
688 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
695 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
696 initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
698 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
699 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
700 LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
701 MoreExecutors.directExecutor());
703 final DOMTransactionChainListener listener = Mockito.mock(DOMTransactionChainListener.class);
704 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
706 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
708 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
710 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
711 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
712 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
714 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
715 // done for put for performance reasons.
716 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
719 writeTx.commit().get(5, TimeUnit.SECONDS);
720 fail("Expected TransactionCommitFailedException");
721 } catch (final ExecutionException e) {
725 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
732 public void testSingleShardTransactionsWithLeaderChanges() throws Exception {
733 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
734 final String testName = "testSingleShardTransactionsWithLeaderChanges";
735 initDatastoresWithCars(testName);
737 final String followerCarShardName = "member-2-shard-cars-" + testName;
738 InMemoryJournal.addWriteMessagesCompleteLatch(followerCarShardName, 1, ApplyJournalEntries.class);
740 // Write top-level car container from the follower so it uses a remote Tx.
742 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
744 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
745 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
747 followerTestKit.doCommit(writeTx.ready());
749 InMemoryJournal.waitForWriteMessagesComplete(followerCarShardName);
751 // Switch the leader to the follower
753 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
754 .shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
756 TestKit.shutdownActorSystem(leaderSystem, true);
757 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
759 followerTestKit.waitUntilNoLeader(followerDistributedDataStore.getActorUtils(), CARS);
761 leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
762 Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
764 final DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder()
765 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
766 IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder, commitTimeout);
768 try (AbstractDataStore ds =
769 newMember1TestKit.setupAbstractDataStore(
770 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS)) {
772 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), CARS);
774 // Write a car entry to the new leader - should switch to local Tx
776 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
778 MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
779 YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
780 writeTx.merge(car1Path, car1);
782 followerTestKit.doCommit(writeTx.ready());
784 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1);
788 @SuppressWarnings("unchecked")
790 public void testReadyLocalTransactionForwardedToLeader() throws Exception {
791 initDatastoresWithCars("testReadyLocalTransactionForwardedToLeader");
792 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
794 final Optional<ActorRef> carsFollowerShard =
795 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
796 assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
798 final DataTree dataTree = new InMemoryDataTreeFactory().create(
799 DataTreeConfiguration.DEFAULT_OPERATIONAL, SchemaContextHelper.full());
801 // Send a tx with immediate commit.
803 DataTreeModification modification = dataTree.takeSnapshot().newModification();
804 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
805 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
807 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
808 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
809 modification.ready();
811 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(tx1 , modification, true, Optional.empty());
813 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
814 Object resp = followerTestKit.expectMsgClass(Object.class);
815 if (resp instanceof akka.actor.Status.Failure) {
816 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
819 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
821 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
823 // Send another tx without immediate commit.
825 modification = dataTree.takeSnapshot().newModification();
826 MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
827 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
828 modification.ready();
830 readyLocal = new ReadyLocalTransaction(tx2 , modification, false, Optional.empty());
832 carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
833 resp = followerTestKit.expectMsgClass(Object.class);
834 if (resp instanceof akka.actor.Status.Failure) {
835 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
838 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
840 final ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
841 ((ReadyTransactionReply)resp).getCohortPath());
843 final Supplier<Short> versionSupplier = Mockito.mock(Supplier.class);
844 Mockito.doReturn(DataStoreVersions.CURRENT_VERSION).when(versionSupplier).get();
845 ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
846 leaderDistributedDataStore.getActorUtils(), Arrays.asList(
847 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor), versionSupplier)), tx2);
848 cohort.canCommit().get(5, TimeUnit.SECONDS);
849 cohort.preCommit().get(5, TimeUnit.SECONDS);
850 cohort.commit().get(5, TimeUnit.SECONDS);
852 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
855 @SuppressWarnings("unchecked")
857 public void testForwardedReadyTransactionForwardedToLeader() throws Exception {
858 initDatastoresWithCars("testForwardedReadyTransactionForwardedToLeader");
859 followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), "cars");
861 final Optional<ActorRef> carsFollowerShard =
862 followerDistributedDataStore.getActorUtils().findLocalShard("cars");
863 assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
865 carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
866 final DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
868 // Send a tx with immediate commit.
870 DataTreeModification modification = dataTree.takeSnapshot().newModification();
871 new WriteModification(CarsModel.BASE_PATH, CarsModel.emptyContainer()).apply(modification);
872 new MergeModification(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()).apply(modification);
874 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
875 new WriteModification(CarsModel.newCarPath("optima"), car1).apply(modification);
877 ForwardedReadyTransaction forwardedReady = new ForwardedReadyTransaction(tx1,
878 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
879 Mockito.mock(ShardDataTreeTransactionParent.class), tx1, modification), true,
882 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
883 Object resp = followerTestKit.expectMsgClass(Object.class);
884 if (resp instanceof akka.actor.Status.Failure) {
885 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
888 assertEquals("Response type", CommitTransactionReply.class, resp.getClass());
890 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1);
892 // Send another tx without immediate commit.
894 modification = dataTree.takeSnapshot().newModification();
895 MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(30000));
896 new WriteModification(CarsModel.newCarPath("sportage"), car2).apply(modification);
898 forwardedReady = new ForwardedReadyTransaction(tx2,
899 DataStoreVersions.CURRENT_VERSION, new ReadWriteShardDataTreeTransaction(
900 Mockito.mock(ShardDataTreeTransactionParent.class), tx2, modification), false,
903 carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
904 resp = followerTestKit.expectMsgClass(Object.class);
905 if (resp instanceof akka.actor.Status.Failure) {
906 throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
909 assertEquals("Response type", ReadyTransactionReply.class, resp.getClass());
911 ActorSelection txActor = leaderDistributedDataStore.getActorUtils().actorSelection(
912 ((ReadyTransactionReply)resp).getCohortPath());
914 final Supplier<Short> versionSupplier = Mockito.mock(Supplier.class);
915 Mockito.doReturn(DataStoreVersions.CURRENT_VERSION).when(versionSupplier).get();
916 final ThreePhaseCommitCohortProxy cohort = new ThreePhaseCommitCohortProxy(
917 leaderDistributedDataStore.getActorUtils(), Arrays.asList(
918 new ThreePhaseCommitCohortProxy.CohortInfo(Futures.successful(txActor), versionSupplier)), tx2);
919 cohort.canCommit().get(5, TimeUnit.SECONDS);
920 cohort.preCommit().get(5, TimeUnit.SECONDS);
921 cohort.commit().get(5, TimeUnit.SECONDS);
923 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
927 public void testTransactionForwardedToLeaderAfterRetry() throws Exception {
928 // FIXME: remove when test passes also for ClientBackedDataStore
929 Assume.assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
930 followerDatastoreContextBuilder.shardBatchedModificationCount(2);
931 leaderDatastoreContextBuilder.shardBatchedModificationCount(2);
932 initDatastoresWithCarsAndPeople("testTransactionForwardedToLeaderAfterRetry");
934 // Do an initial write to get the primary shard info cached.
936 final DOMStoreWriteTransaction initialWriteTx = followerDistributedDataStore.newWriteOnlyTransaction();
937 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
938 initialWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
939 followerTestKit.doCommit(initialWriteTx.ready());
941 // Wait for the commit to be replicated to the follower.
943 MemberNode.verifyRaftState(followerDistributedDataStore, "cars",
944 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
946 MemberNode.verifyRaftState(followerDistributedDataStore, "people",
947 raftState -> assertEquals("getLastApplied", 1, raftState.getLastApplied()));
949 // Prepare, ready and canCommit a WO tx that writes to 2 shards. This will become the current tx in
952 final DOMStoreWriteTransaction writeTx1 = followerDistributedDataStore.newWriteOnlyTransaction();
953 writeTx1.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
954 writeTx1.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
955 final DOMStoreThreePhaseCommitCohort writeTx1Cohort = writeTx1.ready();
956 final ListenableFuture<Boolean> writeTx1CanCommit = writeTx1Cohort.canCommit();
957 writeTx1CanCommit.get(5, TimeUnit.SECONDS);
959 // Prepare and ready another WO tx that writes to 2 shards but don't canCommit yet. This will be queued
960 // in the leader shard.
962 final DOMStoreWriteTransaction writeTx2 = followerDistributedDataStore.newWriteOnlyTransaction();
963 final LinkedList<MapEntryNode> cars = new LinkedList<>();
965 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
966 writeTx2.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
968 NormalizedNode<?, ?> people = ImmutableNodes.mapNodeBuilder(PeopleModel.PERSON_QNAME)
969 .withChild(PeopleModel.newPersonEntry("Dude")).build();
970 writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
971 final DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
973 // Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
974 // tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
975 // leader shard (with shardBatchedModificationCount set to 2). The 3rd BatchedModidifications will be
978 final DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
979 for (int i = 1; i <= 5; i++, carIndex++) {
980 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
981 writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
984 // Prepare another WO that writes to a single shard. This will send a single BatchedModidifications
987 final DOMStoreWriteTransaction writeTx4 = followerDistributedDataStore.newWriteOnlyTransaction();
988 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
989 writeTx4.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
992 // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaciton message to the
993 // leader shard on ready.
995 final DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
996 cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
997 readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
999 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1000 stats -> assertEquals("getReadWriteTransactionCount", 5, stats.getReadWriteTransactionCount()));
1002 // Disable elections on the leader so it switches to follower.
1004 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1005 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
1006 .shardElectionTimeoutFactor(10));
1008 leaderTestKit.waitUntilNoLeader(leaderDistributedDataStore.getActorUtils(), "cars");
1010 // Submit all tx's - the messages should get queued for retry.
1012 final ListenableFuture<Boolean> writeTx2CanCommit = writeTx2Cohort.canCommit();
1013 final DOMStoreThreePhaseCommitCohort writeTx3Cohort = writeTx3.ready();
1014 final DOMStoreThreePhaseCommitCohort writeTx4Cohort = writeTx4.ready();
1015 final DOMStoreThreePhaseCommitCohort rwTxCohort = readWriteTx.ready();
1017 // Enable elections on the other follower so it becomes the leader, at which point the
1018 // tx's should get forwarded from the previous leader to the new leader to complete the commits.
1020 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1021 .customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
1022 IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorUtils(), "cars")
1023 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
1024 IntegrationTestKit.findLocalShard(followerDistributedDataStore.getActorUtils(), "people")
1025 .tell(TimeoutNow.INSTANCE, ActorRef.noSender());
1027 followerTestKit.doCommit(writeTx1CanCommit, writeTx1Cohort);
1028 followerTestKit.doCommit(writeTx2CanCommit, writeTx2Cohort);
1029 followerTestKit.doCommit(writeTx3Cohort);
1030 followerTestKit.doCommit(writeTx4Cohort);
1031 followerTestKit.doCommit(rwTxCohort);
1033 DOMStoreReadTransaction readTx = leaderDistributedDataStore.newReadOnlyTransaction();
1034 verifyCars(readTx, cars.toArray(new MapEntryNode[cars.size()]));
1035 verifyNode(readTx, PeopleModel.PERSON_LIST_PATH, people);
1039 public void testLeadershipTransferOnShutdown() throws Exception {
1040 // FIXME: remove when test passes also for ClientBackedDataStore
1041 Assume.assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1042 leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
1043 followerDatastoreContextBuilder.shardElectionTimeoutFactor(10).customRaftPolicyImplementation(null);
1044 final String testName = "testLeadershipTransferOnShutdown";
1045 initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS_AND_PEOPLE);
1047 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1048 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500),
1050 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1051 testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
1053 followerTestKit.waitForMembersUp("member-3");
1054 follower2TestKit.waitForMembersUp("member-1", "member-2");
1056 // Create and submit a couple tx's so they're pending.
1058 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
1059 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1060 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1061 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
1062 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
1064 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1065 stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
1067 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
1068 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
1069 writeTx.write(CarsModel.newCarPath("optima"), car);
1070 final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
1072 IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
1073 stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
1075 // Gracefully stop the leader via a Shutdown message.
1077 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1078 .shardElectionTimeoutFactor(100));
1080 final FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
1081 final Future<ActorRef> future = leaderDistributedDataStore.getActorUtils().findLocalShardAsync("cars");
1082 final ActorRef leaderActor = Await.result(future, duration);
1084 final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);
1086 // Commit the 2 transactions. They should finish and succeed.
1088 followerTestKit.doCommit(cohort1);
1089 followerTestKit.doCommit(cohort2);
1091 // Wait for the leader actor stopped.
1093 final Boolean stopped = Await.result(stopFuture, duration);
1094 assertEquals("Stopped", Boolean.TRUE, stopped);
1096 // Verify leadership was transferred by reading the committed data from the other nodes.
1098 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
1099 verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
1104 public void testTransactionWithIsolatedLeader() throws Exception {
1105 // FIXME: remove when test passes also for ClientBackedDataStore
1106 Assume.assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
1107 // Set the isolated leader check interval high so we can control the switch to IsolatedLeader.
1108 leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(10000000);
1109 final String testName = "testTransactionWithIsolatedLeader";
1110 initDatastoresWithCars(testName);
1112 // Tx that is submitted after the follower is stopped but before the leader transitions to IsolatedLeader.
1113 final DOMStoreWriteTransaction preIsolatedLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1114 preIsolatedLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1116 // Tx that is submitted after the leader transitions to IsolatedLeader.
1117 final DOMStoreWriteTransaction noShardLeaderWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1118 noShardLeaderWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1120 // Tx that is submitted after the follower is reinstated.
1121 final DOMStoreWriteTransaction successWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1122 successWriteTx.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1124 // Stop the follower
1125 followerTestKit.watch(followerDistributedDataStore.getActorUtils().getShardManager());
1126 followerDistributedDataStore.close();
1127 followerTestKit.expectTerminated(followerDistributedDataStore.getActorUtils().getShardManager());
1129 // Submit the preIsolatedLeaderWriteTx so it's pending
1130 final DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
1132 // Change the isolated leader check interval low so it changes to IsolatedLeader.
1133 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1134 .shardIsolatedLeaderCheckIntervalInMillis(200));
1136 MemberNode.verifyRaftState(leaderDistributedDataStore, "cars",
1137 raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
1140 leaderTestKit.doCommit(noShardLeaderWriteTx.ready());
1141 fail("Expected NoShardLeaderException");
1142 } catch (final ExecutionException e) {
1143 assertEquals("getCause", NoShardLeaderException.class, Throwables.getRootCause(e).getClass());
1146 sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
1147 .shardElectionTimeoutFactor(100));
1149 final DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
1151 followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
1152 testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
1154 leaderTestKit.doCommit(preIsolatedLeaderTxCohort);
1155 leaderTestKit.doCommit(successTxCohort);
1159 public void testTransactionWithShardLeaderNotResponding() throws Exception {
1160 followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1161 followerDatastoreContextBuilder.shardElectionTimeoutFactor(50);
1162 initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
1164 // Do an initial read to get the primary shard info cached.
1166 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1167 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1169 // Shutdown the leader and try to create a new tx.
1171 TestKit.shutdownActorSystem(leaderSystem, true);
1173 followerDatastoreContextBuilder.operationTimeoutInMillis(50).shardElectionTimeoutFactor(1);
1174 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder);
1176 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1178 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1181 followerTestKit.doCommit(rwTx.ready());
1182 fail("Exception expected");
1183 } catch (final ExecutionException e) {
1184 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(e.getCause());
1185 if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
1186 assertTrue(msg, Throwables.getRootCause(e) instanceof NoShardLeaderException
1187 || e.getCause() instanceof ShardLeaderNotRespondingException);
1189 assertTrue(msg, Throwables.getRootCause(e) instanceof RequestTimeoutException);
1195 public void testTransactionWithCreateTxFailureDueToNoLeader() throws Exception {
1196 followerDatastoreContextBuilder.frontendRequestTimeoutInSeconds(2);
1197 initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
1199 // Do an initial read to get the primary shard info cached.
1201 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1202 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1204 // Shutdown the leader and try to create a new tx.
1206 TestKit.shutdownActorSystem(leaderSystem, true);
1208 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1210 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
1212 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1213 .operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
1215 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1217 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1220 followerTestKit.doCommit(rwTx.ready());
1221 fail("Exception expected");
1222 } catch (final ExecutionException e) {
1223 final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(e.getCause());
1224 if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
1225 assertTrue(msg, Throwables.getRootCause(e) instanceof NoShardLeaderException);
1227 assertTrue(msg, Throwables.getRootCause(e) instanceof RequestTimeoutException);
1233 public void testTransactionRetryWithInitialAskTimeoutExOnCreateTx() throws Exception {
1234 followerDatastoreContextBuilder.backendAlivenessTimerIntervalInSeconds(2);
1235 String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
1236 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1238 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1239 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1240 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1241 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1243 try (AbstractDataStore ds =
1244 follower2TestKit.setupAbstractDataStore(
1245 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS)) {
1247 followerTestKit.waitForMembersUp("member-1", "member-3");
1248 follower2TestKit.waitForMembersUp("member-1", "member-2");
1250 // Do an initial read to get the primary shard info cached.
1252 final DOMStoreReadTransaction readTx = followerDistributedDataStore.newReadOnlyTransaction();
1253 readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1255 // Shutdown the leader and try to create a new tx.
1257 TestKit.shutdownActorSystem(leaderSystem, true);
1259 Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
1261 sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
1262 .operationTimeoutInMillis(500).shardElectionTimeoutFactor(5).customRaftPolicyImplementation(null));
1264 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1266 rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1268 followerTestKit.doCommit(rwTx.ready());
1273 public void testSemiReachableCandidateNotDroppingLeader() throws Exception {
1274 final String testName = "testSemiReachableCandidateNotDroppingLeader";
1275 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1277 final DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
1278 .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10);
1279 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
1280 follower2System, follower2DatastoreContextBuilder, commitTimeout);
1282 final AbstractDataStore ds2 =
1283 follower2TestKit.setupAbstractDataStore(
1284 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS);
1286 followerTestKit.waitForMembersUp("member-1", "member-3");
1287 follower2TestKit.waitForMembersUp("member-1", "member-2");
1289 // behavior is controlled by akka.coordinated-shutdown.run-by-actor-system-terminate configuration option
1290 TestKit.shutdownActorSystem(follower2System, true);
1292 ActorRef cars = leaderDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1293 final OnDemandRaftState initialState = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1294 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1296 Cluster leaderCluster = Cluster.get(leaderSystem);
1297 Cluster followerCluster = Cluster.get(followerSystem);
1298 Cluster follower2Cluster = Cluster.get(follower2System);
1300 Member follower2Member = follower2Cluster.readView().self();
1302 await().atMost(10, TimeUnit.SECONDS)
1303 .until(() -> leaderCluster.readView().unreachableMembers().contains(follower2Member));
1304 await().atMost(10, TimeUnit.SECONDS)
1305 .until(() -> followerCluster.readView().unreachableMembers().contains(follower2Member));
1307 ActorRef followerCars = followerDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1309 // to simulate a follower not being able to receive messages, but still being able to send messages and becoming
1310 // candidate, we can just send a couple of RequestVotes to both leader and follower.
1311 cars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1312 followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1313 cars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1314 followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1316 OnDemandRaftState stateAfter = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1317 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1318 OnDemandRaftState followerState = (OnDemandRaftState) followerDistributedDataStore.getActorUtils()
1319 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1321 assertEquals(initialState.getCurrentTerm(), stateAfter.getCurrentTerm());
1322 assertEquals(initialState.getCurrentTerm(), followerState.getCurrentTerm());
1328 public void testInstallSnapshot() throws Exception {
1329 final String testName = "testInstallSnapshot";
1330 final String leaderCarShardName = "member-1-shard-cars-" + testName;
1331 final String followerCarShardName = "member-2-shard-cars-" + testName;
1333 // Setup a saved snapshot on the leader. The follower will startup with no data and the leader should
1334 // install a snapshot to sync the follower.
1336 DataTree tree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_CONFIGURATION,
1337 SchemaContextHelper.full());
1339 final ContainerNode carsNode = CarsModel.newCarsNode(
1340 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", Uint64.valueOf(20000))));
1341 AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
1343 final NormalizedNode<?, ?> snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.empty());
1344 final Snapshot initialSnapshot = Snapshot.create(
1345 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
1346 Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
1347 InMemorySnapshotStore.addSnapshot(leaderCarShardName, initialSnapshot);
1349 InMemorySnapshotStore.addSnapshotSavedLatch(leaderCarShardName);
1350 InMemorySnapshotStore.addSnapshotSavedLatch(followerCarShardName);
1352 initDatastoresWithCars(testName);
1354 final Optional<NormalizedNode<?, ?>> readOptional = leaderDistributedDataStore.newReadOnlyTransaction().read(
1355 CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1356 assertTrue("isPresent", readOptional.isPresent());
1357 assertEquals("Node", carsNode, readOptional.get());
1359 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(leaderCarShardName, Snapshot.class),
1360 initialSnapshot, snapshotRoot);
1362 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(followerCarShardName, Snapshot.class),
1363 initialSnapshot, snapshotRoot);
1367 public void testReadWriteMessageSlicing() throws Exception {
1368 // The slicing is only implemented for tell-based protocol
1369 Assume.assumeTrue(ClientBackedDataStore.class.isAssignableFrom(testParameter));
1371 leaderDatastoreContextBuilder.maximumMessageSliceSize(100);
1372 followerDatastoreContextBuilder.maximumMessageSliceSize(100);
1373 initDatastoresWithCars("testLargeReadReplySlicing");
1375 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1377 final NormalizedNode<?, ?> carsNode = CarsModel.create();
1378 rwTx.write(CarsModel.BASE_PATH, carsNode);
1380 verifyNode(rwTx, CarsModel.BASE_PATH, carsNode);
1383 @SuppressWarnings("IllegalCatch")
1385 public void testRaftCallbackDuringLeadershipDrop() throws Exception {
1386 final String testName = "testRaftCallbackDuringLeadershipDrop";
1387 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1389 final ExecutorService executor = Executors.newSingleThreadExecutor();
1391 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1392 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500)
1393 .shardLeaderElectionTimeoutInSeconds(3600),
1396 final DOMStoreWriteTransaction initialWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1397 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1398 leaderTestKit.doCommit(initialWriteTx.ready());
1400 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1401 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false)) {
1403 final ActorRef member3Cars = ((LocalShardStore) follower2DistributedDataStore).getLocalShards()
1404 .getLocalShards().get("cars").getActor();
1405 final ActorRef member2Cars = ((LocalShardStore)followerDistributedDataStore).getLocalShards()
1406 .getLocalShards().get("cars").getActor();
1407 member2Cars.tell(new StartDropMessages(AppendEntries.class), null);
1408 member3Cars.tell(new StartDropMessages(AppendEntries.class), null);
1410 final DOMStoreWriteTransaction newTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1411 newTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1412 final AtomicBoolean submitDone = new AtomicBoolean(false);
1413 executor.submit(() -> {
1415 leaderTestKit.doCommit(newTx.ready());
1416 submitDone.set(true);
1417 } catch (Exception e) {
1418 throw new RuntimeException(e);
1421 final ActorRef leaderCars = ((LocalShardStore) leaderDistributedDataStore).getLocalShards()
1422 .getLocalShards().get("cars").getActor();
1423 await().atMost(10, TimeUnit.SECONDS)
1424 .until(() -> ((OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1425 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE)).getLastIndex() >= 1);
1427 final OnDemandRaftState raftState = (OnDemandRaftState)leaderDistributedDataStore.getActorUtils()
1428 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE);
1430 // Simulate a follower not receiving heartbeats but still being able to send messages ie RequestVote with
1431 // new term(switching to candidate after election timeout)
1432 leaderCars.tell(new RequestVote(raftState.getCurrentTerm() + 1,
1433 "member-3-shard-cars-testRaftCallbackDuringLeadershipDrop", -1,
1436 member2Cars.tell(new StopDropMessages(AppendEntries.class), null);
1437 member3Cars.tell(new StopDropMessages(AppendEntries.class), null);
1439 await("Is tx stuck in COMMIT_PENDING")
1440 .atMost(10, TimeUnit.SECONDS).untilAtomic(submitDone, equalTo(true));
1444 executor.shutdownNow();
1448 public void testSnapshotOnRootOverwrite() throws Exception {
1449 if (!DistributedDataStore.class.isAssignableFrom(testParameter)) {
1450 // FIXME: ClientBackedDatastore does not have stable indexes/term, the snapshot index seems to fluctuate
1454 final String testName = "testSnapshotOnRootOverwrite";
1455 final String[] shards = {"cars", "default"};
1456 initDatastores(testName, "module-shards-default-cars-member1-and-2.conf", shards,
1457 leaderDatastoreContextBuilder.snapshotOnRootOverwrite(true),
1458 followerDatastoreContextBuilder.snapshotOnRootOverwrite(true));
1460 leaderTestKit.waitForMembersUp("member-2");
1461 final ContainerNode rootNode = ImmutableContainerNodeBuilder.create()
1462 .withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(SchemaContext.NAME))
1463 .withChild((ContainerNode) CarsModel.create())
1466 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1468 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1469 state -> assertEquals(1, state.getSnapshotIndex()));
1471 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1472 state -> assertEquals(1, state.getSnapshotIndex()));
1474 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1475 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1477 for (int i = 0; i < 10; i++) {
1478 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, CarsModel.newCarPath("car " + i),
1479 CarsModel.newCarEntry("car " + i, Uint64.ONE));
1482 // fake snapshot causes the snapshotIndex to move
1483 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1484 state -> assertEquals(10, state.getSnapshotIndex()));
1485 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1486 state -> assertEquals(10, state.getSnapshotIndex()));
1488 // however the real snapshot still has not changed and was taken at index 1
1489 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1490 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1492 // root overwrite so expect a snapshot
1493 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1495 // this was a real snapshot so everything should be in it(1(DisableTrackingPayload) + 1 + 10 + 1)
1496 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1497 state -> assertEquals(12, state.getSnapshotIndex()));
1498 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1499 state -> assertEquals(12, state.getSnapshotIndex()));
1501 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 12);
1502 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 12);
1505 private void verifySnapshot(final String persistenceId, final long lastAppliedIndex) {
1506 await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
1507 List<Snapshot> snap = InMemorySnapshotStore.getSnapshots(persistenceId, Snapshot.class);
1508 assertEquals(1, snap.size());
1509 assertEquals(lastAppliedIndex, snap.get(0).getLastAppliedIndex());
1514 private static void verifySnapshot(final Snapshot actual, final Snapshot expected,
1515 final NormalizedNode<?, ?> expRoot) {
1516 assertEquals("Snapshot getLastAppliedTerm", expected.getLastAppliedTerm(), actual.getLastAppliedTerm());
1517 assertEquals("Snapshot getLastAppliedIndex", expected.getLastAppliedIndex(), actual.getLastAppliedIndex());
1518 assertEquals("Snapshot getLastTerm", expected.getLastTerm(), actual.getLastTerm());
1519 assertEquals("Snapshot getLastIndex", expected.getLastIndex(), actual.getLastIndex());
1520 assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
1521 MetadataShardDataTreeSnapshot shardSnapshot =
1522 (MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
1523 assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
1526 private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1527 final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1528 final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
1529 final Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1530 Mockito.doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1531 Mockito.doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
1532 dataStore.onDatastoreContextUpdated(mockContextFactory);