2 * Copyright (c) 2014, 2015 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.ByteArrayOutputStream;
34 import java.io.DataOutputStream;
35 import java.io.IOException;
36 import java.io.ObjectOutputStream;
37 import java.math.BigInteger;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.Collection;
41 import java.util.Collections;
42 import java.util.List;
43 import java.util.concurrent.CountDownLatch;
44 import java.util.concurrent.ExecutionException;
45 import java.util.concurrent.TimeUnit;
46 import java.util.concurrent.atomic.AtomicReference;
47 import org.junit.AfterClass;
48 import org.junit.BeforeClass;
49 import org.junit.Test;
50 import org.mockito.Mockito;
51 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
52 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
53 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
54 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
55 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
56 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
57 import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
58 import org.opendaylight.controller.cluster.datastore.persisted.PayloadVersion;
59 import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
60 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
61 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
62 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
63 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
64 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
65 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
66 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
67 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
68 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
69 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
70 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
71 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
72 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainClosedException;
73 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
74 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
75 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
76 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
77 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
78 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
79 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
80 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
81 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
82 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
83 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
84 import org.opendaylight.yangtools.concepts.ListenerRegistration;
85 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
86 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
87 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
88 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
89 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
90 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
91 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
92 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
93 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
94 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
96 public class DistributedDataStoreIntegrationTest {
98 private static ActorSystem system;
100 private final DatastoreContext.Builder datastoreContextBuilder = DatastoreContext.newBuilder()
101 .shardHeartbeatIntervalInMillis(100);
104 public static void setUpClass() throws IOException {
105 system = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
106 Address member1Address = AddressFromURIString.parse("akka://cluster-test@127.0.0.1:2558");
107 Cluster.get(system).join(member1Address);
111 public static void tearDownClass() throws IOException {
112 JavaTestKit.shutdownActorSystem(system);
116 protected ActorSystem getSystem() {
121 public void testWriteTransactionWithSingleShard() throws Exception {
122 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
124 try (AbstractDataStore dataStore = setupDistributedDataStore("transactionIntegrationTest",
127 testWriteTransaction(dataStore, TestModel.TEST_PATH,
128 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
130 testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
131 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
138 public void testWriteTransactionWithMultipleShards() throws Exception {
139 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
141 try (AbstractDataStore dataStore = setupDistributedDataStore(
142 "testWriteTransactionWithMultipleShards", "cars-1", "people-1")) {
144 DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
145 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
147 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
148 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
150 doCommit(writeTx.ready());
152 writeTx = dataStore.newWriteOnlyTransaction();
154 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
155 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
157 doCommit(writeTx.ready());
159 writeTx = dataStore.newWriteOnlyTransaction();
161 MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
162 YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
163 writeTx.write(carPath, car);
165 MapEntryNode person = PeopleModel.newPersonEntry("jack");
166 YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
167 writeTx.write(personPath, person);
169 doCommit(writeTx.ready());
171 // Verify the data in the store
173 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
175 Optional<NormalizedNode<?, ?>> optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
176 assertEquals("isPresent", true, optional.isPresent());
177 assertEquals("Data node", car, optional.get());
179 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
180 assertEquals("isPresent", true, optional.isPresent());
181 assertEquals("Data node", person, optional.get());
188 public void testReadWriteTransactionWithSingleShard() throws Exception {
189 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
191 try (AbstractDataStore dataStore = setupDistributedDataStore(
192 "testReadWriteTransactionWithSingleShard", "test-1")) {
194 // 1. Create a read-write Tx
196 DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
197 assertNotNull("newReadWriteTransaction returned null", readWriteTx);
199 // 2. Write some data
201 YangInstanceIdentifier nodePath = TestModel.TEST_PATH;
202 NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
203 readWriteTx.write(nodePath, nodeToWrite);
205 // 3. Read the data from Tx
207 Boolean exists = readWriteTx.exists(nodePath).checkedGet(5, TimeUnit.SECONDS);
208 assertEquals("exists", true, exists);
210 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(nodePath).get(5, TimeUnit.SECONDS);
211 assertEquals("isPresent", true, optional.isPresent());
212 assertEquals("Data node", nodeToWrite, optional.get());
214 // 4. Ready the Tx for commit
216 DOMStoreThreePhaseCommitCohort cohort = readWriteTx.ready();
222 // 6. Verify the data in the store
224 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
226 optional = readTx.read(nodePath).get(5, TimeUnit.SECONDS);
227 assertEquals("isPresent", true, optional.isPresent());
228 assertEquals("Data node", nodeToWrite, optional.get());
235 public void testReadWriteTransactionWithMultipleShards() throws Exception {
236 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
238 try (AbstractDataStore dataStore = setupDistributedDataStore(
239 "testReadWriteTransactionWithMultipleShards", "cars-1", "people-1")) {
241 DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
242 assertNotNull("newReadWriteTransaction returned null", readWriteTx);
244 readWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
245 readWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
247 doCommit(readWriteTx.ready());
249 readWriteTx = dataStore.newReadWriteTransaction();
251 readWriteTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
252 readWriteTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
254 doCommit(readWriteTx.ready());
256 readWriteTx = dataStore.newReadWriteTransaction();
258 MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
259 YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
260 readWriteTx.write(carPath, car);
262 MapEntryNode person = PeopleModel.newPersonEntry("jack");
263 YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
264 readWriteTx.write(personPath, person);
266 Boolean exists = readWriteTx.exists(carPath).checkedGet(5, TimeUnit.SECONDS);
267 assertEquals("exists", true, exists);
269 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
270 assertEquals("isPresent", true, optional.isPresent());
271 assertEquals("Data node", car, optional.get());
273 doCommit(readWriteTx.ready());
275 // Verify the data in the store
277 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
279 optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
280 assertEquals("isPresent", true, optional.isPresent());
281 assertEquals("Data node", car, optional.get());
283 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
284 assertEquals("isPresent", true, optional.isPresent());
285 assertEquals("Data node", person, optional.get());
293 public void testSingleTransactionsWritesInQuickSuccession() throws Exception {
294 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
296 try (AbstractDataStore dataStore = setupDistributedDataStore(
297 "testSingleTransactionsWritesInQuickSuccession", "cars-1")) {
299 DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
301 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
302 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
303 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
304 doCommit(writeTx.ready());
306 writeTx = txChain.newWriteOnlyTransaction();
309 for (int i = 0; i < numCars; i++) {
310 writeTx.write(CarsModel.newCarPath("car" + i),
311 CarsModel.newCarEntry("car" + i, BigInteger.valueOf(20000)));
314 doCommit(writeTx.ready());
316 Optional<NormalizedNode<?, ?>> optional = txChain.newReadOnlyTransaction()
317 .read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
318 assertEquals("isPresent", true, optional.isPresent());
319 assertEquals("# cars", numCars, ((Collection<?>) optional.get().getValue()).size());
325 @SuppressWarnings("checkstyle:IllegalCatch")
326 private void testTransactionWritesWithShardNotInitiallyReady(final String testName, final boolean writeOnly)
328 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
330 String shardName = "test-1";
332 // Setup the InMemoryJournal to block shard recovery to ensure
334 // initialized until we create and submit the write the Tx.
335 String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
336 CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
337 InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
339 try (AbstractDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
341 // Create the write Tx
343 final DOMStoreWriteTransaction writeTx = writeOnly ? dataStore.newWriteOnlyTransaction()
344 : dataStore.newReadWriteTransaction();
345 assertNotNull("newReadWriteTransaction returned null", writeTx);
347 // Do some modification operations and ready the Tx on a
350 final YangInstanceIdentifier listEntryPath = YangInstanceIdentifier
351 .builder(TestModel.OUTER_LIST_PATH)
352 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build();
354 final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
355 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
356 final CountDownLatch txReady = new CountDownLatch(1);
357 Thread txThread = new Thread() {
361 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
363 writeTx.merge(TestModel.OUTER_LIST_PATH,
364 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
366 writeTx.write(listEntryPath,
367 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1));
369 writeTx.delete(listEntryPath);
371 txCohort.set(writeTx.ready());
372 } catch (Exception e) {
383 // Wait for the Tx operations to complete.
385 boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
386 if (caughtEx.get() != null) {
387 throw caughtEx.get();
390 assertEquals("Tx ready", true, done);
392 // At this point the Tx operations should be waiting for the
393 // shard to initialize so
394 // trigger the latch to let the shard recovery to continue.
396 blockRecoveryLatch.countDown();
398 // Wait for the Tx commit to complete.
400 doCommit(txCohort.get());
402 // Verify the data in the store
404 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
406 Optional<NormalizedNode<?, ?>> optional = readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
407 assertEquals("isPresent", true, optional.isPresent());
409 optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
410 assertEquals("isPresent", true, optional.isPresent());
412 optional = readTx.read(listEntryPath).get(5, TimeUnit.SECONDS);
413 assertEquals("isPresent", false, optional.isPresent());
420 public void testWriteOnlyTransactionWithShardNotInitiallyReady() throws Exception {
421 datastoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
422 testTransactionWritesWithShardNotInitiallyReady("testWriteOnlyTransactionWithShardNotInitiallyReady", true);
426 public void testReadWriteTransactionWithShardNotInitiallyReady() throws Exception {
427 testTransactionWritesWithShardNotInitiallyReady("testReadWriteTransactionWithShardNotInitiallyReady", false);
431 @SuppressWarnings("checkstyle:IllegalCatch")
432 public void testTransactionReadsWithShardNotInitiallyReady() throws Exception {
433 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
435 String testName = "testTransactionReadsWithShardNotInitiallyReady";
436 String shardName = "test-1";
438 // Setup the InMemoryJournal to block shard recovery to ensure
440 // initialized until we create the Tx.
441 String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
442 CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
443 InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
445 try (AbstractDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
447 // Create the read-write Tx
449 final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
450 assertNotNull("newReadWriteTransaction returned null", readWriteTx);
452 // Do some reads on the Tx on a separate thread.
454 final AtomicReference<CheckedFuture<Boolean, ReadFailedException>> txExistsFuture =
455 new AtomicReference<>();
456 final AtomicReference<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>>
457 txReadFuture = new AtomicReference<>();
458 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
459 final CountDownLatch txReadsDone = new CountDownLatch(1);
460 Thread txThread = new Thread() {
464 readWriteTx.write(TestModel.TEST_PATH,
465 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
467 txExistsFuture.set(readWriteTx.exists(TestModel.TEST_PATH));
469 txReadFuture.set(readWriteTx.read(TestModel.TEST_PATH));
470 } catch (Exception e) {
474 txReadsDone.countDown();
481 // Wait for the Tx operations to complete.
483 boolean done = Uninterruptibles.awaitUninterruptibly(txReadsDone, 5, TimeUnit.SECONDS);
484 if (caughtEx.get() != null) {
485 throw caughtEx.get();
488 assertEquals("Tx reads done", true, done);
490 // At this point the Tx operations should be waiting for the
491 // shard to initialize so
492 // trigger the latch to let the shard recovery to continue.
494 blockRecoveryLatch.countDown();
496 // Wait for the reads to complete and verify.
498 assertEquals("exists", true, txExistsFuture.get().checkedGet(5, TimeUnit.SECONDS));
499 assertEquals("read", true, txReadFuture.get().checkedGet(5, TimeUnit.SECONDS).isPresent());
507 @Test(expected = NotInitializedException.class)
508 @SuppressWarnings("checkstyle:IllegalCatch")
509 public void testTransactionCommitFailureWithShardNotInitialized() throws Exception {
510 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
512 String testName = "testTransactionCommitFailureWithShardNotInitialized";
513 String shardName = "test-1";
515 // Set the shard initialization timeout low for the test.
517 datastoreContextBuilder.shardInitializationTimeout(300, TimeUnit.MILLISECONDS);
519 // Setup the InMemoryJournal to block shard recovery
522 String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
523 CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
524 InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
526 InMemoryJournal.addEntry(persistentID, 1, "Dummy data so akka will read from persistence");
528 try (AbstractDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
530 // Create the write Tx
532 final DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
533 assertNotNull("newReadWriteTransaction returned null", writeTx);
535 // Do some modifications and ready the Tx on a separate
538 final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
539 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
540 final CountDownLatch txReady = new CountDownLatch(1);
541 Thread txThread = new Thread() {
545 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
547 txCohort.set(writeTx.ready());
548 } catch (Exception e) {
559 // Wait for the Tx operations to complete.
561 boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
562 if (caughtEx.get() != null) {
563 throw caughtEx.get();
566 assertEquals("Tx ready", true, done);
568 // Wait for the commit to complete. Since the shard never
569 // initialized, the Tx should
570 // have timed out and throw an appropriate exception cause.
573 txCohort.get().canCommit().get(5, TimeUnit.SECONDS);
574 } catch (ExecutionException e) {
575 Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
576 Throwables.propagate(e.getCause());
578 blockRecoveryLatch.countDown();
585 @Test(expected = NotInitializedException.class)
586 @SuppressWarnings("checkstyle:IllegalCatch")
587 public void testTransactionReadFailureWithShardNotInitialized() throws Exception {
588 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
590 String testName = "testTransactionReadFailureWithShardNotInitialized";
591 String shardName = "test-1";
593 // Set the shard initialization timeout low for the test.
595 datastoreContextBuilder.shardInitializationTimeout(300, TimeUnit.MILLISECONDS);
597 // Setup the InMemoryJournal to block shard recovery
600 String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
601 CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
602 InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
604 InMemoryJournal.addEntry(persistentID, 1, "Dummy data so akka will read from persistence");
606 try (AbstractDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
608 // Create the read-write Tx
610 final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
611 assertNotNull("newReadWriteTransaction returned null", readWriteTx);
613 // Do a read on the Tx on a separate thread.
615 final AtomicReference<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>>
616 txReadFuture = new AtomicReference<>();
617 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
618 final CountDownLatch txReadDone = new CountDownLatch(1);
619 Thread txThread = new Thread() {
623 readWriteTx.write(TestModel.TEST_PATH,
624 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
626 txReadFuture.set(readWriteTx.read(TestModel.TEST_PATH));
629 } catch (Exception e) {
633 txReadDone.countDown();
640 // Wait for the Tx operations to complete.
642 boolean done = Uninterruptibles.awaitUninterruptibly(txReadDone, 5, TimeUnit.SECONDS);
643 if (caughtEx.get() != null) {
644 throw caughtEx.get();
647 assertEquals("Tx read done", true, done);
649 // Wait for the read to complete. Since the shard never
650 // initialized, the Tx should
651 // have timed out and throw an appropriate exception cause.
654 txReadFuture.get().checkedGet(5, TimeUnit.SECONDS);
655 } catch (ReadFailedException e) {
656 Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
657 Throwables.propagate(e.getCause());
659 blockRecoveryLatch.countDown();
666 @SuppressWarnings("checkstyle:IllegalCatch")
667 private void testTransactionCommitFailureWithNoShardLeader(final boolean writeOnly, final String testName)
669 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
671 String shardName = "default";
673 // We don't want the shard to become the leader so prevent shard
675 datastoreContextBuilder.customRaftPolicyImplementation(
676 "org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy");
678 // The ShardManager uses the election timeout for FindPrimary so
679 // reset it low so it will timeout quickly.
680 datastoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(1)
681 .shardInitializationTimeout(200, TimeUnit.MILLISECONDS);
683 try (AbstractDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
685 Object result = dataStore.getActorContext().executeOperation(
686 dataStore.getActorContext().getShardManager(), new FindLocalShard(shardName, true));
687 assertTrue("Expected LocalShardFound. Actual: " + result, result instanceof LocalShardFound);
689 // Create the write Tx.
691 try (DOMStoreWriteTransaction writeTx = writeOnly ? dataStore.newWriteOnlyTransaction()
692 : dataStore.newReadWriteTransaction()) {
693 assertNotNull("newReadWriteTransaction returned null", writeTx);
695 // Do some modifications and ready the Tx on a separate
698 final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
699 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
700 final CountDownLatch txReady = new CountDownLatch(1);
701 Thread txThread = new Thread() {
705 writeTx.write(TestModel.JUNK_PATH,
706 ImmutableNodes.containerNode(TestModel.JUNK_QNAME));
708 txCohort.set(writeTx.ready());
709 } catch (Exception e) {
720 // Wait for the Tx operations to complete.
722 boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
723 if (caughtEx.get() != null) {
724 throw caughtEx.get();
727 assertEquals("Tx ready", true, done);
729 // Wait for the commit to complete. Since no shard
730 // leader was elected in time, the Tx
731 // should have timed out and throw an appropriate
735 txCohort.get().canCommit().get(5, TimeUnit.SECONDS);
736 } catch (ExecutionException e) {
737 Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
738 Throwables.propagate(e.getCause());
746 @Test(expected = NoShardLeaderException.class)
747 public void testWriteOnlyTransactionCommitFailureWithNoShardLeader() throws Exception {
748 datastoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
749 testTransactionCommitFailureWithNoShardLeader(true, "testWriteOnlyTransactionCommitFailureWithNoShardLeader");
752 @Test(expected = NoShardLeaderException.class)
753 public void testReadWriteTransactionCommitFailureWithNoShardLeader() throws Exception {
754 testTransactionCommitFailureWithNoShardLeader(false, "testReadWriteTransactionCommitFailureWithNoShardLeader");
758 public void testTransactionAbort() throws Exception {
759 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
761 try (AbstractDataStore dataStore = setupDistributedDataStore("transactionAbortIntegrationTest",
764 DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
765 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
767 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
769 DOMStoreThreePhaseCommitCohort cohort = writeTx.ready();
771 cohort.canCommit().get(5, TimeUnit.SECONDS);
773 cohort.abort().get(5, TimeUnit.SECONDS);
775 testWriteTransaction(dataStore, TestModel.TEST_PATH,
776 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
783 @SuppressWarnings("checkstyle:IllegalCatch")
784 public void testTransactionChainWithSingleShard() throws Exception {
785 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
787 try (AbstractDataStore dataStore = setupDistributedDataStore("testTransactionChainWithSingleShard",
790 // 1. Create a Tx chain and write-only Tx
792 DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
794 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
795 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
797 // 2. Write some data
799 NormalizedNode<?, ?> testNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
800 writeTx.write(TestModel.TEST_PATH, testNode);
802 // 3. Ready the Tx for commit
804 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
806 // 4. Commit the Tx on another thread that first waits for
807 // the second read Tx.
809 final CountDownLatch continueCommit1 = new CountDownLatch(1);
810 final CountDownLatch commit1Done = new CountDownLatch(1);
811 final AtomicReference<Exception> commit1Error = new AtomicReference<>();
816 continueCommit1.await();
818 } catch (Exception e) {
821 commit1Done.countDown();
826 // 5. Create a new read Tx from the chain to read and verify
827 // the data from the first
828 // Tx is visible after being readied.
830 DOMStoreReadTransaction readTx = txChain.newReadOnlyTransaction();
831 Optional<NormalizedNode<?, ?>> optional = readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
832 assertEquals("isPresent", true, optional.isPresent());
833 assertEquals("Data node", testNode, optional.get());
835 // 6. Create a new RW Tx from the chain, write more data,
838 DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
839 MapNode outerNode = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
840 rwTx.write(TestModel.OUTER_LIST_PATH, outerNode);
842 final DOMStoreThreePhaseCommitCohort cohort2 = rwTx.ready();
844 // 7. Create a new read Tx from the chain to read the data
845 // from the last RW Tx to
846 // verify it is visible.
848 readTx = txChain.newReadWriteTransaction();
849 optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
850 assertEquals("isPresent", true, optional.isPresent());
851 assertEquals("Data node", outerNode, optional.get());
853 // 8. Wait for the 2 commits to complete and close the
856 continueCommit1.countDown();
857 Uninterruptibles.awaitUninterruptibly(commit1Done, 5, TimeUnit.SECONDS);
859 if (commit1Error.get() != null) {
860 throw commit1Error.get();
867 // 9. Create a new read Tx from the data store and verify
870 readTx = dataStore.newReadOnlyTransaction();
871 optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
872 assertEquals("isPresent", true, optional.isPresent());
873 assertEquals("Data node", outerNode, optional.get());
880 public void testTransactionChainWithMultipleShards() throws Exception {
881 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
883 try (AbstractDataStore dataStore = setupDistributedDataStore(
884 "testTransactionChainWithMultipleShards", "cars-1", "people-1")) {
886 DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
888 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
889 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
891 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
892 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
894 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
895 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
897 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
899 DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
901 MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
902 YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
903 readWriteTx.write(carPath, car);
905 MapEntryNode person = PeopleModel.newPersonEntry("jack");
906 YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
907 readWriteTx.merge(personPath, person);
909 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
910 assertEquals("isPresent", true, optional.isPresent());
911 assertEquals("Data node", car, optional.get());
913 optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
914 assertEquals("isPresent", true, optional.isPresent());
915 assertEquals("Data node", person, optional.get());
917 DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
919 writeTx = txChain.newWriteOnlyTransaction();
921 writeTx.delete(carPath);
923 DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
925 ListenableFuture<Boolean> canCommit1 = cohort1.canCommit();
926 ListenableFuture<Boolean> canCommit2 = cohort2.canCommit();
928 doCommit(canCommit1, cohort1);
929 doCommit(canCommit2, cohort2);
934 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
936 optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
937 assertEquals("isPresent", false, optional.isPresent());
939 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
940 assertEquals("isPresent", true, optional.isPresent());
941 assertEquals("Data node", person, optional.get());
948 public void testCreateChainedTransactionsInQuickSuccession() throws Exception {
949 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
951 try (AbstractDataStore dataStore = setupDistributedDataStore(
952 "testCreateChainedTransactionsInQuickSuccession", "cars-1")) {
954 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
955 ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
956 .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
957 MoreExecutors.directExecutor());
959 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
960 DOMTransactionChain txChain = broker.createTransactionChain(listener);
962 List<CheckedFuture<Void, TransactionCommitFailedException>> futures = new ArrayList<>();
964 DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
965 writeTx.put(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, CarsModel.emptyContainer());
966 writeTx.put(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
967 futures.add(writeTx.submit());
970 for (int i = 0; i < numCars; i++) {
971 DOMDataReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
973 rwTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.newCarPath("car" + i),
974 CarsModel.newCarEntry("car" + i, BigInteger.valueOf(20000)));
976 futures.add(rwTx.submit());
979 for (CheckedFuture<Void, TransactionCommitFailedException> f : futures) {
983 Optional<NormalizedNode<?, ?>> optional = txChain.newReadOnlyTransaction()
984 .read(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
985 assertEquals("isPresent", true, optional.isPresent());
986 assertEquals("# cars", numCars, ((Collection<?>) optional.get().getValue()).size());
997 public void testCreateChainedTransactionAfterEmptyTxReadied() throws Exception {
998 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1000 try (AbstractDataStore dataStore = setupDistributedDataStore(
1001 "testCreateChainedTransactionAfterEmptyTxReadied", "test-1")) {
1003 DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
1005 DOMStoreReadWriteTransaction rwTx1 = txChain.newReadWriteTransaction();
1009 DOMStoreReadWriteTransaction rwTx2 = txChain.newReadWriteTransaction();
1011 Optional<NormalizedNode<?, ?>> optional = rwTx2.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
1012 assertEquals("isPresent", false, optional.isPresent());
1021 public void testCreateChainedTransactionWhenPreviousNotReady() throws Exception {
1022 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1024 try (AbstractDataStore dataStore = setupDistributedDataStore(
1025 "testCreateChainedTransactionWhenPreviousNotReady", "test-1")) {
1027 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
1029 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
1030 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
1032 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1034 // Try to create another Tx of each type - each should fail
1035 // b/c the previous Tx wasn't
1038 assertExceptionOnTxChainCreates(txChain, IllegalStateException.class);
1045 public void testCreateChainedTransactionAfterClose() throws Exception {
1046 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1048 try (AbstractDataStore dataStore = setupDistributedDataStore(
1049 "testCreateChainedTransactionAfterClose", "test-1")) {
1051 DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
1055 // Try to create another Tx of each type - should fail b/c
1056 // the previous Tx was closed.
1058 assertExceptionOnTxChainCreates(txChain, TransactionChainClosedException.class);
1065 public void testChainWithReadOnlyTxAfterPreviousReady() throws Exception {
1066 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1068 try (AbstractDataStore dataStore = setupDistributedDataStore(
1069 "testChainWithReadOnlyTxAfterPreviousReady", "test-1")) {
1071 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
1073 // Create a write tx and submit.
1075 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
1076 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1077 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
1079 // Create read-only tx's and issue a read.
1081 CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture1 = txChain
1082 .newReadOnlyTransaction().read(TestModel.TEST_PATH);
1084 CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture2 = txChain
1085 .newReadOnlyTransaction().read(TestModel.TEST_PATH);
1087 // Create another write tx and issue the write.
1089 DOMStoreWriteTransaction writeTx2 = txChain.newWriteOnlyTransaction();
1090 writeTx2.write(TestModel.OUTER_LIST_PATH,
1091 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1093 // Ensure the reads succeed.
1095 assertEquals("isPresent", true, readFuture1.checkedGet(5, TimeUnit.SECONDS).isPresent());
1096 assertEquals("isPresent", true, readFuture2.checkedGet(5, TimeUnit.SECONDS).isPresent());
1098 // Ensure the writes succeed.
1100 DOMStoreThreePhaseCommitCohort cohort2 = writeTx2.ready();
1105 assertEquals("isPresent", true, txChain.newReadOnlyTransaction().read(TestModel.OUTER_LIST_PATH)
1106 .checkedGet(5, TimeUnit.SECONDS).isPresent());
1113 public void testChainedTransactionFailureWithSingleShard() throws Exception {
1114 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1116 try (AbstractDataStore dataStore = setupDistributedDataStore(
1117 "testChainedTransactionFailureWithSingleShard", "cars-1")) {
1119 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
1120 ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
1121 .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
1122 MoreExecutors.directExecutor());
1124 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
1125 DOMTransactionChain txChain = broker.createTransactionChain(listener);
1127 DOMDataReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
1129 ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
1130 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
1131 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
1133 rwTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
1136 rwTx.submit().checkedGet(5, TimeUnit.SECONDS);
1137 fail("Expected TransactionCommitFailedException");
1138 } catch (TransactionCommitFailedException e) {
1142 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(rwTx),
1143 any(Throwable.class));
1153 public void testChainedTransactionFailureWithMultipleShards() throws Exception {
1154 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1156 try (AbstractDataStore dataStore = setupDistributedDataStore(
1157 "testChainedTransactionFailureWithMultipleShards", "cars-1", "people-1")) {
1159 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
1160 ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
1161 .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
1162 MoreExecutors.directExecutor());
1164 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
1165 DOMTransactionChain txChain = broker.createTransactionChain(listener);
1167 DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
1169 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH,
1170 PeopleModel.emptyContainer());
1172 ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
1173 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
1174 .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
1176 // Note that merge will validate the data and fail but put
1177 // succeeds b/c deep validation is not
1178 // done for put for performance reasons.
1179 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
1182 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
1183 fail("Expected TransactionCommitFailedException");
1184 } catch (TransactionCommitFailedException e) {
1188 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx),
1189 any(Throwable.class));
1199 public void testChangeListenerRegistration() throws Exception {
1200 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1202 try (AbstractDataStore dataStore = setupDistributedDataStore("testChangeListenerRegistration",
1205 testWriteTransaction(dataStore, TestModel.TEST_PATH,
1206 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1208 MockDataChangeListener listener = new MockDataChangeListener(1);
1210 ListenerRegistration<MockDataChangeListener> listenerReg = dataStore
1211 .registerChangeListener(TestModel.TEST_PATH, listener, DataChangeScope.SUBTREE);
1213 assertNotNull("registerChangeListener returned null", listenerReg);
1215 // Wait for the initial notification
1217 listener.waitForChangeEvents(TestModel.TEST_PATH);
1223 testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
1224 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1226 YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1227 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build();
1228 testWriteTransaction(dataStore, listPath,
1229 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1));
1231 // Wait for the 2 updates.
1233 listener.waitForChangeEvents(TestModel.OUTER_LIST_PATH, listPath);
1235 listenerReg.close();
1237 testWriteTransaction(dataStore,
1238 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
1239 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build(),
1240 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2));
1242 listener.expectNoMoreChanges("Received unexpected change after close");
1249 public void testRestoreFromDatastoreSnapshot() throws Exception {
1250 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1252 final String name = "transactionIntegrationTest";
1254 ContainerNode carsNode = CarsModel.newCarsNode(
1255 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", BigInteger.valueOf(20000L)),
1256 CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000L))));
1258 DataTree dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
1259 dataTree.setSchemaContext(SchemaContextHelper.full());
1260 AbstractShardTest.writeToStore(dataTree, CarsModel.BASE_PATH, carsNode);
1261 NormalizedNode<?, ?> root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.EMPTY);
1263 final Snapshot carsSnapshot = Snapshot.create(
1264 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(root)),
1265 Collections.<ReplicatedLogEntry>emptyList(), 2, 1, 2, 1, 1, "member-1", null);
1267 NormalizedNode<?, ?> peopleNode = PeopleModel.create();
1268 dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
1269 dataTree.setSchemaContext(SchemaContextHelper.full());
1270 AbstractShardTest.writeToStore(dataTree, PeopleModel.BASE_PATH, peopleNode);
1271 root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.EMPTY);
1273 Snapshot peopleSnapshot = Snapshot.create(
1274 new ShardSnapshotState(new MetadataShardDataTreeSnapshot(root)),
1275 Collections.<ReplicatedLogEntry>emptyList(), 2, 1, 2, 1, 1, "member-1", null);
1277 restoreFromSnapshot = new DatastoreSnapshot(name, null, Arrays.asList(
1278 new DatastoreSnapshot.ShardSnapshot("cars", carsSnapshot),
1279 new DatastoreSnapshot.ShardSnapshot("people", peopleSnapshot)));
1281 try (AbstractDataStore dataStore = setupDistributedDataStore(name, "module-shards-member1.conf",
1282 true, "cars", "people")) {
1284 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
1286 Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1287 assertEquals("isPresent", true, optional.isPresent());
1288 assertEquals("Data node", carsNode, optional.get());
1290 optional = readTx.read(PeopleModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1291 assertEquals("isPresent", true, optional.isPresent());
1292 assertEquals("Data node", peopleNode, optional.get());
1300 public void testRecoveryFromPreCarbonSnapshot() throws Exception {
1301 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
1303 final String name = "testRecoveryFromPreCarbonSnapshot";
1305 ContainerNode carsNode = CarsModel.newCarsNode(
1306 CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", BigInteger.valueOf(20000L)),
1307 CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000L))));
1309 DataTree dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
1310 dataTree.setSchemaContext(SchemaContextHelper.full());
1311 AbstractShardTest.writeToStore(dataTree, CarsModel.BASE_PATH, carsNode);
1312 NormalizedNode<?, ?> root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.EMPTY);
1314 MetadataShardDataTreeSnapshot shardSnapshot = new MetadataShardDataTreeSnapshot(root);
1315 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
1316 try (final DataOutputStream dos = new DataOutputStream(bos)) {
1317 PayloadVersion.BORON.writeTo(dos);
1318 try (ObjectOutputStream oos = new ObjectOutputStream(dos)) {
1319 oos.writeObject(shardSnapshot);
1323 final org.opendaylight.controller.cluster.raft.Snapshot snapshot =
1324 org.opendaylight.controller.cluster.raft.Snapshot.create(bos.toByteArray(),
1325 Collections.<ReplicatedLogEntry>emptyList(), 2, 1, 2, 1, 1, "member-1", null);
1327 InMemorySnapshotStore.addSnapshot("member-1-shard-cars-" + name, snapshot);
1329 try (AbstractDataStore dataStore = setupDistributedDataStore(name, "module-shards-member1.conf",
1332 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
1334 Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1335 assertEquals("isPresent", true, optional.isPresent());
1336 assertEquals("Data node", carsNode, optional.get());