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;
19 import akka.actor.ActorSystem;
20 import akka.actor.Address;
21 import akka.actor.AddressFromURIString;
22 import akka.cluster.Cluster;
23 import akka.testkit.JavaTestKit;
24 import com.google.common.base.Optional;
25 import com.google.common.collect.ImmutableMap;
26 import com.google.common.util.concurrent.CheckedFuture;
27 import com.google.common.util.concurrent.ListenableFuture;
28 import com.google.common.util.concurrent.MoreExecutors;
29 import com.google.common.util.concurrent.Uninterruptibles;
30 import com.typesafe.config.ConfigFactory;
31 import java.io.IOException;
32 import java.math.BigInteger;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.List;
38 import java.util.concurrent.CountDownLatch;
39 import java.util.concurrent.ExecutionException;
40 import java.util.concurrent.TimeUnit;
41 import java.util.concurrent.atomic.AtomicReference;
42 import org.junit.AfterClass;
43 import org.junit.BeforeClass;
44 import org.junit.Test;
45 import org.mockito.Mockito;
46 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
47 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
48 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
49 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
50 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
51 import org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener;
52 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
53 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
54 import org.opendaylight.controller.cluster.raft.Snapshot;
55 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
56 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
57 import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
58 import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
59 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
60 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
61 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
62 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
63 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainClosedException;
64 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
65 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
66 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
67 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
68 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
69 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
70 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
71 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
72 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
73 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
74 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
75 import org.opendaylight.yangtools.concepts.ListenerRegistration;
76 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
77 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
80 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
81 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
82 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
84 public class DistributedDataStoreIntegrationTest {
86 private static ActorSystem system;
88 private final DatastoreContext.Builder datastoreContextBuilder =
89 DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100);
92 public static void setUpClass() throws IOException {
93 system = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
94 Address member1Address = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558");
95 Cluster.get(system).join(member1Address);
99 public static void tearDownClass() throws IOException {
100 JavaTestKit.shutdownActorSystem(system);
104 protected ActorSystem getSystem() {
109 public void testWriteTransactionWithSingleShard() throws Exception{
110 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
111 DistributedDataStore dataStore =
112 setupDistributedDataStore("transactionIntegrationTest", "test-1");
114 testWriteTransaction(dataStore, TestModel.TEST_PATH,
115 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
117 testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
118 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
125 public void testWriteTransactionWithMultipleShards() throws Exception{
126 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
127 DistributedDataStore dataStore =
128 setupDistributedDataStore("testWriteTransactionWithMultipleShards", "cars-1", "people-1");
130 DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
131 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
133 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
134 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
136 doCommit(writeTx.ready());
138 writeTx = dataStore.newWriteOnlyTransaction();
140 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
141 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
143 doCommit(writeTx.ready());
145 writeTx = dataStore.newWriteOnlyTransaction();
147 MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
148 YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
149 writeTx.write(carPath, car);
151 MapEntryNode person = PeopleModel.newPersonEntry("jack");
152 YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
153 writeTx.write(personPath, person);
155 doCommit(writeTx.ready());
157 // Verify the data in the store
159 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
161 Optional<NormalizedNode<?, ?>> optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
162 assertEquals("isPresent", true, optional.isPresent());
163 assertEquals("Data node", car, optional.get());
165 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
166 assertEquals("isPresent", true, optional.isPresent());
167 assertEquals("Data node", person, optional.get());
174 public void testReadWriteTransactionWithSingleShard() throws Exception{
175 System.setProperty("shard.persistent", "true");
176 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
177 DistributedDataStore dataStore =
178 setupDistributedDataStore("testReadWriteTransactionWithSingleShard", "test-1");
180 // 1. Create a read-write Tx
182 DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
183 assertNotNull("newReadWriteTransaction returned null", readWriteTx);
185 // 2. Write some data
187 YangInstanceIdentifier nodePath = TestModel.TEST_PATH;
188 NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
189 readWriteTx.write(nodePath, nodeToWrite );
191 // 3. Read the data from Tx
193 Boolean exists = readWriteTx.exists(nodePath).checkedGet(5, TimeUnit.SECONDS);
194 assertEquals("exists", true, exists);
196 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(nodePath).get(5, TimeUnit.SECONDS);
197 assertEquals("isPresent", true, optional.isPresent());
198 assertEquals("Data node", nodeToWrite, optional.get());
200 // 4. Ready the Tx for commit
202 DOMStoreThreePhaseCommitCohort cohort = readWriteTx.ready();
208 // 6. Verify the data in the store
210 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
212 optional = readTx.read(nodePath).get(5, TimeUnit.SECONDS);
213 assertEquals("isPresent", true, optional.isPresent());
214 assertEquals("Data node", nodeToWrite, optional.get());
221 public void testReadWriteTransactionWithMultipleShards() throws Exception{
222 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
223 DistributedDataStore dataStore =
224 setupDistributedDataStore("testReadWriteTransactionWithMultipleShards", "cars-1", "people-1");
226 DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
227 assertNotNull("newReadWriteTransaction returned null", readWriteTx);
229 readWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
230 readWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
232 doCommit(readWriteTx.ready());
234 readWriteTx = dataStore.newReadWriteTransaction();
236 readWriteTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
237 readWriteTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
239 doCommit(readWriteTx.ready());
241 readWriteTx = dataStore.newReadWriteTransaction();
243 MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
244 YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
245 readWriteTx.write(carPath, car);
247 MapEntryNode person = PeopleModel.newPersonEntry("jack");
248 YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
249 readWriteTx.write(personPath, person);
251 Boolean exists = readWriteTx.exists(carPath).checkedGet(5, TimeUnit.SECONDS);
252 assertEquals("exists", true, exists);
254 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
255 assertEquals("isPresent", true, optional.isPresent());
256 assertEquals("Data node", car, optional.get());
258 doCommit(readWriteTx.ready());
260 // Verify the data in the store
262 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
264 optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
265 assertEquals("isPresent", true, optional.isPresent());
266 assertEquals("Data node", car, optional.get());
268 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
269 assertEquals("isPresent", true, optional.isPresent());
270 assertEquals("Data node", person, optional.get());
277 public void testSingleTransactionsWritesInQuickSuccession() throws Exception{
278 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
279 DistributedDataStore dataStore = setupDistributedDataStore(
280 "testSingleTransactionsWritesInQuickSuccession", "cars-1");
282 DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
284 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
285 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
286 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
287 doCommit(writeTx.ready());
289 writeTx = txChain.newWriteOnlyTransaction();
292 for(int i = 0; i < nCars; i++) {
293 writeTx.write(CarsModel.newCarPath("car" + i),
294 CarsModel.newCarEntry("car" + i, BigInteger.valueOf(20000)));
297 doCommit(writeTx.ready());
299 Optional<NormalizedNode<?, ?>> optional = txChain.newReadOnlyTransaction().read(
300 CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
301 assertEquals("isPresent", true, optional.isPresent());
302 assertEquals("# cars", nCars, ((Collection<?>)optional.get().getValue()).size());
308 private void testTransactionWritesWithShardNotInitiallyReady(final String testName,
309 final boolean writeOnly) throws Exception {
310 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
311 String shardName = "test-1";
313 // Setup the InMemoryJournal to block shard recovery to ensure the shard isn't
314 // initialized until we create and submit the write the Tx.
315 String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
316 CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
317 InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
319 DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName);
321 // Create the write Tx
323 final DOMStoreWriteTransaction writeTx = writeOnly ? dataStore.newWriteOnlyTransaction() :
324 dataStore.newReadWriteTransaction();
325 assertNotNull("newReadWriteTransaction returned null", writeTx);
327 // Do some modification operations and ready the Tx on a separate thread.
329 final YangInstanceIdentifier listEntryPath = YangInstanceIdentifier.builder(
330 TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME,
331 TestModel.ID_QNAME, 1).build();
333 final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
334 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
335 final CountDownLatch txReady = new CountDownLatch(1);
336 Thread txThread = new Thread() {
340 writeTx.write(TestModel.TEST_PATH,
341 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
343 writeTx.merge(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(
344 TestModel.OUTER_LIST_QNAME).build());
346 writeTx.write(listEntryPath, ImmutableNodes.mapEntry(
347 TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1));
349 writeTx.delete(listEntryPath);
351 txCohort.set(writeTx.ready());
352 } catch(Exception e) {
363 // Wait for the Tx operations to complete.
365 boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
366 if(caughtEx.get() != null) {
367 throw caughtEx.get();
370 assertEquals("Tx ready", true, done);
372 // At this point the Tx operations should be waiting for the shard to initialize so
373 // trigger the latch to let the shard recovery to continue.
375 blockRecoveryLatch.countDown();
377 // Wait for the Tx commit to complete.
379 doCommit(txCohort.get());
381 // Verify the data in the store
383 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
385 Optional<NormalizedNode<?, ?>> optional = readTx.read(TestModel.TEST_PATH).
386 get(5, TimeUnit.SECONDS);
387 assertEquals("isPresent", true, optional.isPresent());
389 optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
390 assertEquals("isPresent", true, optional.isPresent());
392 optional = readTx.read(listEntryPath).get(5, TimeUnit.SECONDS);
393 assertEquals("isPresent", false, optional.isPresent());
400 public void testWriteOnlyTransactionWithShardNotInitiallyReady() throws Exception {
401 datastoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
402 testTransactionWritesWithShardNotInitiallyReady("testWriteOnlyTransactionWithShardNotInitiallyReady", true);
406 public void testReadWriteTransactionWithShardNotInitiallyReady() throws Exception {
407 testTransactionWritesWithShardNotInitiallyReady("testReadWriteTransactionWithShardNotInitiallyReady", false);
411 public void testTransactionReadsWithShardNotInitiallyReady() throws Exception {
412 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
413 String testName = "testTransactionReadsWithShardNotInitiallyReady";
414 String shardName = "test-1";
416 // Setup the InMemoryJournal to block shard recovery to ensure the shard isn't
417 // initialized until we create the Tx.
418 String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
419 CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
420 InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
422 DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName);
424 // Create the read-write Tx
426 final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
427 assertNotNull("newReadWriteTransaction returned null", readWriteTx);
429 // Do some reads on the Tx on a separate thread.
431 final AtomicReference<CheckedFuture<Boolean, ReadFailedException>> txExistsFuture =
432 new AtomicReference<>();
433 final AtomicReference<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>>
434 txReadFuture = new AtomicReference<>();
435 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
436 final CountDownLatch txReadsDone = new CountDownLatch(1);
437 Thread txThread = new Thread() {
441 readWriteTx.write(TestModel.TEST_PATH,
442 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
444 txExistsFuture.set(readWriteTx.exists(TestModel.TEST_PATH));
446 txReadFuture.set(readWriteTx.read(TestModel.TEST_PATH));
447 } catch(Exception e) {
451 txReadsDone.countDown();
458 // Wait for the Tx operations to complete.
460 boolean done = Uninterruptibles.awaitUninterruptibly(txReadsDone, 5, TimeUnit.SECONDS);
461 if(caughtEx.get() != null) {
462 throw caughtEx.get();
465 assertEquals("Tx reads done", true, done);
467 // At this point the Tx operations should be waiting for the shard to initialize so
468 // trigger the latch to let the shard recovery to continue.
470 blockRecoveryLatch.countDown();
472 // Wait for the reads to complete and verify.
474 assertEquals("exists", true, txExistsFuture.get().checkedGet(5, TimeUnit.SECONDS));
475 assertEquals("read", true, txReadFuture.get().checkedGet(5, TimeUnit.SECONDS).isPresent());
483 @Test(expected=NotInitializedException.class)
484 public void testTransactionCommitFailureWithShardNotInitialized() throws Throwable{
485 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
486 String testName = "testTransactionCommitFailureWithShardNotInitialized";
487 String shardName = "test-1";
489 // Set the shard initialization timeout low for the test.
491 datastoreContextBuilder.shardInitializationTimeout(300, TimeUnit.MILLISECONDS);
493 // Setup the InMemoryJournal to block shard recovery indefinitely.
495 String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
496 CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
497 InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
499 DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName);
501 // Create the write Tx
503 final DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
504 assertNotNull("newReadWriteTransaction returned null", writeTx);
506 // Do some modifications and ready the Tx on a separate thread.
508 final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
509 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
510 final CountDownLatch txReady = new CountDownLatch(1);
511 Thread txThread = new Thread() {
515 writeTx.write(TestModel.TEST_PATH,
516 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
518 txCohort.set(writeTx.ready());
519 } catch(Exception e) {
530 // Wait for the Tx operations to complete.
532 boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
533 if(caughtEx.get() != null) {
534 throw caughtEx.get();
537 assertEquals("Tx ready", true, done);
539 // Wait for the commit to complete. Since the shard never initialized, the Tx should
540 // have timed out and throw an appropriate exception cause.
543 txCohort.get().canCommit().get(5, TimeUnit.SECONDS);
544 } catch(ExecutionException e) {
547 blockRecoveryLatch.countDown();
553 @Test(expected=NotInitializedException.class)
554 public void testTransactionReadFailureWithShardNotInitialized() throws Throwable{
555 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
556 String testName = "testTransactionReadFailureWithShardNotInitialized";
557 String shardName = "test-1";
559 // Set the shard initialization timeout low for the test.
561 datastoreContextBuilder.shardInitializationTimeout(300, TimeUnit.MILLISECONDS);
563 // Setup the InMemoryJournal to block shard recovery indefinitely.
565 String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
566 CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
567 InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
569 DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName);
571 // Create the read-write Tx
573 final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
574 assertNotNull("newReadWriteTransaction returned null", readWriteTx);
576 // Do a read on the Tx on a separate thread.
578 final AtomicReference<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>>
579 txReadFuture = new AtomicReference<>();
580 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
581 final CountDownLatch txReadDone = new CountDownLatch(1);
582 Thread txThread = new Thread() {
586 readWriteTx.write(TestModel.TEST_PATH,
587 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
589 txReadFuture.set(readWriteTx.read(TestModel.TEST_PATH));
592 } catch(Exception e) {
596 txReadDone.countDown();
603 // Wait for the Tx operations to complete.
605 boolean done = Uninterruptibles.awaitUninterruptibly(txReadDone, 5, TimeUnit.SECONDS);
606 if(caughtEx.get() != null) {
607 throw caughtEx.get();
610 assertEquals("Tx read done", true, done);
612 // Wait for the read to complete. Since the shard never initialized, the Tx should
613 // have timed out and throw an appropriate exception cause.
616 txReadFuture.get().checkedGet(5, TimeUnit.SECONDS);
617 } catch(ReadFailedException e) {
620 blockRecoveryLatch.countDown();
626 private void testTransactionCommitFailureWithNoShardLeader(final boolean writeOnly, final String testName) throws Throwable {
627 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
628 String shardName = "default";
630 // We don't want the shard to become the leader so prevent shard elections.
631 datastoreContextBuilder.customRaftPolicyImplementation(
632 "org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy");
634 // The ShardManager uses the election timeout for FindPrimary so reset it low so it will timeout quickly.
635 datastoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(1).
636 shardInitializationTimeout(200, TimeUnit.MILLISECONDS);
638 DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName);
640 Object result = dataStore.getActorContext().executeOperation(dataStore.getActorContext().getShardManager(),
641 new FindLocalShard(shardName, true));
642 assertTrue("Expected LocalShardFound. Actual: " + result, result instanceof LocalShardFound);
644 // Create the write Tx.
646 final DOMStoreWriteTransaction writeTx = writeOnly ? dataStore.newWriteOnlyTransaction() :
647 dataStore.newReadWriteTransaction();
648 assertNotNull("newReadWriteTransaction returned null", writeTx);
650 // Do some modifications and ready the Tx on a separate thread.
652 final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
653 final AtomicReference<Exception> caughtEx = new AtomicReference<>();
654 final CountDownLatch txReady = new CountDownLatch(1);
655 Thread txThread = new Thread() {
659 writeTx.write(TestModel.JUNK_PATH,
660 ImmutableNodes.containerNode(TestModel.JUNK_QNAME));
662 txCohort.set(writeTx.ready());
663 } catch(Exception e) {
674 // Wait for the Tx operations to complete.
676 boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
677 if(caughtEx.get() != null) {
678 throw caughtEx.get();
681 assertEquals("Tx ready", true, done);
683 // Wait for the commit to complete. Since no shard leader was elected in time, the Tx
684 // should have timed out and throw an appropriate exception cause.
687 txCohort.get().canCommit().get(5, TimeUnit.SECONDS);
688 } catch(ExecutionException e) {
696 @Test(expected=NoShardLeaderException.class)
697 public void testWriteOnlyTransactionCommitFailureWithNoShardLeader() throws Throwable {
698 datastoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
699 testTransactionCommitFailureWithNoShardLeader(true, "testWriteOnlyTransactionCommitFailureWithNoShardLeader");
702 @Test(expected=NoShardLeaderException.class)
703 public void testReadWriteTransactionCommitFailureWithNoShardLeader() throws Throwable {
704 testTransactionCommitFailureWithNoShardLeader(false, "testReadWriteTransactionCommitFailureWithNoShardLeader");
708 public void testTransactionAbort() throws Exception{
709 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
710 DistributedDataStore dataStore =
711 setupDistributedDataStore("transactionAbortIntegrationTest", "test-1");
713 DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
714 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
716 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
718 DOMStoreThreePhaseCommitCohort cohort = writeTx.ready();
720 cohort.canCommit().get(5, TimeUnit.SECONDS);
722 cohort.abort().get(5, TimeUnit.SECONDS);
724 testWriteTransaction(dataStore, TestModel.TEST_PATH,
725 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
732 public void testTransactionChainWithSingleShard() throws Exception{
733 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
734 DistributedDataStore dataStore = setupDistributedDataStore("testTransactionChainWithSingleShard", "test-1");
736 // 1. Create a Tx chain and write-only Tx
738 DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
740 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
741 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
743 // 2. Write some data
745 NormalizedNode<?, ?> testNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
746 writeTx.write(TestModel.TEST_PATH, testNode);
748 // 3. Ready the Tx for commit
750 final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
752 // 4. Commit the Tx on another thread that first waits for the second read Tx.
754 final CountDownLatch continueCommit1 = new CountDownLatch(1);
755 final CountDownLatch commit1Done = new CountDownLatch(1);
756 final AtomicReference<Exception> commit1Error = new AtomicReference<>();
761 continueCommit1.await();
763 } catch (Exception e) {
766 commit1Done.countDown();
771 // 5. Create a new read Tx from the chain to read and verify the data from the first
772 // Tx is visible after being readied.
774 DOMStoreReadTransaction readTx = txChain.newReadOnlyTransaction();
775 Optional<NormalizedNode<?, ?>> optional = readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
776 assertEquals("isPresent", true, optional.isPresent());
777 assertEquals("Data node", testNode, optional.get());
779 // 6. Create a new RW Tx from the chain, write more data, and ready it
781 DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
782 MapNode outerNode = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
783 rwTx.write(TestModel.OUTER_LIST_PATH, outerNode);
785 DOMStoreThreePhaseCommitCohort cohort2 = rwTx.ready();
787 // 7. Create a new read Tx from the chain to read the data from the last RW Tx to
788 // verify it is visible.
790 readTx = txChain.newReadWriteTransaction();
791 optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
792 assertEquals("isPresent", true, optional.isPresent());
793 assertEquals("Data node", outerNode, optional.get());
795 // 8. Wait for the 2 commits to complete and close the chain.
797 continueCommit1.countDown();
798 Uninterruptibles.awaitUninterruptibly(commit1Done, 5, TimeUnit.SECONDS);
800 if(commit1Error.get() != null) {
801 throw commit1Error.get();
808 // 9. Create a new read Tx from the data store and verify committed data.
810 readTx = dataStore.newReadOnlyTransaction();
811 optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
812 assertEquals("isPresent", true, optional.isPresent());
813 assertEquals("Data node", outerNode, optional.get());
820 public void testTransactionChainWithMultipleShards() throws Exception{
821 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
822 DistributedDataStore dataStore = setupDistributedDataStore("testTransactionChainWithMultipleShards",
823 "cars-1", "people-1");
825 DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
827 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
828 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
830 writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
831 writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
833 writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
834 writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
836 DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
838 DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
840 MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
841 YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
842 readWriteTx.write(carPath, car);
844 MapEntryNode person = PeopleModel.newPersonEntry("jack");
845 YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
846 readWriteTx.merge(personPath, person);
848 Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
849 assertEquals("isPresent", true, optional.isPresent());
850 assertEquals("Data node", car, optional.get());
852 optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
853 assertEquals("isPresent", true, optional.isPresent());
854 assertEquals("Data node", person, optional.get());
856 DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
858 writeTx = txChain.newWriteOnlyTransaction();
860 writeTx.delete(carPath);
862 DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
864 ListenableFuture<Boolean> canCommit1 = cohort1.canCommit();
865 ListenableFuture<Boolean> canCommit2 = cohort2.canCommit();
867 doCommit(canCommit1, cohort1);
868 doCommit(canCommit2, cohort2);
873 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
875 optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
876 assertEquals("isPresent", false, optional.isPresent());
878 optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
879 assertEquals("isPresent", true, optional.isPresent());
880 assertEquals("Data node", person, optional.get());
887 public void testCreateChainedTransactionsInQuickSuccession() throws Exception{
888 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
889 DistributedDataStore dataStore = setupDistributedDataStore(
890 "testCreateChainedTransactionsInQuickSuccession", "cars-1");
892 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
893 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
894 LogicalDatastoreType.CONFIGURATION, dataStore).build(), MoreExecutors.directExecutor());
896 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
897 DOMTransactionChain txChain = broker.createTransactionChain(listener);
899 List<CheckedFuture<Void, TransactionCommitFailedException>> futures = new ArrayList<>();
901 DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
902 writeTx.put(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, CarsModel.emptyContainer());
903 writeTx.put(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
904 futures.add(writeTx.submit());
907 for(int i = 0; i < nCars; i++) {
908 DOMDataReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
910 rwTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.newCarPath("car" + i),
911 CarsModel.newCarEntry("car" + i, BigInteger.valueOf(20000)));
913 futures.add(rwTx.submit());
916 for(CheckedFuture<Void, TransactionCommitFailedException> f: futures) {
920 Optional<NormalizedNode<?, ?>> optional = txChain.newReadOnlyTransaction().read(
921 LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
922 assertEquals("isPresent", true, optional.isPresent());
923 assertEquals("# cars", nCars, ((Collection<?>)optional.get().getValue()).size());
934 public void testCreateChainedTransactionAfterEmptyTxReadied() throws Exception{
935 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
936 DistributedDataStore dataStore = setupDistributedDataStore(
937 "testCreateChainedTransactionAfterEmptyTxReadied", "test-1");
939 DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
941 DOMStoreReadWriteTransaction rwTx1 = txChain.newReadWriteTransaction();
945 DOMStoreReadWriteTransaction rwTx2 = txChain.newReadWriteTransaction();
947 Optional<NormalizedNode<?, ?>> optional = rwTx2.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
948 assertEquals("isPresent", false, optional.isPresent());
957 public void testCreateChainedTransactionWhenPreviousNotReady() throws Throwable {
958 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
959 DistributedDataStore dataStore = setupDistributedDataStore(
960 "testCreateChainedTransactionWhenPreviousNotReady", "test-1");
962 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
964 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
965 assertNotNull("newWriteOnlyTransaction returned null", writeTx);
967 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
969 // Try to create another Tx of each type - each should fail b/c the previous Tx wasn't
972 assertExceptionOnTxChainCreates(txChain, IllegalStateException.class);
977 public void testCreateChainedTransactionAfterClose() throws Throwable {
978 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
979 DistributedDataStore dataStore = setupDistributedDataStore(
980 "testCreateChainedTransactionAfterClose", "test-1");
982 DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
986 // Try to create another Tx of each type - should fail b/c the previous Tx was closed.
988 assertExceptionOnTxChainCreates(txChain, TransactionChainClosedException.class);
993 public void testChainWithReadOnlyTxAfterPreviousReady() throws Throwable {
994 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
995 DistributedDataStore dataStore = setupDistributedDataStore(
996 "testChainWithReadOnlyTxAfterPreviousReady", "test-1");
998 final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
1000 // Create a write tx and submit.
1002 DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
1003 writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1004 DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
1006 // Create read-only tx's and issue a read.
1008 CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture1 =
1009 txChain.newReadOnlyTransaction().read(TestModel.TEST_PATH);
1011 CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture2 =
1012 txChain.newReadOnlyTransaction().read(TestModel.TEST_PATH);
1014 // Create another write tx and issue the write.
1016 DOMStoreWriteTransaction writeTx2 = txChain.newWriteOnlyTransaction();
1017 writeTx2.write(TestModel.OUTER_LIST_PATH,
1018 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1020 // Ensure the reads succeed.
1022 assertEquals("isPresent", true, readFuture1.checkedGet(5, TimeUnit.SECONDS).isPresent());
1023 assertEquals("isPresent", true, readFuture2.checkedGet(5, TimeUnit.SECONDS).isPresent());
1025 // Ensure the writes succeed.
1027 DOMStoreThreePhaseCommitCohort cohort2 = writeTx2.ready();
1032 assertEquals("isPresent", true, txChain.newReadOnlyTransaction().read(TestModel.OUTER_LIST_PATH).
1033 checkedGet(5, TimeUnit.SECONDS).isPresent());
1038 public void testChainedTransactionFailureWithSingleShard() throws Exception{
1039 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
1040 DistributedDataStore dataStore = setupDistributedDataStore(
1041 "testChainedTransactionFailureWithSingleShard", "cars-1");
1043 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
1044 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
1045 LogicalDatastoreType.CONFIGURATION, dataStore).build(), MoreExecutors.directExecutor());
1047 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
1048 DOMTransactionChain txChain = broker.createTransactionChain(listener);
1050 DOMDataReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
1052 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
1053 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
1054 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
1056 rwTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
1059 rwTx.submit().checkedGet(5, TimeUnit.SECONDS);
1060 fail("Expected TransactionCommitFailedException");
1061 } catch (TransactionCommitFailedException e) {
1065 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(rwTx), any(Throwable.class));
1074 public void testChainedTransactionFailureWithMultipleShards() throws Exception{
1075 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
1076 DistributedDataStore dataStore = setupDistributedDataStore(
1077 "testChainedTransactionFailureWithMultipleShards", "cars-1", "people-1");
1079 ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
1080 ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
1081 LogicalDatastoreType.CONFIGURATION, dataStore).build(), MoreExecutors.directExecutor());
1083 TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
1084 DOMTransactionChain txChain = broker.createTransactionChain(listener);
1086 DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
1088 writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
1090 ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
1091 new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
1092 withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
1094 // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
1095 // done for put for performance reasons.
1096 writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
1099 writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
1100 fail("Expected TransactionCommitFailedException");
1101 } catch (TransactionCommitFailedException e) {
1105 verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
1114 public void testChangeListenerRegistration() throws Exception{
1115 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
1116 DistributedDataStore dataStore =
1117 setupDistributedDataStore("testChangeListenerRegistration", "test-1");
1119 testWriteTransaction(dataStore, TestModel.TEST_PATH,
1120 ImmutableNodes.containerNode(TestModel.TEST_QNAME));
1122 MockDataChangeListener listener = new MockDataChangeListener(1);
1124 ListenerRegistration<MockDataChangeListener>
1125 listenerReg = dataStore.registerChangeListener(TestModel.TEST_PATH, listener,
1126 DataChangeScope.SUBTREE);
1128 assertNotNull("registerChangeListener returned null", listenerReg);
1130 // Wait for the initial notification
1132 listener.waitForChangeEvents(TestModel.TEST_PATH);
1138 testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
1139 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
1141 YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH).
1142 nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build();
1143 testWriteTransaction(dataStore, listPath,
1144 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1));
1146 // Wait for the 2 updates.
1148 listener.waitForChangeEvents(TestModel.OUTER_LIST_PATH, listPath);
1150 listenerReg.close();
1152 testWriteTransaction(dataStore, YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH).
1153 nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build(),
1154 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2));
1156 listener.expectNoMoreChanges("Received unexpected change after close");
1163 public void testRestoreFromDatastoreSnapshot() throws Exception{
1164 new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
1165 String name = "transactionIntegrationTest";
1167 ContainerNode carsNode = CarsModel.newCarsNode(CarsModel.newCarsMapNode(
1168 CarsModel.newCarEntry("optima", BigInteger.valueOf(20000L)),
1169 CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000L))));
1171 ShardDataTree dataTree = new ShardDataTree(SchemaContextHelper.full());
1172 AbstractShardTest.writeToStore(dataTree, CarsModel.BASE_PATH, carsNode);
1173 NormalizedNode<?, ?> root = AbstractShardTest.readStore(dataTree.getDataTree(),
1174 YangInstanceIdentifier.builder().build());
1176 Snapshot carsSnapshot = Snapshot.create(SerializationUtils.serializeNormalizedNode(root),
1177 Collections.<ReplicatedLogEntry>emptyList(), 2, 1, 2, 1, 1, "member-1");
1179 NormalizedNode<?, ?> peopleNode = PeopleModel.create();
1180 dataTree = new ShardDataTree(SchemaContextHelper.full());
1181 AbstractShardTest.writeToStore(dataTree, PeopleModel.BASE_PATH, peopleNode);
1182 root = AbstractShardTest.readStore(dataTree.getDataTree(), YangInstanceIdentifier.builder().build());
1184 Snapshot peopleSnapshot = Snapshot.create(SerializationUtils.serializeNormalizedNode(root),
1185 Collections.<ReplicatedLogEntry>emptyList(), 2, 1, 2, 1, 1, "member-1");
1187 restoreFromSnapshot = new DatastoreSnapshot(name, null, Arrays.asList(
1188 new DatastoreSnapshot.ShardSnapshot("cars",
1189 org.apache.commons.lang3.SerializationUtils.serialize(carsSnapshot)),
1190 new DatastoreSnapshot.ShardSnapshot("people",
1191 org.apache.commons.lang3.SerializationUtils.serialize(peopleSnapshot))));
1193 DistributedDataStore dataStore = setupDistributedDataStore(name, "module-shards-member1.conf",
1194 true, "cars", "people");
1196 DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
1198 Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1199 assertEquals("isPresent", true, optional.isPresent());
1200 assertEquals("Data node", carsNode, optional.get());
1202 optional = readTx.read(PeopleModel.BASE_PATH).get(5, TimeUnit.SECONDS);
1203 assertEquals("isPresent", true, optional.isPresent());
1204 assertEquals("Data node", peopleNode, optional.get());