2 * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.datastore;
10 import static org.awaitility.Awaitility.await;
11 import static org.hamcrest.CoreMatchers.instanceOf;
12 import static org.hamcrest.MatcherAssert.assertThat;
13 import static org.junit.Assert.assertEquals;
14 import static org.junit.Assert.assertFalse;
15 import static org.junit.Assert.assertNotNull;
16 import static org.junit.Assert.assertTrue;
17 import static org.junit.Assert.fail;
18 import static org.junit.Assume.assumeFalse;
19 import static org.mockito.ArgumentMatchers.any;
20 import static org.mockito.ArgumentMatchers.eq;
21 import static org.mockito.Mockito.timeout;
22 import static org.mockito.Mockito.verify;
24 import akka.actor.ActorSystem;
25 import com.google.common.base.Throwables;
26 import com.google.common.collect.ImmutableMap;
27 import com.google.common.util.concurrent.FluentFuture;
28 import com.google.common.util.concurrent.ListenableFuture;
29 import com.google.common.util.concurrent.MoreExecutors;
30 import com.google.common.util.concurrent.Uninterruptibles;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.List;
36 import java.util.Optional;
37 import java.util.concurrent.CountDownLatch;
38 import java.util.concurrent.ExecutionException;
39 import java.util.concurrent.TimeUnit;
40 import java.util.concurrent.atomic.AtomicReference;
41 import org.junit.Test;
42 import org.junit.runners.Parameterized.Parameter;
43 import org.mockito.Mockito;
44 import org.opendaylight.controller.cluster.access.client.RequestTimeoutException;
45 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
46 import org.opendaylight.controller.cluster.datastore.TestShard.RequestFrontendMetadata;
47 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
48 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
49 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
50 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
51 import org.opendaylight.controller.cluster.datastore.persisted.FrontendClientMetadata;
52 import org.opendaylight.controller.cluster.datastore.persisted.FrontendShardDataTreeSnapshotMetadata;
53 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
54 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
55 import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
56 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
57 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
58 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
59 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
60 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
61 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
62 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
63 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
64 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
65 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
66 import org.opendaylight.mdsal.dom.api.DOMTransactionChainClosedException;
67 import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
68 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
69 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
70 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
71 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
72 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
73 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
74 import org.opendaylight.yangtools.concepts.ListenerRegistration;
75 import org.opendaylight.yangtools.yang.common.Uint64;
76 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
77 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
80 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
81 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
82 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
83 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
84 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
85 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
86 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
88 public abstract class AbstractDistributedDataStoreIntegrationTest {
91 public Class<? extends AbstractDataStore> testParameter;
93 protected ActorSystem system;
95 protected final DatastoreContext.Builder datastoreContextBuilder = DatastoreContext.newBuilder()
96 .shardHeartbeatIntervalInMillis(100);
98 protected ActorSystem getSystem() {
103 public void testWriteTransactionWithSingleShard() throws Exception {
104 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
105 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
106 testParameter, "transactionIntegrationTest", "test-1")) {
108 testKit.testWriteTransaction(dataStore, TestModel.TEST_PATH,
109 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
111 testKit.testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
112 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
113 .withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 42))
119 public void testWriteTransactionWithMultipleShards() throws Exception {
120 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
121 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
122 testParameter, "testWriteTransactionWithMultipleShards", "cars-1", "people-1")) {
124 DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
125 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
127 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
128 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
130 testKit.doCommit(writeTx.ready());
132 writeTx = dataStore.newWriteOnlyTransaction();
134 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
135 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
137 testKit.doCommit(writeTx.ready());
139 writeTx = dataStore.newWriteOnlyTransaction();
141 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
142 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
143 writeTx.write(carPath, car);
145 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
146 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
147 writeTx.write(personPath, person);
149 testKit.doCommit(writeTx.ready());
151 // Verify the data in the store
152 final DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
154 Optional<NormalizedNode> optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
155 assertTrue("isPresent", optional.isPresent());
156 assertEquals("Data node", car, optional.get());
158 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
159 assertTrue("isPresent", optional.isPresent());
160 assertEquals("Data node", person, optional.get());
165 public void testReadWriteTransactionWithSingleShard() throws Exception {
166 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
167 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
168 testParameter, "testReadWriteTransactionWithSingleShard", "test-1")) {
170 // 1. Create a read-write Tx
171 final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
172 assertNotNull("newReadWriteTransaction returned null", readWriteTx);
174 // 2. Write some data
175 final YangInstanceIdentifier nodePath = TestModel.TEST_PATH;
176 final NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
177 readWriteTx.write(nodePath, nodeToWrite);
179 // 3. Read the data from Tx
180 final Boolean exists = readWriteTx.exists(nodePath).get(5, TimeUnit.SECONDS);
181 assertEquals("exists", Boolean.TRUE, exists);
183 Optional<NormalizedNode> optional = readWriteTx.read(nodePath).get(5, TimeUnit.SECONDS);
184 assertTrue("isPresent", optional.isPresent());
185 assertEquals("Data node", nodeToWrite, optional.get());
187 // 4. Ready the Tx for commit
188 final DOMStoreThreePhaseCommitCohort cohort = readWriteTx.ready();
191 testKit.doCommit(cohort);
193 // 6. Verify the data in the store
194 final DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
196 optional = readTx.read(nodePath).get(5, TimeUnit.SECONDS);
197 assertTrue("isPresent", optional.isPresent());
198 assertEquals("Data node", nodeToWrite, optional.get());
203 public void testReadWriteTransactionWithMultipleShards() throws Exception {
204 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
205 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
206 testParameter, "testReadWriteTransactionWithMultipleShards", "cars-1", "people-1")) {
208 DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
209 assertNotNull("newReadWriteTransaction returned null", readWriteTx);
211 readWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
212 readWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
214 testKit.doCommit(readWriteTx.ready());
216 readWriteTx = dataStore.newReadWriteTransaction();
218 readWriteTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
219 readWriteTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
221 testKit.doCommit(readWriteTx.ready());
223 readWriteTx = dataStore.newReadWriteTransaction();
225 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
226 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
227 readWriteTx.write(carPath, car);
229 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
230 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
231 readWriteTx.write(personPath, person);
233 final Boolean exists = readWriteTx.exists(carPath).get(5, TimeUnit.SECONDS);
234 assertEquals("exists", Boolean.TRUE, exists);
236 Optional<NormalizedNode> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
237 assertTrue("isPresent", optional.isPresent());
238 assertEquals("Data node", car, optional.get());
240 testKit.doCommit(readWriteTx.ready());
242 // Verify the data in the store
243 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
245 optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
246 assertTrue("isPresent", optional.isPresent());
247 assertEquals("Data node", car, optional.get());
249 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
250 assertTrue("isPresent", optional.isPresent());
251 assertEquals("Data node", person, optional.get());
256 public void testSingleTransactionsWritesInQuickSuccession() throws Exception {
257 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
258 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
259 testParameter, "testSingleTransactionsWritesInQuickSuccession", "cars-1")) {
261 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
263 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
264 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
265 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
266 testKit.doCommit(writeTx.ready());
269 for (int i = 0; i < numCars; i++) {
270 writeTx = txChain.newWriteOnlyTransaction();
271 writeTx.write(CarsModel.newCarPath("car" + i), CarsModel.newCarEntry("car" + i, Uint64.valueOf(20000)));
273 testKit.doCommit(writeTx.ready());
275 try (var tx = txChain.newReadOnlyTransaction()) {
276 tx.read(CarsModel.BASE_PATH).get();
280 // wait to let the shard catch up with purged
281 await("transaction state propagation").atMost(5, TimeUnit.SECONDS)
282 .pollInterval(500, TimeUnit.MILLISECONDS)
283 .untilAsserted(() -> {
284 // verify frontend metadata has no holes in purged transactions causing overtime memory leak
285 final var localShard = dataStore.getActorUtils().findLocalShard("cars-1") .orElseThrow();
286 FrontendShardDataTreeSnapshotMetadata frontendMetadata =
287 (FrontendShardDataTreeSnapshotMetadata) dataStore.getActorUtils()
288 .executeOperation(localShard, new RequestFrontendMetadata());
290 final var clientMeta = frontendMetadata.getClients().get(0);
291 if (dataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
292 assertTellMetadata(clientMeta);
294 assertAskMetadata(clientMeta);
298 final var body = txChain.newReadOnlyTransaction().read(CarsModel.CAR_LIST_PATH)
299 .get(5, TimeUnit.SECONDS)
302 assertThat(body, instanceOf(Collection.class));
303 assertEquals("# cars", numCars, ((Collection<?>) body).size());
307 private static void assertAskMetadata(final FrontendClientMetadata clientMeta) {
308 // FIXME: needs to be enabled
310 // ask based should track no metadata
311 assertEquals(List.of(), clientMeta.getCurrentHistories());
314 private static void assertTellMetadata(final FrontendClientMetadata clientMeta) {
315 final var iterator = clientMeta.getCurrentHistories().iterator();
316 var metadata = iterator.next();
317 while (iterator.hasNext() && metadata.getHistoryId() != 1) {
318 metadata = iterator.next();
320 assertEquals("[[0..10]]", metadata.getPurgedTransactions().ranges().toString());
323 @SuppressWarnings("checkstyle:IllegalCatch")
324 private void testTransactionCommitFailureWithNoShardLeader(final boolean writeOnly, final String testName)
326 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
327 final String shardName = "default";
329 // We don't want the shard to become the leader so prevent shard
331 datastoreContextBuilder.customRaftPolicyImplementation(
332 "org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy");
334 // The ShardManager uses the election timeout for FindPrimary so
335 // reset it low so it will timeout quickly.
336 datastoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(1)
337 .shardInitializationTimeout(200, TimeUnit.MILLISECONDS).frontendRequestTimeoutInSeconds(2);
339 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(testParameter, testName, false, shardName)) {
341 final Object result = dataStore.getActorUtils().executeOperation(
342 dataStore.getActorUtils().getShardManager(), new FindLocalShard(shardName, true));
343 assertTrue("Expected LocalShardFound. Actual: " + result, result instanceof LocalShardFound);
345 // Create the write Tx.
346 DOMStoreWriteTransaction writeTxToClose = null;
348 writeTxToClose = writeOnly ? dataStore.newWriteOnlyTransaction()
349 : dataStore.newReadWriteTransaction();
350 final DOMStoreWriteTransaction writeTx = writeTxToClose;
351 assertNotNull("newReadWriteTransaction returned null", writeTx);
353 // Do some modifications and ready the Tx on a separate
355 final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
356 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
357 final CountDownLatch txReady = new CountDownLatch(1);
358 final Thread txThread = new Thread(() -> {
360 writeTx.write(TestModel.JUNK_PATH,
361 ImmutableNodes.containerNode(TestModel.JUNK_QNAME));
363 txCohort.set(writeTx.ready());
364 } catch (Exception e) {
373 // Wait for the Tx operations to complete.
374 boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
375 if (caughtEx.get() != null) {
376 throw caughtEx.get();
379 assertTrue("Tx ready", done);
381 // Wait for the commit to complete. Since no shard
382 // leader was elected in time, the Tx
383 // should have timed out and throw an appropriate
386 txCohort.get().canCommit().get(10, TimeUnit.SECONDS);
387 fail("Expected NoShardLeaderException");
388 } catch (final ExecutionException e) {
389 final String msg = "Unexpected exception: "
390 + Throwables.getStackTraceAsString(e.getCause());
391 if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
392 assertTrue(Throwables.getRootCause(e) instanceof NoShardLeaderException);
394 assertTrue(msg, Throwables.getRootCause(e) instanceof RequestTimeoutException);
399 if (writeTxToClose != null) {
400 writeTxToClose.close();
402 } catch (Exception e) {
403 // FIXME TransactionProxy.close throws IllegalStateException:
404 // Transaction is ready, it cannot be closed
411 public void testWriteOnlyTransactionCommitFailureWithNoShardLeader() throws Exception {
412 datastoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
413 testTransactionCommitFailureWithNoShardLeader(true, "testWriteOnlyTransactionCommitFailureWithNoShardLeader");
417 public void testReadWriteTransactionCommitFailureWithNoShardLeader() throws Exception {
418 testTransactionCommitFailureWithNoShardLeader(false, "testReadWriteTransactionCommitFailureWithNoShardLeader");
422 public void testTransactionAbort() throws Exception {
423 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
424 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
425 testParameter, "transactionAbortIntegrationTest", "test-1")) {
427 final DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
428 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
430 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
432 final DOMStoreThreePhaseCommitCohort cohort = writeTx.ready();
434 cohort.canCommit().get(5, TimeUnit.SECONDS);
436 cohort.abort().get(5, TimeUnit.SECONDS);
438 testKit.testWriteTransaction(dataStore, TestModel.TEST_PATH,
439 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
444 @SuppressWarnings("checkstyle:IllegalCatch")
445 public void testTransactionChainWithSingleShard() throws Exception {
446 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
447 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
448 testParameter, "testTransactionChainWithSingleShard", "test-1")) {
450 // 1. Create a Tx chain and write-only Tx
451 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
453 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
454 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
456 // 2. Write some data
457 final NormalizedNode testNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
458 writeTx.write(TestModel.TEST_PATH, testNode);
460 // 3. Ready the Tx for commit
461 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
463 // 4. Commit the Tx on another thread that first waits for
464 // the second read Tx.
465 final CountDownLatch continueCommit1 = new CountDownLatch(1);
466 final CountDownLatch commit1Done = new CountDownLatch(1);
467 final AtomicReference<Exception> commit1Error = new AtomicReference<>();
470 continueCommit1.await();
471 testKit.doCommit(cohort1);
472 } catch (Exception e) {
475 commit1Done.countDown();
479 // 5. Create a new read Tx from the chain to read and verify
480 // the data from the first
481 // Tx is visible after being readied.
482 DOMStoreReadTransaction readTx = txChain.newReadOnlyTransaction();
483 Optional<NormalizedNode> optional = readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
484 assertTrue("isPresent", optional.isPresent());
485 assertEquals("Data node", testNode, optional.get());
487 // 6. Create a new RW Tx from the chain, write more data,
489 final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
490 final MapNode outerNode = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
491 .withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 42))
493 rwTx.write(TestModel.OUTER_LIST_PATH, outerNode);
495 final DOMStoreThreePhaseCommitCohort cohort2 = rwTx.ready();
497 // 7. Create a new read Tx from the chain to read the data
498 // from the last RW Tx to
499 // verify it is visible.
500 readTx = txChain.newReadWriteTransaction();
501 optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
502 assertTrue("isPresent", optional.isPresent());
503 assertEquals("Data node", outerNode, optional.get());
505 // 8. Wait for the 2 commits to complete and close the
507 continueCommit1.countDown();
508 Uninterruptibles.awaitUninterruptibly(commit1Done, 5, TimeUnit.SECONDS);
510 if (commit1Error.get() != null) {
511 throw commit1Error.get();
514 testKit.doCommit(cohort2);
518 // 9. Create a new read Tx from the data store and verify
520 readTx = dataStore.newReadOnlyTransaction();
521 optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
522 assertTrue("isPresent", optional.isPresent());
523 assertEquals("Data node", outerNode, optional.get());
528 public void testTransactionChainWithMultipleShards() throws Exception {
529 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
530 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
531 testParameter, "testTransactionChainWithMultipleShards", "cars-1", "people-1")) {
533 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
535 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
536 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
538 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
539 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
541 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
542 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
544 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
546 final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
548 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
549 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
550 readWriteTx.write(carPath, car);
552 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
553 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
554 readWriteTx.merge(personPath, person);
556 Optional<NormalizedNode> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
557 assertTrue("isPresent", optional.isPresent());
558 assertEquals("Data node", car, optional.get());
560 optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
561 assertTrue("isPresent", optional.isPresent());
562 assertEquals("Data node", person, optional.get());
564 final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
566 writeTx = txChain.newWriteOnlyTransaction();
568 writeTx.delete(carPath);
570 final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
572 final ListenableFuture<Boolean> canCommit1 = cohort1.canCommit();
573 final ListenableFuture<Boolean> canCommit2 = cohort2.canCommit();
575 testKit.doCommit(canCommit1, cohort1);
576 testKit.doCommit(canCommit2, cohort2);
577 testKit.doCommit(cohort3);
581 final DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
583 optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
584 assertFalse("isPresent", optional.isPresent());
586 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
587 assertTrue("isPresent", optional.isPresent());
588 assertEquals("Data node", person, optional.get());
593 public void testCreateChainedTransactionsInQuickSuccession() throws Exception {
594 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
595 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
596 testParameter, "testCreateChainedTransactionsInQuickSuccession", "cars-1")) {
598 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
599 ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
600 .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
601 MoreExecutors.directExecutor());
603 final DOMTransactionChainListener listener = Mockito.mock(DOMTransactionChainListener.class);
604 DOMTransactionChain txChain = broker.createTransactionChain(listener);
606 final List<ListenableFuture<?>> futures = new ArrayList<>();
608 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
609 writeTx.put(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, CarsModel.emptyContainer());
610 writeTx.put(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
611 futures.add(writeTx.commit());
614 for (int i = 0; i < numCars; i++) {
615 final DOMDataTreeReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
617 rwTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.newCarPath("car" + i),
618 CarsModel.newCarEntry("car" + i, Uint64.valueOf(20000)));
620 futures.add(rwTx.commit());
623 for (final ListenableFuture<?> f : futures) {
624 f.get(5, TimeUnit.SECONDS);
627 final Optional<NormalizedNode> optional = txChain.newReadOnlyTransaction()
628 .read(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
629 assertTrue("isPresent", optional.isPresent());
630 assertEquals("# cars", numCars, ((Collection<?>) optional.get().body()).size());
639 public void testCreateChainedTransactionAfterEmptyTxReadied() throws Exception {
640 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
641 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
642 testParameter, "testCreateChainedTransactionAfterEmptyTxReadied", "test-1")) {
644 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
646 final DOMStoreReadWriteTransaction rwTx1 = txChain.newReadWriteTransaction();
650 final DOMStoreReadWriteTransaction rwTx2 = txChain.newReadWriteTransaction();
652 final Optional<NormalizedNode> optional = rwTx2.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
653 assertFalse("isPresent", optional.isPresent());
660 public void testCreateChainedTransactionWhenPreviousNotReady() throws Exception {
661 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
662 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
663 testParameter, "testCreateChainedTransactionWhenPreviousNotReady", "test-1")) {
665 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
667 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
668 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
670 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
672 // Try to create another Tx of each type - each should fail
673 // b/c the previous Tx wasn't
675 testKit.assertExceptionOnTxChainCreates(txChain, IllegalStateException.class);
680 public void testCreateChainedTransactionAfterClose() throws Exception {
681 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
682 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
683 testParameter, "testCreateChainedTransactionAfterClose", "test-1")) {
685 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
688 // Try to create another Tx of each type - should fail b/c
689 // the previous Tx was closed.
690 testKit.assertExceptionOnTxChainCreates(txChain, DOMTransactionChainClosedException.class);
695 public void testChainWithReadOnlyTxAfterPreviousReady() throws Exception {
696 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
697 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
698 testParameter, "testChainWithReadOnlyTxAfterPreviousReady", "test-1")) {
700 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
702 // Create a write tx and submit.
703 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
704 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
705 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
707 // Create read-only tx's and issue a read.
708 FluentFuture<Optional<NormalizedNode>> readFuture1 = txChain
709 .newReadOnlyTransaction().read(TestModel.TEST_PATH);
711 FluentFuture<Optional<NormalizedNode>> readFuture2 = txChain
712 .newReadOnlyTransaction().read(TestModel.TEST_PATH);
714 // Create another write tx and issue the write.
715 DOMStoreWriteTransaction writeTx2 = txChain.newWriteOnlyTransaction();
716 writeTx2.write(TestModel.OUTER_LIST_PATH,
717 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
718 .withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 42))
721 // Ensure the reads succeed.
723 assertTrue("isPresent", readFuture1.get(5, TimeUnit.SECONDS).isPresent());
724 assertTrue("isPresent", readFuture2.get(5, TimeUnit.SECONDS).isPresent());
726 // Ensure the writes succeed.
727 DOMStoreThreePhaseCommitCohort cohort2 = writeTx2.ready();
729 testKit.doCommit(cohort1);
730 testKit.doCommit(cohort2);
732 assertTrue("isPresent", txChain.newReadOnlyTransaction().read(TestModel.OUTER_LIST_PATH)
733 .get(5, TimeUnit.SECONDS).isPresent());
738 public void testChainedTransactionFailureWithSingleShard() throws Exception {
739 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
740 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
741 testParameter, "testChainedTransactionFailureWithSingleShard", "cars-1")) {
743 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
744 ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
745 .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
746 MoreExecutors.directExecutor());
748 final DOMTransactionChainListener listener = Mockito.mock(DOMTransactionChainListener.class);
749 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
751 final DOMDataTreeReadWriteTransaction writeTx = txChain.newReadWriteTransaction();
753 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH,
754 PeopleModel.emptyContainer());
756 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
757 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
758 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
760 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
763 writeTx.commit().get(5, TimeUnit.SECONDS);
764 fail("Expected TransactionCommitFailedException");
765 } catch (final ExecutionException e) {
769 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx),
770 any(Throwable.class));
778 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
779 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
780 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
781 testParameter, "testChainedTransactionFailureWithMultipleShards", "cars-1", "people-1")) {
783 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
784 ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
785 .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
786 MoreExecutors.directExecutor());
788 final DOMTransactionChainListener listener = Mockito.mock(DOMTransactionChainListener.class);
789 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
791 final DOMDataTreeWriteTransaction writeTx = txChain.newReadWriteTransaction();
793 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH,
794 PeopleModel.emptyContainer());
796 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
797 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
798 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
800 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
802 // Note that merge will validate the data and fail but put
803 // succeeds b/c deep validation is not
804 // done for put for performance reasons.
806 writeTx.commit().get(5, TimeUnit.SECONDS);
807 fail("Expected TransactionCommitFailedException");
808 } catch (final ExecutionException e) {
812 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx),
813 any(Throwable.class));
821 public void testDataTreeChangeListenerRegistration() throws Exception {
822 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
823 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
824 testParameter, "testDataTreeChangeListenerRegistration", "test-1")) {
826 testKit.testWriteTransaction(dataStore, TestModel.TEST_PATH,
827 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
829 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
831 ListenerRegistration<MockDataTreeChangeListener> listenerReg = dataStore
832 .registerTreeChangeListener(TestModel.TEST_PATH, listener);
834 assertNotNull("registerTreeChangeListener returned null", listenerReg);
836 IntegrationTestKit.verifyShardState(dataStore, "test-1",
837 state -> assertEquals("getTreeChangeListenerActors", 1,
838 state.getTreeChangeListenerActors().size()));
840 // Wait for the initial notification
841 listener.waitForChangeEvents(TestModel.TEST_PATH);
845 testKit.testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
846 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
847 .withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 42))
850 YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
851 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build();
852 testKit.testWriteTransaction(dataStore, listPath,
853 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1));
855 // Wait for the 2 updates.
856 listener.waitForChangeEvents(TestModel.OUTER_LIST_PATH, listPath);
859 IntegrationTestKit.verifyShardState(dataStore, "test-1",
860 state -> assertEquals("getTreeChangeListenerActors", 0,
861 state.getTreeChangeListenerActors().size()));
863 testKit.testWriteTransaction(dataStore,
864 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
865 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build(),
866 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2));
868 listener.expectNoMoreChanges("Received unexpected change after close");
873 public void testRestoreFromDatastoreSnapshot() throws Exception {
874 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
875 final String name = "transactionIntegrationTest";
877 final ContainerNode carsNode = CarsModel.newCarsNode(
878 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", Uint64.valueOf(20000)),
879 CarsModel.newCarEntry("sportage", Uint64.valueOf(30000))));
881 DataTree dataTree = new InMemoryDataTreeFactory().create(
882 DataTreeConfiguration.DEFAULT_OPERATIONAL, SchemaContextHelper.full());
883 AbstractShardTest.writeToStore(dataTree, CarsModel.BASE_PATH, carsNode);
884 NormalizedNode root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.empty());
886 final Snapshot carsSnapshot = Snapshot.create(
887 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(root)),
888 Collections.emptyList(), 2, 1, 2, 1, 1, "member-1", null);
890 dataTree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_OPERATIONAL,
891 SchemaContextHelper.full());
893 final NormalizedNode peopleNode = PeopleModel.create();
894 AbstractShardTest.writeToStore(dataTree, PeopleModel.BASE_PATH, peopleNode);
896 root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.empty());
898 final Snapshot peopleSnapshot = Snapshot.create(
899 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(root)),
900 Collections.emptyList(), 2, 1, 2, 1, 1, "member-1", null);
902 testKit.restoreFromSnapshot = new DatastoreSnapshot(name, null, Arrays.asList(
903 new DatastoreSnapshot.ShardSnapshot("cars", carsSnapshot),
904 new DatastoreSnapshot.ShardSnapshot("people", peopleSnapshot)));
906 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
907 testParameter, name, "module-shards-member1.conf", true, "cars", "people")) {
909 final DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
912 Optional<NormalizedNode> optional = readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
913 assertTrue("isPresent", optional.isPresent());
914 assertEquals("Data node", carsNode, optional.get());
916 optional = readTx.read(PeopleModel.BASE_PATH).get(5, TimeUnit.SECONDS);
917 assertTrue("isPresent", optional.isPresent());
918 assertEquals("Data node", peopleNode, optional.get());
923 public void testSnapshotOnRootOverwrite() throws Exception {
924 if (!DistributedDataStore.class.isAssignableFrom(testParameter)) {
925 // FIXME: ClientBackedDatastore does not have stable indexes/term, the snapshot index seems to fluctuate
929 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(),
930 datastoreContextBuilder.snapshotOnRootOverwrite(true));
931 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
932 testParameter, "testRootOverwrite", "module-shards-default-cars-member1.conf",
933 true, "cars", "default")) {
935 ContainerNode rootNode = ImmutableContainerNodeBuilder.create()
936 .withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(SchemaContext.NAME))
937 .withChild(CarsModel.create())
940 testKit.testWriteTransaction(dataStore, YangInstanceIdentifier.empty(), rootNode);
941 IntegrationTestKit.verifyShardState(dataStore, "cars",
942 state -> assertEquals(1, state.getSnapshotIndex()));
944 // root has been written expect snapshot at index 0
945 verifySnapshot("member-1-shard-cars-testRootOverwrite", 1, 1);
947 for (int i = 0; i < 10; i++) {
948 testKit.testWriteTransaction(dataStore, CarsModel.newCarPath("car " + i),
949 CarsModel.newCarEntry("car " + i, Uint64.ONE));
952 // fake snapshot causes the snapshotIndex to move
953 IntegrationTestKit.verifyShardState(dataStore, "cars",
954 state -> assertEquals(10, state.getSnapshotIndex()));
956 // however the real snapshot still has not changed and was taken at index 0
957 verifySnapshot("member-1-shard-cars-testRootOverwrite", 1, 1);
959 // root overwrite so expect a snapshot
960 testKit.testWriteTransaction(dataStore, YangInstanceIdentifier.empty(), rootNode);
962 // this was a real snapshot so everything should be in it(1 + 10 + 1)
963 IntegrationTestKit.verifyShardState(dataStore, "cars",
964 state -> assertEquals(12, state.getSnapshotIndex()));
966 verifySnapshot("member-1-shard-cars-testRootOverwrite", 12, 1);
970 private static void verifySnapshot(final String persistenceId, final long lastAppliedIndex,
971 final long lastAppliedTerm) {
972 await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
973 List<Snapshot> snap = InMemorySnapshotStore.getSnapshots(persistenceId, Snapshot.class);
974 assertEquals(1, snap.size());
975 assertEquals(lastAppliedIndex, snap.get(0).getLastAppliedIndex());
976 assertEquals(lastAppliedTerm, snap.get(0).getLastAppliedTerm());