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.mockito.ArgumentMatchers.any;
19 import static org.mockito.ArgumentMatchers.eq;
20 import static org.mockito.Mockito.timeout;
21 import static org.mockito.Mockito.verify;
23 import akka.actor.ActorSystem;
24 import com.google.common.base.Throwables;
25 import com.google.common.collect.ImmutableMap;
26 import com.google.common.util.concurrent.FluentFuture;
27 import com.google.common.util.concurrent.ListenableFuture;
28 import com.google.common.util.concurrent.MoreExecutors;
29 import com.google.common.util.concurrent.Uninterruptibles;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.List;
35 import java.util.Optional;
36 import java.util.concurrent.CountDownLatch;
37 import java.util.concurrent.ExecutionException;
38 import java.util.concurrent.TimeUnit;
39 import java.util.concurrent.atomic.AtomicReference;
40 import org.junit.Test;
41 import org.junit.runners.Parameterized.Parameter;
42 import org.mockito.Mockito;
43 import org.opendaylight.controller.cluster.access.client.RequestTimeoutException;
44 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
45 import org.opendaylight.controller.cluster.datastore.TestShard.RequestFrontendMetadata;
46 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
47 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
48 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
49 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
50 import org.opendaylight.controller.cluster.datastore.persisted.FrontendClientMetadata;
51 import org.opendaylight.controller.cluster.datastore.persisted.FrontendShardDataTreeSnapshotMetadata;
52 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
53 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
54 import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
55 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
56 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
57 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
58 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
59 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
60 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
61 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
62 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
63 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
64 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
65 import org.opendaylight.mdsal.dom.api.DOMTransactionChainClosedException;
66 import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
67 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
68 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
69 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
70 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
71 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
72 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
73 import org.opendaylight.yangtools.concepts.ListenerRegistration;
74 import org.opendaylight.yangtools.yang.common.Uint64;
75 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
76 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
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.impl.schema.Builders;
82 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
83 import org.opendaylight.yangtools.yang.data.tree.api.DataTree;
84 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeConfiguration;
85 import org.opendaylight.yangtools.yang.data.tree.impl.di.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 // ask based should track no metadata
309 assertEquals(List.of(), clientMeta.getCurrentHistories());
312 private static void assertTellMetadata(final FrontendClientMetadata clientMeta) {
313 final var iterator = clientMeta.getCurrentHistories().iterator();
314 var metadata = iterator.next();
315 while (iterator.hasNext() && metadata.getHistoryId() != 1) {
316 metadata = iterator.next();
318 assertEquals("[[0..10]]", metadata.getPurgedTransactions().ranges().toString());
321 @SuppressWarnings("checkstyle:IllegalCatch")
322 private void testTransactionCommitFailureWithNoShardLeader(final boolean writeOnly, final String testName)
324 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
325 final String shardName = "default";
327 // We don't want the shard to become the leader so prevent shard
329 datastoreContextBuilder.customRaftPolicyImplementation(
330 "org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy");
332 // The ShardManager uses the election timeout for FindPrimary so
333 // reset it low so it will timeout quickly.
334 datastoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(1)
335 .shardInitializationTimeout(200, TimeUnit.MILLISECONDS).frontendRequestTimeoutInSeconds(2);
337 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(testParameter, testName, false, shardName)) {
339 final Object result = dataStore.getActorUtils().executeOperation(
340 dataStore.getActorUtils().getShardManager(), new FindLocalShard(shardName, true));
341 assertTrue("Expected LocalShardFound. Actual: " + result, result instanceof LocalShardFound);
343 // Create the write Tx.
344 DOMStoreWriteTransaction writeTxToClose = null;
346 writeTxToClose = writeOnly ? dataStore.newWriteOnlyTransaction()
347 : dataStore.newReadWriteTransaction();
348 final DOMStoreWriteTransaction writeTx = writeTxToClose;
349 assertNotNull("newReadWriteTransaction returned null", writeTx);
351 // Do some modifications and ready the Tx on a separate
353 final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
354 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
355 final CountDownLatch txReady = new CountDownLatch(1);
356 final Thread txThread = new Thread(() -> {
358 writeTx.write(TestModel.JUNK_PATH,
359 ImmutableNodes.containerNode(TestModel.JUNK_QNAME));
361 txCohort.set(writeTx.ready());
362 } catch (Exception e) {
371 // Wait for the Tx operations to complete.
372 boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
373 if (caughtEx.get() != null) {
374 throw caughtEx.get();
377 assertTrue("Tx ready", done);
379 // Wait for the commit to complete. Since no shard
380 // leader was elected in time, the Tx
381 // should have timed out and throw an appropriate
384 txCohort.get().canCommit().get(10, TimeUnit.SECONDS);
385 fail("Expected NoShardLeaderException");
386 } catch (final ExecutionException e) {
387 final String msg = "Unexpected exception: "
388 + Throwables.getStackTraceAsString(e.getCause());
389 if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
390 assertTrue(Throwables.getRootCause(e) instanceof NoShardLeaderException);
392 assertTrue(msg, Throwables.getRootCause(e) instanceof RequestTimeoutException);
397 if (writeTxToClose != null) {
398 writeTxToClose.close();
400 } catch (Exception e) {
401 // FIXME TransactionProxy.close throws IllegalStateException:
402 // Transaction is ready, it cannot be closed
409 public void testWriteOnlyTransactionCommitFailureWithNoShardLeader() throws Exception {
410 datastoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
411 testTransactionCommitFailureWithNoShardLeader(true, "testWriteOnlyTransactionCommitFailureWithNoShardLeader");
415 public void testReadWriteTransactionCommitFailureWithNoShardLeader() throws Exception {
416 testTransactionCommitFailureWithNoShardLeader(false, "testReadWriteTransactionCommitFailureWithNoShardLeader");
420 public void testTransactionAbort() throws Exception {
421 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
422 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
423 testParameter, "transactionAbortIntegrationTest", "test-1")) {
425 final DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
426 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
428 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
430 final DOMStoreThreePhaseCommitCohort cohort = writeTx.ready();
432 cohort.canCommit().get(5, TimeUnit.SECONDS);
434 cohort.abort().get(5, TimeUnit.SECONDS);
436 testKit.testWriteTransaction(dataStore, TestModel.TEST_PATH,
437 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
442 @SuppressWarnings("checkstyle:IllegalCatch")
443 public void testTransactionChainWithSingleShard() throws Exception {
444 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
445 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
446 testParameter, "testTransactionChainWithSingleShard", "test-1")) {
448 // 1. Create a Tx chain and write-only Tx
449 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
451 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
452 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
454 // 2. Write some data
455 final NormalizedNode testNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
456 writeTx.write(TestModel.TEST_PATH, testNode);
458 // 3. Ready the Tx for commit
459 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
461 // 4. Commit the Tx on another thread that first waits for
462 // the second read Tx.
463 final CountDownLatch continueCommit1 = new CountDownLatch(1);
464 final CountDownLatch commit1Done = new CountDownLatch(1);
465 final AtomicReference<Exception> commit1Error = new AtomicReference<>();
468 continueCommit1.await();
469 testKit.doCommit(cohort1);
470 } catch (Exception e) {
473 commit1Done.countDown();
477 // 5. Create a new read Tx from the chain to read and verify
478 // the data from the first
479 // Tx is visible after being readied.
480 DOMStoreReadTransaction readTx = txChain.newReadOnlyTransaction();
481 Optional<NormalizedNode> optional = readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
482 assertTrue("isPresent", optional.isPresent());
483 assertEquals("Data node", testNode, optional.get());
485 // 6. Create a new RW Tx from the chain, write more data,
487 final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
488 final MapNode outerNode = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
489 .withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 42))
491 rwTx.write(TestModel.OUTER_LIST_PATH, outerNode);
493 final DOMStoreThreePhaseCommitCohort cohort2 = rwTx.ready();
495 // 7. Create a new read Tx from the chain to read the data
496 // from the last RW Tx to
497 // verify it is visible.
498 readTx = txChain.newReadWriteTransaction();
499 optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
500 assertTrue("isPresent", optional.isPresent());
501 assertEquals("Data node", outerNode, optional.get());
503 // 8. Wait for the 2 commits to complete and close the
505 continueCommit1.countDown();
506 Uninterruptibles.awaitUninterruptibly(commit1Done, 5, TimeUnit.SECONDS);
508 if (commit1Error.get() != null) {
509 throw commit1Error.get();
512 testKit.doCommit(cohort2);
516 // 9. Create a new read Tx from the data store and verify
518 readTx = dataStore.newReadOnlyTransaction();
519 optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
520 assertTrue("isPresent", optional.isPresent());
521 assertEquals("Data node", outerNode, optional.get());
526 public void testTransactionChainWithMultipleShards() throws Exception {
527 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
528 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
529 testParameter, "testTransactionChainWithMultipleShards", "cars-1", "people-1")) {
531 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
533 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
534 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
536 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
537 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
539 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
540 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
542 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
544 final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
546 final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
547 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
548 readWriteTx.write(carPath, car);
550 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
551 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
552 readWriteTx.merge(personPath, person);
554 Optional<NormalizedNode> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
555 assertTrue("isPresent", optional.isPresent());
556 assertEquals("Data node", car, optional.get());
558 optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
559 assertTrue("isPresent", optional.isPresent());
560 assertEquals("Data node", person, optional.get());
562 final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
564 writeTx = txChain.newWriteOnlyTransaction();
566 writeTx.delete(carPath);
568 final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
570 final ListenableFuture<Boolean> canCommit1 = cohort1.canCommit();
571 final ListenableFuture<Boolean> canCommit2 = cohort2.canCommit();
573 testKit.doCommit(canCommit1, cohort1);
574 testKit.doCommit(canCommit2, cohort2);
575 testKit.doCommit(cohort3);
579 final DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
581 optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
582 assertFalse("isPresent", optional.isPresent());
584 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
585 assertTrue("isPresent", optional.isPresent());
586 assertEquals("Data node", person, optional.get());
591 public void testCreateChainedTransactionsInQuickSuccession() throws Exception {
592 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
593 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
594 testParameter, "testCreateChainedTransactionsInQuickSuccession", "cars-1")) {
596 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
597 ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
598 .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
599 MoreExecutors.directExecutor());
601 final DOMTransactionChainListener listener = Mockito.mock(DOMTransactionChainListener.class);
602 DOMTransactionChain txChain = broker.createTransactionChain(listener);
604 final List<ListenableFuture<?>> futures = new ArrayList<>();
606 final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
607 writeTx.put(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, CarsModel.emptyContainer());
608 writeTx.put(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
609 futures.add(writeTx.commit());
612 for (int i = 0; i < numCars; i++) {
613 final DOMDataTreeReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
615 rwTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.newCarPath("car" + i),
616 CarsModel.newCarEntry("car" + i, Uint64.valueOf(20000)));
618 futures.add(rwTx.commit());
621 for (final ListenableFuture<?> f : futures) {
622 f.get(5, TimeUnit.SECONDS);
625 final Optional<NormalizedNode> optional = txChain.newReadOnlyTransaction()
626 .read(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
627 assertTrue("isPresent", optional.isPresent());
628 assertEquals("# cars", numCars, ((Collection<?>) optional.get().body()).size());
637 public void testCreateChainedTransactionAfterEmptyTxReadied() throws Exception {
638 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
639 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
640 testParameter, "testCreateChainedTransactionAfterEmptyTxReadied", "test-1")) {
642 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
644 final DOMStoreReadWriteTransaction rwTx1 = txChain.newReadWriteTransaction();
648 final DOMStoreReadWriteTransaction rwTx2 = txChain.newReadWriteTransaction();
650 final Optional<NormalizedNode> optional = rwTx2.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
651 assertFalse("isPresent", optional.isPresent());
658 public void testCreateChainedTransactionWhenPreviousNotReady() throws Exception {
659 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
660 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
661 testParameter, "testCreateChainedTransactionWhenPreviousNotReady", "test-1")) {
663 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
665 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
666 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
668 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
670 // Try to create another Tx of each type - each should fail
671 // b/c the previous Tx wasn't
673 testKit.assertExceptionOnTxChainCreates(txChain, IllegalStateException.class);
678 public void testCreateChainedTransactionAfterClose() throws Exception {
679 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
680 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
681 testParameter, "testCreateChainedTransactionAfterClose", "test-1")) {
683 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
686 // Try to create another Tx of each type - should fail b/c
687 // the previous Tx was closed.
688 testKit.assertExceptionOnTxChainCreates(txChain, DOMTransactionChainClosedException.class);
693 public void testChainWithReadOnlyTxAfterPreviousReady() throws Exception {
694 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
695 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
696 testParameter, "testChainWithReadOnlyTxAfterPreviousReady", "test-1")) {
698 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
700 // Create a write tx and submit.
701 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
702 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
703 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
705 // Create read-only tx's and issue a read.
706 FluentFuture<Optional<NormalizedNode>> readFuture1 = txChain
707 .newReadOnlyTransaction().read(TestModel.TEST_PATH);
709 FluentFuture<Optional<NormalizedNode>> readFuture2 = txChain
710 .newReadOnlyTransaction().read(TestModel.TEST_PATH);
712 // Create another write tx and issue the write.
713 DOMStoreWriteTransaction writeTx2 = txChain.newWriteOnlyTransaction();
714 writeTx2.write(TestModel.OUTER_LIST_PATH,
715 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
716 .withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 42))
719 // Ensure the reads succeed.
721 assertTrue("isPresent", readFuture1.get(5, TimeUnit.SECONDS).isPresent());
722 assertTrue("isPresent", readFuture2.get(5, TimeUnit.SECONDS).isPresent());
724 // Ensure the writes succeed.
725 DOMStoreThreePhaseCommitCohort cohort2 = writeTx2.ready();
727 testKit.doCommit(cohort1);
728 testKit.doCommit(cohort2);
730 assertTrue("isPresent", txChain.newReadOnlyTransaction().read(TestModel.OUTER_LIST_PATH)
731 .get(5, TimeUnit.SECONDS).isPresent());
736 public void testChainedTransactionFailureWithSingleShard() throws Exception {
737 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
738 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
739 testParameter, "testChainedTransactionFailureWithSingleShard", "cars-1")) {
741 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
742 ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
743 .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
744 MoreExecutors.directExecutor());
746 final DOMTransactionChainListener listener = Mockito.mock(DOMTransactionChainListener.class);
747 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
749 final DOMDataTreeReadWriteTransaction writeTx = txChain.newReadWriteTransaction();
751 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH,
752 PeopleModel.emptyContainer());
754 final ContainerNode invalidData = Builders.containerBuilder()
755 .withNodeIdentifier(new NodeIdentifier(CarsModel.BASE_QNAME))
756 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk"))
759 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
762 writeTx.commit().get(5, TimeUnit.SECONDS);
763 fail("Expected TransactionCommitFailedException");
764 } catch (final ExecutionException e) {
768 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx),
769 any(Throwable.class));
777 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
778 final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
779 try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
780 testParameter, "testChainedTransactionFailureWithMultipleShards", "cars-1", "people-1")) {
782 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
783 ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
784 .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
785 MoreExecutors.directExecutor());
787 final DOMTransactionChainListener listener = Mockito.mock(DOMTransactionChainListener.class);
788 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
790 final DOMDataTreeWriteTransaction writeTx = txChain.newReadWriteTransaction();
792 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH,
793 PeopleModel.emptyContainer());
795 final ContainerNode invalidData = Builders.containerBuilder()
796 .withNodeIdentifier(new NodeIdentifier(CarsModel.BASE_QNAME))
797 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk"))
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 = Builders.containerBuilder()
936 .withNodeIdentifier(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());