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.collect.Range;
36 import com.google.common.primitives.UnsignedLong;
37 import com.google.common.util.concurrent.ListenableFuture;
38 import com.google.common.util.concurrent.MoreExecutors;
39 import com.google.common.util.concurrent.Uninterruptibles;
40 import com.typesafe.config.ConfigFactory;
41 import java.util.Arrays;
42 import java.util.Collection;
43 import java.util.Collections;
44 import java.util.Iterator;
45 import java.util.LinkedList;
46 import java.util.List;
47 import java.util.Optional;
49 import java.util.concurrent.ExecutionException;
50 import java.util.concurrent.ExecutorService;
51 import java.util.concurrent.Executors;
52 import java.util.concurrent.TimeUnit;
53 import java.util.concurrent.atomic.AtomicBoolean;
54 import java.util.concurrent.atomic.AtomicLong;
55 import java.util.function.Supplier;
56 import org.junit.After;
57 import org.junit.Assume;
58 import org.junit.Before;
59 import org.junit.Ignore;
60 import org.junit.Test;
61 import org.junit.runner.RunWith;
62 import org.junit.runners.Parameterized;
63 import org.junit.runners.Parameterized.Parameter;
64 import org.junit.runners.Parameterized.Parameters;
65 import org.mockito.Mockito;
66 import org.mockito.stubbing.Answer;
67 import org.opendaylight.controller.cluster.access.client.RequestTimeoutException;
68 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
69 import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
70 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
71 import org.opendaylight.controller.cluster.databroker.TestClientBackedDataStore;
72 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
73 import org.opendaylight.controller.cluster.datastore.TestShard.RequestFrontendMetadata;
74 import org.opendaylight.controller.cluster.datastore.TestShard.StartDropMessages;
75 import org.opendaylight.controller.cluster.datastore.TestShard.StopDropMessages;
76 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
77 import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
78 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
79 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
80 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
81 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
82 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
83 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
84 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
85 import org.opendaylight.controller.cluster.datastore.persisted.FrontendHistoryMetadata;
86 import org.opendaylight.controller.cluster.datastore.persisted.FrontendShardDataTreeSnapshotMetadata;
87 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
88 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
89 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
90 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
91 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
92 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
93 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
94 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
95 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
96 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
97 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
98 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
99 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
100 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
101 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
102 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
103 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
104 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
105 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
106 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
107 import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
108 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
109 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
110 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
111 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
112 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
113 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
114 import org.opendaylight.yangtools.yang.common.Uint64;
115 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
116 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
117 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
119 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
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.api.CollectionNodeBuilder;
125 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
126 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
127 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
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);
208 TestKit.shutdownActorSystem(followerSystem);
209 TestKit.shutdownActorSystem(follower2System);
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, MapNode> 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 final Optional<NormalizedNode<?, ?>> optional = readTx.read(path).get(5, TimeUnit.SECONDS);
264 assertTrue("isPresent", optional.isPresent());
265 assertEquals("Data node", expNode, optional.get());
268 private static void verifyExists(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path)
270 final Boolean exists = readTx.exists(path).get(5, TimeUnit.SECONDS);
271 assertEquals("exists", Boolean.TRUE, exists);
275 public void testWriteTransactionWithSingleShard() throws Exception {
276 final String testName = "testWriteTransactionWithSingleShard";
277 initDatastoresWithCars(testName);
279 final String followerCarShardName = "member-2-shard-cars-" + testName;
281 DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
282 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
284 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
285 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
287 final MapEntryNode car1 = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
288 final YangInstanceIdentifier car1Path = CarsModel.newCarPath("optima");
289 writeTx.merge(car1Path, car1);
291 final MapEntryNode car2 = CarsModel.newCarEntry("sportage", Uint64.valueOf(25000));
292 final YangInstanceIdentifier car2Path = CarsModel.newCarPath("sportage");
293 writeTx.merge(car2Path, car2);
295 followerTestKit.doCommit(writeTx.ready());
297 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car1, car2);
299 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car1, car2);
303 writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
305 writeTx.delete(car1Path);
307 followerTestKit.doCommit(writeTx.ready());
309 verifyExists(followerDistributedDataStore.newReadOnlyTransaction(), car2Path);
311 verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car2);
313 verifyCars(leaderDistributedDataStore.newReadOnlyTransaction(), car2);
315 // Re-instate the follower member 2 as a single-node to verify replication and recovery.
317 // The following is a bit tricky. Before we reinstate the follower we need to ensure it has persisted and
318 // applied and all the log entries from the leader. Since we've verified the car data above we know that
319 // all the transactions have been applied on the leader so we first read and capture its lastAppliedIndex.
320 final AtomicLong leaderLastAppliedIndex = new AtomicLong();
321 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, CARS[0],
322 state -> leaderLastAppliedIndex.set(state.getLastApplied()));
324 // Now we need to make sure the follower has persisted the leader's lastAppliedIndex via ApplyJournalEntries.
325 // However we don't know exactly how many ApplyJournalEntries messages there will be as it can differ between
326 // the tell-based and ask-based front-ends. For ask-based there will be exactly 2 ApplyJournalEntries but
327 // tell-based persists additional payloads which could be replicated and applied in a batch resulting in
328 // either 2 or 3 ApplyJournalEntries. To handle this we read the follower's persisted ApplyJournalEntries
329 // until we find the one that encompasses the leader's lastAppliedIndex.
330 Stopwatch sw = Stopwatch.createStarted();
331 boolean done = false;
333 final List<ApplyJournalEntries> entries = InMemoryJournal.get(followerCarShardName,
334 ApplyJournalEntries.class);
335 for (ApplyJournalEntries aje: entries) {
336 if (aje.getToIndex() >= leaderLastAppliedIndex.get()) {
342 assertTrue("Follower did not persist ApplyJournalEntries containing leader's lastAppliedIndex "
343 + leaderLastAppliedIndex + ". Entries persisted: " + entries, sw.elapsed(TimeUnit.SECONDS) <= 5);
345 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
348 TestKit.shutdownActorSystem(leaderSystem, true);
349 TestKit.shutdownActorSystem(followerSystem, true);
351 final ActorSystem newSystem = newActorSystem("reinstated-member2", "Member2");
353 try (AbstractDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder,
355 .setupAbstractDataStore(testParameter, testName, "module-shards-member2", true, CARS)) {
356 verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
361 public void testSingleTransactionsWritesInQuickSuccession() throws Exception {
362 final String testName = "testWriteTransactionWithSingleShard";
363 initDatastoresWithCars(testName);
365 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
367 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
368 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
369 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
370 followerTestKit.doCommit(writeTx.ready());
373 for (int i = 0; i < numCars; i++) {
374 writeTx = txChain.newWriteOnlyTransaction();
375 writeTx.write(CarsModel.newCarPath("car" + i),
376 CarsModel.newCarEntry("car" + i, Uint64.valueOf(20000)));
378 followerTestKit.doCommit(writeTx.ready());
380 DOMStoreReadTransaction domStoreReadTransaction = txChain.newReadOnlyTransaction();
381 domStoreReadTransaction.read(CarsModel.BASE_PATH).get();
383 domStoreReadTransaction.close();
386 // wait to let the shard catch up with purged
387 await("Range set leak test").atMost(5, TimeUnit.SECONDS)
388 .pollInterval(500, TimeUnit.MILLISECONDS)
389 .untilAsserted(() -> {
390 Optional<ActorRef> localShard =
391 leaderDistributedDataStore.getActorUtils().findLocalShard("cars");
392 FrontendShardDataTreeSnapshotMetadata frontendMetadata =
393 (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
394 .executeOperation(localShard.get(), new RequestFrontendMetadata());
396 if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
397 Iterator<FrontendHistoryMetadata> iterator =
398 frontendMetadata.getClients().get(0).getCurrentHistories().iterator();
399 FrontendHistoryMetadata metadata = iterator.next();
400 while (iterator.hasNext() && metadata.getHistoryId() != 1) {
401 metadata = iterator.next();
404 assertEquals(0, metadata.getClosedTransactions().size());
405 assertEquals(Range.closedOpen(UnsignedLong.valueOf(0), UnsignedLong.valueOf(11)),
406 metadata.getPurgedTransactions().asRanges().iterator().next());
408 // ask based should track no metadata
409 assertTrue(frontendMetadata.getClients().get(0).getCurrentHistories().isEmpty());
413 final Optional<NormalizedNode<?, ?>> optional = txChain.newReadOnlyTransaction()
414 .read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
415 assertTrue("isPresent", optional.isPresent());
416 assertEquals("# cars", numCars, ((Collection<?>) optional.get().getValue()).size());
420 @Ignore("Flushes out tell based leak needs to be handled separately")
421 public void testCloseTransactionMetadataLeak() throws Exception {
422 // Ask based frontend seems to have some issues with back to back close
423 Assume.assumeTrue(testParameter.isAssignableFrom(TestClientBackedDataStore.class));
425 final String testName = "testWriteTransactionWithSingleShard";
426 initDatastoresWithCars(testName);
428 final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
430 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
431 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
432 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
433 followerTestKit.doCommit(writeTx.ready());
436 for (int i = 0; i < numCars; i++) {
437 writeTx = txChain.newWriteOnlyTransaction();
440 DOMStoreReadTransaction domStoreReadTransaction = txChain.newReadOnlyTransaction();
441 domStoreReadTransaction.read(CarsModel.BASE_PATH).get();
443 domStoreReadTransaction.close();
446 writeTx = txChain.newWriteOnlyTransaction();
447 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
448 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
449 followerTestKit.doCommit(writeTx.ready());
451 // wait to let the shard catch up with purged
452 await("Close transaction purge leak test.").atMost(5, TimeUnit.SECONDS)
453 .pollInterval(500, TimeUnit.MILLISECONDS)
454 .untilAsserted(() -> {
455 Optional<ActorRef> localShard =
456 leaderDistributedDataStore.getActorUtils().findLocalShard("cars");
457 FrontendShardDataTreeSnapshotMetadata frontendMetadata =
458 (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
459 .executeOperation(localShard.get(), new RequestFrontendMetadata());
461 if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
462 Iterator<FrontendHistoryMetadata> iterator =
463 frontendMetadata.getClients().get(0).getCurrentHistories().iterator();
464 FrontendHistoryMetadata metadata = iterator.next();
465 while (iterator.hasNext() && metadata.getHistoryId() != 1) {
466 metadata = iterator.next();
469 Set<Range<UnsignedLong>> ranges = metadata.getPurgedTransactions().asRanges();
471 assertEquals(0, metadata.getClosedTransactions().size());
472 assertEquals(1, ranges.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 TestKit.shutdownActorSystem(follower2System);
1291 ActorRef cars = leaderDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1292 OnDemandRaftState initialState = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1293 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1295 Cluster leaderCluster = Cluster.get(leaderSystem);
1296 Cluster followerCluster = Cluster.get(followerSystem);
1297 Cluster follower2Cluster = Cluster.get(follower2System);
1299 Member follower2Member = follower2Cluster.readView().self();
1301 await().atMost(10, TimeUnit.SECONDS)
1302 .until(() -> leaderCluster.readView().unreachableMembers().contains(follower2Member));
1303 await().atMost(10, TimeUnit.SECONDS)
1304 .until(() -> followerCluster.readView().unreachableMembers().contains(follower2Member));
1306 ActorRef followerCars = followerDistributedDataStore.getActorUtils().findLocalShard("cars").get();
1308 // to simulate a follower not being able to receive messages, but still being able to send messages and becoming
1309 // candidate, we can just send a couple of RequestVotes to both leader and follower.
1310 cars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1311 followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 1, "member-3-shard-cars", -1, -1), null);
1312 cars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1313 followerCars.tell(new RequestVote(initialState.getCurrentTerm() + 3, "member-3-shard-cars", -1, -1), null);
1315 OnDemandRaftState stateAfter = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1316 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1317 OnDemandRaftState followerState = (OnDemandRaftState) followerDistributedDataStore.getActorUtils()
1318 .executeOperation(cars, GetOnDemandRaftState.INSTANCE);
1320 assertEquals(initialState.getCurrentTerm(), stateAfter.getCurrentTerm());
1321 assertEquals(initialState.getCurrentTerm(), followerState.getCurrentTerm());
1327 public void testInstallSnapshot() throws Exception {
1328 final String testName = "testInstallSnapshot";
1329 final String leaderCarShardName = "member-1-shard-cars-" + testName;
1330 final String followerCarShardName = "member-2-shard-cars-" + testName;
1332 // Setup a saved snapshot on the leader. The follower will startup with no data and the leader should
1333 // install a snapshot to sync the follower.
1335 DataTree tree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_CONFIGURATION,
1336 SchemaContextHelper.full());
1338 final ContainerNode carsNode = CarsModel.newCarsNode(
1339 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", Uint64.valueOf(20000))));
1340 AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
1342 final NormalizedNode<?, ?> snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.empty());
1343 final Snapshot initialSnapshot = Snapshot.create(
1344 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
1345 Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
1346 InMemorySnapshotStore.addSnapshot(leaderCarShardName, initialSnapshot);
1348 InMemorySnapshotStore.addSnapshotSavedLatch(leaderCarShardName);
1349 InMemorySnapshotStore.addSnapshotSavedLatch(followerCarShardName);
1351 initDatastoresWithCars(testName);
1353 final Optional<NormalizedNode<?, ?>> readOptional = leaderDistributedDataStore.newReadOnlyTransaction().read(
1354 CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1355 assertTrue("isPresent", readOptional.isPresent());
1356 assertEquals("Node", carsNode, readOptional.get());
1358 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(leaderCarShardName, Snapshot.class),
1359 initialSnapshot, snapshotRoot);
1361 verifySnapshot(InMemorySnapshotStore.waitForSavedSnapshot(followerCarShardName, Snapshot.class),
1362 initialSnapshot, snapshotRoot);
1366 public void testReadWriteMessageSlicing() throws Exception {
1367 // The slicing is only implemented for tell-based protocol
1368 Assume.assumeTrue(ClientBackedDataStore.class.isAssignableFrom(testParameter));
1370 leaderDatastoreContextBuilder.maximumMessageSliceSize(100);
1371 followerDatastoreContextBuilder.maximumMessageSliceSize(100);
1372 initDatastoresWithCars("testLargeReadReplySlicing");
1374 final DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
1376 final NormalizedNode<?, ?> carsNode = CarsModel.create();
1377 rwTx.write(CarsModel.BASE_PATH, carsNode);
1379 verifyNode(rwTx, CarsModel.BASE_PATH, carsNode);
1382 @SuppressWarnings("IllegalCatch")
1384 public void testRaftCallbackDuringLeadershipDrop() throws Exception {
1385 final String testName = "testRaftCallbackDuringLeadershipDrop";
1386 initDatastores(testName, MODULE_SHARDS_CARS_1_2_3, CARS);
1388 final ExecutorService executor = Executors.newSingleThreadExecutor();
1390 final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
1391 DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500)
1392 .shardLeaderElectionTimeoutInSeconds(3600),
1395 final DOMStoreWriteTransaction initialWriteTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1396 initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
1397 leaderTestKit.doCommit(initialWriteTx.ready());
1399 try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
1400 testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false)) {
1402 final ActorRef member3Cars = ((LocalShardStore) follower2DistributedDataStore).getLocalShards()
1403 .getLocalShards().get("cars").getActor();
1404 final ActorRef member2Cars = ((LocalShardStore)followerDistributedDataStore).getLocalShards()
1405 .getLocalShards().get("cars").getActor();
1406 member2Cars.tell(new StartDropMessages(AppendEntries.class), null);
1407 member3Cars.tell(new StartDropMessages(AppendEntries.class), null);
1409 final DOMStoreWriteTransaction newTx = leaderDistributedDataStore.newWriteOnlyTransaction();
1410 newTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
1411 final AtomicBoolean submitDone = new AtomicBoolean(false);
1412 executor.submit(() -> {
1414 leaderTestKit.doCommit(newTx.ready());
1415 submitDone.set(true);
1416 } catch (Exception e) {
1417 throw new RuntimeException(e);
1420 final ActorRef leaderCars = ((LocalShardStore) leaderDistributedDataStore).getLocalShards()
1421 .getLocalShards().get("cars").getActor();
1422 await().atMost(10, TimeUnit.SECONDS)
1423 .until(() -> ((OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
1424 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE)).getLastIndex() >= 1);
1426 final OnDemandRaftState raftState = (OnDemandRaftState)leaderDistributedDataStore.getActorUtils()
1427 .executeOperation(leaderCars, GetOnDemandRaftState.INSTANCE);
1429 // Simulate a follower not receiving heartbeats but still being able to send messages ie RequestVote with
1430 // new term(switching to candidate after election timeout)
1431 leaderCars.tell(new RequestVote(raftState.getCurrentTerm() + 1,
1432 "member-3-shard-cars-testRaftCallbackDuringLeadershipDrop", -1,
1435 member2Cars.tell(new StopDropMessages(AppendEntries.class), null);
1436 member3Cars.tell(new StopDropMessages(AppendEntries.class), null);
1438 await("Is tx stuck in COMMIT_PENDING")
1439 .atMost(10, TimeUnit.SECONDS).untilAtomic(submitDone, equalTo(true));
1443 executor.shutdownNow();
1447 public void testSnapshotOnRootOverwrite() throws Exception {
1448 if (!DistributedDataStore.class.isAssignableFrom(testParameter)) {
1449 // FIXME: ClientBackedDatastore does not have stable indexes/term, the snapshot index seems to fluctuate
1453 final String testName = "testSnapshotOnRootOverwrite";
1454 final String[] shards = {"cars", "default"};
1455 initDatastores(testName, "module-shards-default-cars-member1-and-2.conf", shards,
1456 leaderDatastoreContextBuilder.snapshotOnRootOverwrite(true),
1457 followerDatastoreContextBuilder.snapshotOnRootOverwrite(true));
1459 leaderTestKit.waitForMembersUp("member-2");
1460 final ContainerNode rootNode = ImmutableContainerNodeBuilder.create()
1461 .withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(SchemaContext.NAME))
1462 .withChild((ContainerNode) CarsModel.create())
1465 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1467 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1468 state -> assertEquals(1, state.getSnapshotIndex()));
1470 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1471 state -> assertEquals(1, state.getSnapshotIndex()));
1473 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1474 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1476 for (int i = 0; i < 10; i++) {
1477 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, CarsModel.newCarPath("car " + i),
1478 CarsModel.newCarEntry("car " + i, Uint64.ONE));
1481 // fake snapshot causes the snapshotIndex to move
1482 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1483 state -> assertEquals(10, state.getSnapshotIndex()));
1484 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1485 state -> assertEquals(10, state.getSnapshotIndex()));
1487 // however the real snapshot still has not changed and was taken at index 1
1488 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 1);
1489 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
1491 // root overwrite so expect a snapshot
1492 leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
1494 // this was a real snapshot so everything should be in it(1(DisableTrackingPayload) + 1 + 10 + 1)
1495 IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
1496 state -> assertEquals(12, state.getSnapshotIndex()));
1497 IntegrationTestKit.verifyShardState(followerDistributedDataStore, "cars",
1498 state -> assertEquals(12, state.getSnapshotIndex()));
1500 verifySnapshot("member-1-shard-cars-testSnapshotOnRootOverwrite", 12);
1501 verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 12);
1504 private void verifySnapshot(final String persistenceId, final long lastAppliedIndex) {
1505 await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
1506 List<Snapshot> snap = InMemorySnapshotStore.getSnapshots(persistenceId, Snapshot.class);
1507 assertEquals(1, snap.size());
1508 assertEquals(lastAppliedIndex, snap.get(0).getLastAppliedIndex());
1513 private static void verifySnapshot(final Snapshot actual, final Snapshot expected,
1514 final NormalizedNode<?, ?> expRoot) {
1515 assertEquals("Snapshot getLastAppliedTerm", expected.getLastAppliedTerm(), actual.getLastAppliedTerm());
1516 assertEquals("Snapshot getLastAppliedIndex", expected.getLastAppliedIndex(), actual.getLastAppliedIndex());
1517 assertEquals("Snapshot getLastTerm", expected.getLastTerm(), actual.getLastTerm());
1518 assertEquals("Snapshot getLastIndex", expected.getLastIndex(), actual.getLastIndex());
1519 assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
1520 MetadataShardDataTreeSnapshot shardSnapshot =
1521 (MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
1522 assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
1525 private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
1526 final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
1527 final DatastoreContextFactory mockContextFactory = Mockito.mock(DatastoreContextFactory.class);
1528 final Answer<DatastoreContext> answer = invocation -> newBuilder.build();
1529 Mockito.doAnswer(answer).when(mockContextFactory).getBaseDatastoreContext();
1530 Mockito.doAnswer(answer).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
1531 dataStore.onDatastoreContextUpdated(mockContextFactory);