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
9 package org.opendaylight.controller.cluster.datastore;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertTrue;
14 import static org.junit.Assert.fail;
15 import static org.mockito.Matchers.any;
16 import static org.mockito.Matchers.eq;
17 import static org.mockito.Mockito.timeout;
18 import static org.mockito.Mockito.verify;
20 import akka.actor.ActorSystem;
21 import akka.actor.Address;
22 import akka.actor.AddressFromURIString;
23 import akka.cluster.Cluster;
24 import akka.testkit.JavaTestKit;
25 import com.google.common.base.Optional;
26 import com.google.common.base.Throwables;
27 import com.google.common.collect.ImmutableMap;
28 import com.google.common.util.concurrent.CheckedFuture;
29 import com.google.common.util.concurrent.ListenableFuture;
30 import com.google.common.util.concurrent.MoreExecutors;
31 import com.google.common.util.concurrent.Uninterruptibles;
32 import com.typesafe.config.ConfigFactory;
33 import java.io.IOException;
34 import java.math.BigInteger;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.Collection;
38 import java.util.Collections;
39 import java.util.List;
40 import java.util.concurrent.CountDownLatch;
41 import java.util.concurrent.ExecutionException;
42 import java.util.concurrent.TimeUnit;
43 import java.util.concurrent.TimeoutException;
44 import java.util.concurrent.atomic.AtomicReference;
45 import org.junit.After;
46 import org.junit.Before;
47 import org.junit.Test;
48 import org.junit.runner.RunWith;
49 import org.junit.runners.Parameterized;
50 import org.junit.runners.Parameterized.Parameter;
51 import org.junit.runners.Parameterized.Parameters;
52 import org.mockito.Mockito;
53 import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
54 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
55 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
56 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
57 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
58 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
59 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
60 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
61 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
62 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
63 import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
64 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
65 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
66 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
67 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
68 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
69 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
70 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
71 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
72 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
73 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
74 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainClosedException;
75 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
76 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
77 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
78 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
79 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
80 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
81 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
82 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
83 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
84 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
85 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
86 import org.opendaylight.yangtools.concepts.ListenerRegistration;
87 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
88 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
90 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
91 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
92 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
93 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
94 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
95 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
96 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
98 @RunWith(Parameterized.class)
99 public class DistributedDataStoreIntegrationTest {
101 @Parameters(name = "{0}")
102 public static Collection<Object[]> data() {
103 return Arrays.asList(new Object[][] {
104 { DistributedDataStore.class }, { ClientBackedDataStore.class }
109 public Class<? extends AbstractDataStore> testParameter;
111 private ActorSystem system;
113 private final DatastoreContext.Builder datastoreContextBuilder = DatastoreContext.newBuilder()
114 .shardHeartbeatIntervalInMillis(100);
117 public void setUp() throws IOException {
118 InMemorySnapshotStore.clear();
119 InMemoryJournal.clear();
120 system = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
121 Address member1Address = AddressFromURIString.parse("akka://cluster-test@127.0.0.1:2558");
122 Cluster.get(system).join(member1Address);
126 public void tearDown() throws IOException {
127 JavaTestKit.shutdownActorSystem(system, null, Boolean.TRUE);
131 protected ActorSystem getSystem() {
136 public void testWriteTransactionWithSingleShard() throws Exception {
137 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
139 try (AbstractDataStore dataStore = setupAbstractDataStore(
140 testParameter, "transactionIntegrationTest", "test-1")) {
142 testWriteTransaction(dataStore, TestModel.TEST_PATH,
143 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
145 testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
146 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
153 public void testWriteTransactionWithMultipleShards() throws Exception {
154 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
156 try (AbstractDataStore dataStore = setupAbstractDataStore(
157 testParameter, "testWriteTransactionWithMultipleShards", "cars-1", "people-1")) {
159 DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
160 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
162 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
163 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
165 doCommit(writeTx.ready());
167 writeTx = dataStore.newWriteOnlyTransaction();
169 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
170 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
172 doCommit(writeTx.ready());
174 writeTx = dataStore.newWriteOnlyTransaction();
176 final MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
177 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
178 writeTx.write(carPath, car);
180 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
181 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
182 writeTx.write(personPath, person);
184 doCommit(writeTx.ready());
186 // Verify the data in the store
187 final DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
189 Optional<NormalizedNode<?, ?>> optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
190 assertEquals("isPresent", true, optional.isPresent());
191 assertEquals("Data node", car, optional.get());
193 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
194 assertEquals("isPresent", true, optional.isPresent());
195 assertEquals("Data node", person, optional.get());
202 public void testReadWriteTransactionWithSingleShard() throws Exception {
203 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
205 try (AbstractDataStore dataStore = setupAbstractDataStore(
206 testParameter, "testReadWriteTransactionWithSingleShard", "test-1")) {
208 // 1. Create a read-write Tx
209 final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
210 assertNotNull("newReadWriteTransaction returned null", readWriteTx);
212 // 2. Write some data
213 final YangInstanceIdentifier nodePath = TestModel.TEST_PATH;
214 final NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
215 readWriteTx.write(nodePath, nodeToWrite);
217 // 3. Read the data from Tx
218 final Boolean exists = readWriteTx.exists(nodePath).checkedGet(5, TimeUnit.SECONDS);
219 assertEquals("exists", true, exists);
221 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(nodePath).get(5, TimeUnit.SECONDS);
222 assertEquals("isPresent", true, optional.isPresent());
223 assertEquals("Data node", nodeToWrite, optional.get());
225 // 4. Ready the Tx for commit
226 final DOMStoreThreePhaseCommitCohort cohort = readWriteTx.ready();
231 // 6. Verify the data in the store
232 final DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
234 optional = readTx.read(nodePath).get(5, TimeUnit.SECONDS);
235 assertEquals("isPresent", true, optional.isPresent());
236 assertEquals("Data node", nodeToWrite, optional.get());
243 public void testReadWriteTransactionWithMultipleShards() throws Exception {
244 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
246 try (AbstractDataStore dataStore = setupAbstractDataStore(
247 testParameter, "testReadWriteTransactionWithMultipleShards", "cars-1", "people-1")) {
249 DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
250 assertNotNull("newReadWriteTransaction returned null", readWriteTx);
252 readWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
253 readWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
255 doCommit(readWriteTx.ready());
257 readWriteTx = dataStore.newReadWriteTransaction();
259 readWriteTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
260 readWriteTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
262 doCommit(readWriteTx.ready());
264 readWriteTx = dataStore.newReadWriteTransaction();
266 final MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
267 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
268 readWriteTx.write(carPath, car);
270 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
271 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
272 readWriteTx.write(personPath, person);
274 final Boolean exists = readWriteTx.exists(carPath).checkedGet(5, TimeUnit.SECONDS);
275 assertEquals("exists", true, exists);
277 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
278 assertEquals("isPresent", true, optional.isPresent());
279 assertEquals("Data node", car, optional.get());
281 doCommit(readWriteTx.ready());
283 // Verify the data in the store
284 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
286 optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
287 assertEquals("isPresent", true, optional.isPresent());
288 assertEquals("Data node", car, optional.get());
290 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
291 assertEquals("isPresent", true, optional.isPresent());
292 assertEquals("Data node", person, optional.get());
300 public void testSingleTransactionsWritesInQuickSuccession() throws Exception {
301 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
303 try (AbstractDataStore dataStore = setupAbstractDataStore(
304 testParameter, "testSingleTransactionsWritesInQuickSuccession", "cars-1")) {
306 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
308 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
309 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
310 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
311 doCommit(writeTx.ready());
313 writeTx = txChain.newWriteOnlyTransaction();
316 for (int i = 0; i < numCars; i++) {
317 writeTx.write(CarsModel.newCarPath("car" + i),
318 CarsModel.newCarEntry("car" + i, BigInteger.valueOf(20000)));
321 doCommit(writeTx.ready());
323 final Optional<NormalizedNode<?, ?>> optional = txChain.newReadOnlyTransaction()
324 .read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
325 assertEquals("isPresent", true, optional.isPresent());
326 assertEquals("# cars", numCars, ((Collection<?>) optional.get().getValue()).size());
332 @SuppressWarnings("checkstyle:IllegalCatch")
333 private void testTransactionWritesWithShardNotInitiallyReady(final String testName, final boolean writeOnly)
335 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
337 final String shardName = "test-1";
339 // Setup the InMemoryJournal to block shard recovery to ensure
341 // initialized until we create and submit the write the Tx.
342 final String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
343 final CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
344 InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
346 try (AbstractDataStore dataStore = setupAbstractDataStore(
347 testParameter, testName, false, shardName)) {
349 // Create the write Tx
350 final DOMStoreWriteTransaction writeTx = writeOnly ? dataStore.newWriteOnlyTransaction()
351 : dataStore.newReadWriteTransaction();
352 assertNotNull("newReadWriteTransaction returned null", writeTx);
354 // Do some modification operations and ready the Tx on a
356 final YangInstanceIdentifier listEntryPath = YangInstanceIdentifier
357 .builder(TestModel.OUTER_LIST_PATH)
358 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build();
360 final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
361 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
362 final CountDownLatch txReady = new CountDownLatch(1);
363 final Thread txThread = new Thread(() -> {
365 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
367 writeTx.merge(TestModel.OUTER_LIST_PATH,
368 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
370 writeTx.write(listEntryPath,
371 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1));
373 writeTx.delete(listEntryPath);
375 txCohort.set(writeTx.ready());
376 } catch (Exception e) {
385 // Wait for the Tx operations to complete.
386 final boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
387 if (caughtEx.get() != null) {
388 throw caughtEx.get();
391 assertEquals("Tx ready", true, done);
393 // At this point the Tx operations should be waiting for the
394 // shard to initialize so
395 // trigger the latch to let the shard recovery to continue.
396 blockRecoveryLatch.countDown();
398 // Wait for the Tx commit to complete.
399 doCommit(txCohort.get());
401 // Verify the data in the store
402 final DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
404 Optional<NormalizedNode<?, ?>> optional = readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
405 assertEquals("isPresent", true, optional.isPresent());
407 optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
408 assertEquals("isPresent", true, optional.isPresent());
410 optional = readTx.read(listEntryPath).get(5, TimeUnit.SECONDS);
411 assertEquals("isPresent", false, optional.isPresent());
418 public void testWriteOnlyTransactionWithShardNotInitiallyReady() throws Exception {
419 datastoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
420 testTransactionWritesWithShardNotInitiallyReady("testWriteOnlyTransactionWithShardNotInitiallyReady", true);
424 public void testReadWriteTransactionWithShardNotInitiallyReady() throws Exception {
425 testTransactionWritesWithShardNotInitiallyReady("testReadWriteTransactionWithShardNotInitiallyReady", false);
429 @SuppressWarnings("checkstyle:IllegalCatch")
430 public void testTransactionReadsWithShardNotInitiallyReady() throws Exception {
431 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
433 final String testName = "testTransactionReadsWithShardNotInitiallyReady";
434 final String shardName = "test-1";
436 // Setup the InMemoryJournal to block shard recovery to ensure
438 // initialized until we create the Tx.
439 final String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
440 final CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
441 InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
443 try (AbstractDataStore dataStore = setupAbstractDataStore(
444 testParameter, testName, false, shardName)) {
446 // Create the read-write Tx
447 final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
448 assertNotNull("newReadWriteTransaction returned null", readWriteTx);
450 // Do some reads on the Tx on a separate thread.
451 final AtomicReference<CheckedFuture<Boolean, ReadFailedException>> txExistsFuture =
452 new AtomicReference<>();
453 final AtomicReference<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>>
454 txReadFuture = new AtomicReference<>();
455 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
456 final CountDownLatch txReadsDone = new CountDownLatch(1);
457 final Thread txThread = new Thread(() -> {
459 readWriteTx.write(TestModel.TEST_PATH,
460 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
462 txExistsFuture.set(readWriteTx.exists(TestModel.TEST_PATH));
464 txReadFuture.set(readWriteTx.read(TestModel.TEST_PATH));
465 } catch (Exception e) {
468 txReadsDone.countDown();
474 // Wait for the Tx operations to complete.
475 boolean done = Uninterruptibles.awaitUninterruptibly(txReadsDone, 5, TimeUnit.SECONDS);
476 if (caughtEx.get() != null) {
477 throw caughtEx.get();
480 assertEquals("Tx reads done", true, done);
482 // At this point the Tx operations should be waiting for the
483 // shard to initialize so
484 // trigger the latch to let the shard recovery to continue.
485 blockRecoveryLatch.countDown();
487 // Wait for the reads to complete and verify.
488 assertEquals("exists", true, txExistsFuture.get().checkedGet(5, TimeUnit.SECONDS));
489 assertEquals("read", true, txReadFuture.get().checkedGet(5, TimeUnit.SECONDS).isPresent());
497 @Test(expected = NotInitializedException.class)
498 @SuppressWarnings("checkstyle:IllegalCatch")
499 public void testTransactionCommitFailureWithShardNotInitialized() throws Exception {
500 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
502 final String testName = "testTransactionCommitFailureWithShardNotInitialized";
503 final String shardName = "test-1";
505 // Set the shard initialization timeout low for the test.
506 datastoreContextBuilder.shardInitializationTimeout(300, TimeUnit.MILLISECONDS);
508 // Setup the InMemoryJournal to block shard recovery
510 final String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
511 final CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
512 InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
514 InMemoryJournal.addEntry(persistentID, 1, "Dummy data so akka will read from persistence");
516 final AbstractDataStore dataStore =
517 setupAbstractDataStore(testParameter, testName, false, shardName);
519 // Create the write Tx
520 final DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
521 assertNotNull("newReadWriteTransaction returned null", writeTx);
523 // Do some modifications and ready the Tx on a separate
525 final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
526 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
527 final CountDownLatch txReady = new CountDownLatch(1);
528 final Thread txThread = new Thread(() -> {
530 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
532 txCohort.set(writeTx.ready());
533 } catch (Exception e) {
542 // Wait for the Tx operations to complete.
543 boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
544 if (caughtEx.get() != null) {
545 throw caughtEx.get();
548 assertEquals("Tx ready", true, done);
550 // Wait for the commit to complete. Since the shard never
551 // initialized, the Tx should
552 // have timed out and throw an appropriate exception cause.
554 txCohort.get().canCommit().get(5, TimeUnit.SECONDS);
555 fail("Expected NotInitializedException");
556 } catch (final Exception e) {
557 Throwables.propagate(Throwables.getRootCause(e));
559 blockRecoveryLatch.countDown();
565 @Test(expected = NotInitializedException.class)
566 @SuppressWarnings("checkstyle:IllegalCatch")
567 public void testTransactionReadFailureWithShardNotInitialized() throws Exception {
568 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
570 final String testName = "testTransactionReadFailureWithShardNotInitialized";
571 final String shardName = "test-1";
573 // Set the shard initialization timeout low for the test.
574 datastoreContextBuilder.shardInitializationTimeout(300, TimeUnit.MILLISECONDS);
576 // Setup the InMemoryJournal to block shard recovery
578 final String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
579 final CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
580 InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
582 InMemoryJournal.addEntry(persistentID, 1, "Dummy data so akka will read from persistence");
584 try (AbstractDataStore dataStore = setupAbstractDataStore(
585 testParameter, testName, false, shardName)) {
587 // Create the read-write Tx
588 final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
589 assertNotNull("newReadWriteTransaction returned null", readWriteTx);
591 // Do a read on the Tx on a separate thread.
592 final AtomicReference<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>>
593 txReadFuture = new AtomicReference<>();
594 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
595 final CountDownLatch txReadDone = new CountDownLatch(1);
596 final Thread txThread = new Thread(() -> {
598 readWriteTx.write(TestModel.TEST_PATH,
599 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
601 txReadFuture.set(readWriteTx.read(TestModel.TEST_PATH));
604 } catch (Exception e) {
607 txReadDone.countDown();
613 // Wait for the Tx operations to complete.
614 boolean done = Uninterruptibles.awaitUninterruptibly(txReadDone, 5, TimeUnit.SECONDS);
615 if (caughtEx.get() != null) {
616 throw caughtEx.get();
619 assertEquals("Tx read done", true, done);
621 // Wait for the read to complete. Since the shard never
622 // initialized, the Tx should
623 // have timed out and throw an appropriate exception cause.
625 txReadFuture.get().checkedGet(5, TimeUnit.SECONDS);
626 fail("Expected NotInitializedException");
627 } catch (final ReadFailedException e) {
628 Throwables.propagate(Throwables.getRootCause(e));
630 blockRecoveryLatch.countDown();
637 @SuppressWarnings("checkstyle:IllegalCatch")
638 private void testTransactionCommitFailureWithNoShardLeader(final boolean writeOnly, final String testName)
640 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
642 final String shardName = "default";
644 // We don't want the shard to become the leader so prevent shard
646 datastoreContextBuilder.customRaftPolicyImplementation(
647 "org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy");
649 // The ShardManager uses the election timeout for FindPrimary so
650 // reset it low so it will timeout quickly.
651 datastoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(1)
652 .shardInitializationTimeout(200, TimeUnit.MILLISECONDS);
654 try (AbstractDataStore dataStore = setupAbstractDataStore(
655 testParameter, testName, false, shardName)) {
657 final Object result = dataStore.getActorContext().executeOperation(
658 dataStore.getActorContext().getShardManager(), new FindLocalShard(shardName, true));
659 assertTrue("Expected LocalShardFound. Actual: " + result, result instanceof LocalShardFound);
661 // Create the write Tx.
662 DOMStoreWriteTransaction writeTxToClose = null;
664 writeTxToClose = writeOnly ? dataStore.newWriteOnlyTransaction()
665 : dataStore.newReadWriteTransaction();
666 final DOMStoreWriteTransaction writeTx = writeTxToClose;
667 assertNotNull("newReadWriteTransaction returned null", writeTx);
669 // Do some modifications and ready the Tx on a separate
671 final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
672 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
673 final CountDownLatch txReady = new CountDownLatch(1);
674 final Thread txThread = new Thread(() -> {
676 writeTx.write(TestModel.JUNK_PATH,
677 ImmutableNodes.containerNode(TestModel.JUNK_QNAME));
679 txCohort.set(writeTx.ready());
680 } catch (Exception e) {
689 // Wait for the Tx operations to complete.
690 boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
691 if (caughtEx.get() != null) {
692 throw caughtEx.get();
695 assertEquals("Tx ready", true, done);
697 // Wait for the commit to complete. Since no shard
698 // leader was elected in time, the Tx
699 // should have timed out and throw an appropriate
702 txCohort.get().canCommit().get(5, TimeUnit.SECONDS);
703 fail("Expected NoShardLeaderException");
704 } catch (final ExecutionException e) {
705 assertTrue(Throwables.getRootCause(e) instanceof NoShardLeaderException);
706 assertEquals(DistributedDataStore.class, testParameter);
707 } catch (TimeoutException e) {
708 // ClientBackedDataStore doesn't set cause to ExecutionException, future just time outs
709 assertEquals(ClientBackedDataStore.class, testParameter);
713 if (writeTxToClose != null) {
714 writeTxToClose.close();
716 } catch (Exception e) {
717 // FIXME TransactionProxy.close throws IllegalStateException:
718 // Transaction is ready, it cannot be closed
727 public void testWriteOnlyTransactionCommitFailureWithNoShardLeader() throws Exception {
728 datastoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
729 testTransactionCommitFailureWithNoShardLeader(true, "testWriteOnlyTransactionCommitFailureWithNoShardLeader");
733 public void testReadWriteTransactionCommitFailureWithNoShardLeader() throws Exception {
734 testTransactionCommitFailureWithNoShardLeader(false, "testReadWriteTransactionCommitFailureWithNoShardLeader");
738 public void testTransactionAbort() throws Exception {
739 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
741 try (AbstractDataStore dataStore = setupAbstractDataStore(
742 testParameter, "transactionAbortIntegrationTest", "test-1")) {
744 final DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
745 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
747 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
749 final DOMStoreThreePhaseCommitCohort cohort = writeTx.ready();
751 cohort.canCommit().get(5, TimeUnit.SECONDS);
753 cohort.abort().get(5, TimeUnit.SECONDS);
755 testWriteTransaction(dataStore, TestModel.TEST_PATH,
756 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
763 @SuppressWarnings("checkstyle:IllegalCatch")
764 public void testTransactionChainWithSingleShard() throws Exception {
765 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
767 try (AbstractDataStore dataStore = setupAbstractDataStore(
768 testParameter, "testTransactionChainWithSingleShard", "test-1")) {
770 // 1. Create a Tx chain and write-only Tx
771 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
773 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
774 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
776 // 2. Write some data
777 final NormalizedNode<?, ?> testNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
778 writeTx.write(TestModel.TEST_PATH, testNode);
780 // 3. Ready the Tx for commit
781 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
783 // 4. Commit the Tx on another thread that first waits for
784 // the second read Tx.
785 final CountDownLatch continueCommit1 = new CountDownLatch(1);
786 final CountDownLatch commit1Done = new CountDownLatch(1);
787 final AtomicReference<Exception> commit1Error = new AtomicReference<>();
790 continueCommit1.await();
792 } catch (Exception e) {
795 commit1Done.countDown();
799 // 5. Create a new read Tx from the chain to read and verify
800 // the data from the first
801 // Tx is visible after being readied.
802 DOMStoreReadTransaction readTx = txChain.newReadOnlyTransaction();
803 Optional<NormalizedNode<?, ?>> optional = readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
804 assertEquals("isPresent", true, optional.isPresent());
805 assertEquals("Data node", testNode, optional.get());
807 // 6. Create a new RW Tx from the chain, write more data,
809 final DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
810 final MapNode outerNode = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
811 rwTx.write(TestModel.OUTER_LIST_PATH, outerNode);
813 final DOMStoreThreePhaseCommitCohort cohort2 = rwTx.ready();
815 // 7. Create a new read Tx from the chain to read the data
816 // from the last RW Tx to
817 // verify it is visible.
818 readTx = txChain.newReadWriteTransaction();
819 optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
820 assertEquals("isPresent", true, optional.isPresent());
821 assertEquals("Data node", outerNode, optional.get());
823 // 8. Wait for the 2 commits to complete and close the
825 continueCommit1.countDown();
826 Uninterruptibles.awaitUninterruptibly(commit1Done, 5, TimeUnit.SECONDS);
828 if (commit1Error.get() != null) {
829 throw commit1Error.get();
836 // 9. Create a new read Tx from the data store and verify
838 readTx = dataStore.newReadOnlyTransaction();
839 optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
840 assertEquals("isPresent", true, optional.isPresent());
841 assertEquals("Data node", outerNode, optional.get());
848 public void testTransactionChainWithMultipleShards() throws Exception {
849 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
851 try (AbstractDataStore dataStore = setupAbstractDataStore(
852 testParameter, "testTransactionChainWithMultipleShards", "cars-1", "people-1")) {
854 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
856 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
857 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
859 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
860 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
862 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
863 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
865 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
867 final DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
869 final MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
870 final YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
871 readWriteTx.write(carPath, car);
873 final MapEntryNode person = PeopleModel.newPersonEntry("jack");
874 final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
875 readWriteTx.merge(personPath, person);
877 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
878 assertEquals("isPresent", true, optional.isPresent());
879 assertEquals("Data node", car, optional.get());
881 optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
882 assertEquals("isPresent", true, optional.isPresent());
883 assertEquals("Data node", person, optional.get());
885 final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
887 writeTx = txChain.newWriteOnlyTransaction();
889 writeTx.delete(carPath);
891 final DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
893 final ListenableFuture<Boolean> canCommit1 = cohort1.canCommit();
894 final ListenableFuture<Boolean> canCommit2 = cohort2.canCommit();
896 doCommit(canCommit1, cohort1);
897 doCommit(canCommit2, cohort2);
902 final DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
904 optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
905 assertEquals("isPresent", false, optional.isPresent());
907 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
908 assertEquals("isPresent", true, optional.isPresent());
909 assertEquals("Data node", person, optional.get());
916 public void testCreateChainedTransactionsInQuickSuccession() throws Exception {
917 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
919 try (AbstractDataStore dataStore = setupAbstractDataStore(
920 testParameter, "testCreateChainedTransactionsInQuickSuccession", "cars-1")) {
922 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
923 ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
924 .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
925 MoreExecutors.directExecutor());
927 final TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
928 DOMTransactionChain txChain = broker.createTransactionChain(listener);
930 final List<CheckedFuture<Void, TransactionCommitFailedException>> futures = new ArrayList<>();
932 final DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
933 writeTx.put(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, CarsModel.emptyContainer());
934 writeTx.put(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
935 futures.add(writeTx.submit());
938 for (int i = 0; i < numCars; i++) {
939 final DOMDataReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
941 rwTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.newCarPath("car" + i),
942 CarsModel.newCarEntry("car" + i, BigInteger.valueOf(20000)));
944 futures.add(rwTx.submit());
947 for (final CheckedFuture<Void, TransactionCommitFailedException> f : futures) {
951 final Optional<NormalizedNode<?, ?>> optional = txChain.newReadOnlyTransaction()
952 .read(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
953 assertEquals("isPresent", true, optional.isPresent());
954 assertEquals("# cars", numCars, ((Collection<?>) optional.get().getValue()).size());
965 public void testCreateChainedTransactionAfterEmptyTxReadied() throws Exception {
966 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
968 try (AbstractDataStore dataStore = setupAbstractDataStore(
969 testParameter, "testCreateChainedTransactionAfterEmptyTxReadied", "test-1")) {
971 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
973 final DOMStoreReadWriteTransaction rwTx1 = txChain.newReadWriteTransaction();
977 final DOMStoreReadWriteTransaction rwTx2 = txChain.newReadWriteTransaction();
979 final Optional<NormalizedNode<?, ?>> optional = rwTx2.read(TestModel.TEST_PATH).get(
980 5, TimeUnit.SECONDS);
981 assertEquals("isPresent", false, optional.isPresent());
990 public void testCreateChainedTransactionWhenPreviousNotReady() throws Exception {
991 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
993 try (AbstractDataStore dataStore = setupAbstractDataStore(
994 testParameter, "testCreateChainedTransactionWhenPreviousNotReady", "test-1")) {
996 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
998 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
999 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
1001 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1003 // Try to create another Tx of each type - each should fail
1004 // b/c the previous Tx wasn't
1006 assertExceptionOnTxChainCreates(txChain, IllegalStateException.class);
1013 public void testCreateChainedTransactionAfterClose() throws Exception {
1014 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1016 try (AbstractDataStore dataStore = setupAbstractDataStore(
1017 testParameter, "testCreateChainedTransactionAfterClose", "test-1")) {
1019 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
1022 // Try to create another Tx of each type - should fail b/c
1023 // the previous Tx was closed.
1024 assertExceptionOnTxChainCreates(txChain, TransactionChainClosedException.class);
1031 public void testChainWithReadOnlyTxAfterPreviousReady() throws Exception {
1032 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1034 try (AbstractDataStore dataStore = setupAbstractDataStore(
1035 testParameter, "testChainWithReadOnlyTxAfterPreviousReady", "test-1")) {
1037 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
1039 // Create a write tx and submit.
1040 final DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
1041 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1042 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
1044 // Create read-only tx's and issue a read.
1045 CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture1 = txChain
1046 .newReadOnlyTransaction().read(TestModel.TEST_PATH);
1048 CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture2 = txChain
1049 .newReadOnlyTransaction().read(TestModel.TEST_PATH);
1051 // Create another write tx and issue the write.
1052 DOMStoreWriteTransaction writeTx2 = txChain.newWriteOnlyTransaction();
1053 writeTx2.write(TestModel.OUTER_LIST_PATH,
1054 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1056 // Ensure the reads succeed.
1058 assertEquals("isPresent", true, readFuture1.checkedGet(5, TimeUnit.SECONDS).isPresent());
1059 assertEquals("isPresent", true, readFuture2.checkedGet(5, TimeUnit.SECONDS).isPresent());
1061 // Ensure the writes succeed.
1062 DOMStoreThreePhaseCommitCohort cohort2 = writeTx2.ready();
1067 assertEquals("isPresent", true, txChain.newReadOnlyTransaction().read(TestModel.OUTER_LIST_PATH)
1068 .checkedGet(5, TimeUnit.SECONDS).isPresent());
1075 public void testChainedTransactionFailureWithSingleShard() throws Exception {
1076 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1078 try (AbstractDataStore dataStore = setupAbstractDataStore(
1079 testParameter, "testChainedTransactionFailureWithSingleShard", "cars-1")) {
1081 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
1082 ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
1083 .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
1084 MoreExecutors.directExecutor());
1086 final TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
1087 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
1089 final DOMDataReadWriteTransaction writeTx = txChain.newReadWriteTransaction();
1091 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH,
1092 PeopleModel.emptyContainer());
1094 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
1095 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
1096 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
1098 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
1101 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
1102 fail("Expected TransactionCommitFailedException");
1103 } catch (final TransactionCommitFailedException e) {
1107 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx),
1108 any(Throwable.class));
1118 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
1119 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1121 try (AbstractDataStore dataStore = setupAbstractDataStore(
1122 testParameter, "testChainedTransactionFailureWithMultipleShards", "cars-1", "people-1")) {
1124 final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
1125 ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
1126 .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
1127 MoreExecutors.directExecutor());
1129 final TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
1130 final DOMTransactionChain txChain = broker.createTransactionChain(listener);
1132 final DOMDataReadWriteTransaction writeTx = txChain.newReadWriteTransaction();
1134 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH,
1135 PeopleModel.emptyContainer());
1137 final ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
1138 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
1139 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
1141 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
1143 // Note that merge will validate the data and fail but put
1144 // succeeds b/c deep validation is not
1145 // done for put for performance reasons.
1147 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
1148 fail("Expected TransactionCommitFailedException");
1149 } catch (final TransactionCommitFailedException e) {
1153 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx),
1154 any(Throwable.class));
1164 public void testChangeListenerRegistration() throws Exception {
1165 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1167 try (AbstractDataStore dataStore = setupAbstractDataStore(
1168 testParameter, "testChangeListenerRegistration", "test-1")) {
1170 testWriteTransaction(dataStore, TestModel.TEST_PATH,
1171 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1173 final MockDataChangeListener listener = new MockDataChangeListener(1);
1175 final ListenerRegistration<MockDataChangeListener> listenerReg = dataStore
1176 .registerChangeListener(TestModel.TEST_PATH, listener, DataChangeScope.SUBTREE);
1178 assertNotNull("registerChangeListener returned null", listenerReg);
1180 IntegrationTestKit.verifyShardState(dataStore, "test-1",
1181 state -> assertEquals("getDataChangeListenerActors", 1,
1182 state.getDataChangeListenerActors().size()));
1184 // Wait for the initial notification
1185 listener.waitForChangeEvents(TestModel.TEST_PATH);
1189 testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
1190 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1192 YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1193 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build();
1194 testWriteTransaction(dataStore, listPath,
1195 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1));
1197 // Wait for the 2 updates.
1198 listener.waitForChangeEvents(TestModel.OUTER_LIST_PATH, listPath);
1199 listenerReg.close();
1201 IntegrationTestKit.verifyShardState(dataStore, "test-1",
1202 state -> assertEquals("getDataChangeListenerActors", 0,
1203 state.getDataChangeListenerActors().size()));
1205 testWriteTransaction(dataStore,
1206 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1207 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build(),
1208 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2));
1210 listener.expectNoMoreChanges("Received unexpected change after close");
1217 public void testDataTreeChangeListenerRegistration() throws Exception {
1218 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1220 try (AbstractDataStore dataStore = setupAbstractDataStore(
1221 testParameter, "testDataTreeChangeListenerRegistration", "test-1")) {
1223 testWriteTransaction(dataStore, TestModel.TEST_PATH,
1224 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1226 final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
1228 ListenerRegistration<MockDataTreeChangeListener> listenerReg = dataStore
1229 .registerTreeChangeListener(TestModel.TEST_PATH, listener);
1231 assertNotNull("registerTreeChangeListener returned null", listenerReg);
1233 IntegrationTestKit.verifyShardState(dataStore, "test-1",
1234 state -> assertEquals("getTreeChangeListenerActors", 1,
1235 state.getTreeChangeListenerActors().size()));
1237 // Wait for the initial notification
1238 listener.waitForChangeEvents(TestModel.TEST_PATH);
1242 testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
1243 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1245 YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1246 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build();
1247 testWriteTransaction(dataStore, listPath,
1248 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1));
1250 // Wait for the 2 updates.
1251 listener.waitForChangeEvents(TestModel.OUTER_LIST_PATH, listPath);
1252 listenerReg.close();
1254 IntegrationTestKit.verifyShardState(dataStore, "test-1",
1255 state -> assertEquals("getTreeChangeListenerActors", 0,
1256 state.getTreeChangeListenerActors().size()));
1258 testWriteTransaction(dataStore,
1259 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1260 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build(),
1261 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2));
1263 listener.expectNoMoreChanges("Received unexpected change after close");
1270 public void testRestoreFromDatastoreSnapshot() throws Exception {
1271 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1273 final String name = "transactionIntegrationTest";
1275 final ContainerNode carsNode = CarsModel.newCarsNode(
1276 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", BigInteger.valueOf(20000L)),
1277 CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000L))));
1279 DataTree dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
1280 dataTree.setSchemaContext(SchemaContextHelper.full());
1281 AbstractShardTest.writeToStore(dataTree, CarsModel.BASE_PATH, carsNode);
1282 NormalizedNode<?, ?> root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.EMPTY);
1284 final Snapshot carsSnapshot = Snapshot.create(
1285 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(root)),
1286 Collections.emptyList(), 2, 1, 2, 1, 1, "member-1", null);
1288 dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
1289 dataTree.setSchemaContext(SchemaContextHelper.full());
1291 final NormalizedNode<?, ?> peopleNode = PeopleModel.create();
1292 AbstractShardTest.writeToStore(dataTree, PeopleModel.BASE_PATH, peopleNode);
1294 root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.EMPTY);
1296 final Snapshot peopleSnapshot = Snapshot.create(
1297 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(root)),
1298 Collections.emptyList(), 2, 1, 2, 1, 1, "member-1", null);
1300 restoreFromSnapshot = new DatastoreSnapshot(name, null, Arrays.asList(
1301 new DatastoreSnapshot.ShardSnapshot("cars", carsSnapshot),
1302 new DatastoreSnapshot.ShardSnapshot("people", peopleSnapshot)));
1304 try (AbstractDataStore dataStore = setupAbstractDataStore(
1305 testParameter, name, "module-shards-member1.conf", true, "cars", "people")) {
1307 final DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
1310 Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1311 assertEquals("isPresent", true, optional.isPresent());
1312 assertEquals("Data node", carsNode, optional.get());
1314 optional = readTx.read(PeopleModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1315 assertEquals("isPresent", true, optional.isPresent());
1316 assertEquals("Data node", peopleNode, optional.get());