2 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.datastore.compat;
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertTrue;
13 import static org.mockito.Mockito.inOrder;
14 import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.HELIUM_2_VERSION;
15 import akka.actor.ActorRef;
16 import akka.actor.PoisonPill;
17 import akka.dispatch.Dispatchers;
18 import akka.dispatch.OnComplete;
19 import akka.pattern.Patterns;
20 import akka.testkit.TestActorRef;
21 import akka.util.Timeout;
22 import com.google.common.base.Optional;
23 import java.io.IOException;
24 import java.util.Collections;
25 import java.util.HashSet;
27 import java.util.concurrent.CountDownLatch;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.atomic.AtomicReference;
30 import org.junit.Test;
31 import org.mockito.InOrder;
32 import org.opendaylight.controller.cluster.datastore.AbstractShardTest;
33 import org.opendaylight.controller.cluster.datastore.Shard;
34 import org.opendaylight.controller.cluster.datastore.ShardDataTree;
35 import org.opendaylight.controller.cluster.datastore.ShardDataTreeCohort;
36 import org.opendaylight.controller.cluster.datastore.ShardTestKit;
37 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
38 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
39 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
40 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
41 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
42 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
43 import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
44 import org.opendaylight.controller.cluster.datastore.modification.Modification;
45 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
46 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
47 import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
48 import org.opendaylight.controller.cluster.datastore.node.NormalizedNodeToNodeCodec;
49 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
50 import org.opendaylight.controller.cluster.raft.ReplicatedLogImplEntry;
51 import org.opendaylight.controller.cluster.raft.Snapshot;
52 import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries;
53 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
54 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
55 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
56 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
57 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
58 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
59 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
60 import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
63 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
64 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
67 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
68 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
69 import scala.concurrent.Future;
70 import scala.concurrent.duration.FiniteDuration;
73 * Unit tests for backwards compatibility with pre-Lithium versions.
75 * @author Thomas Pantelis
77 public class PreLithiumShardTest extends AbstractShardTest {
79 private CompositeModificationPayload newLegacyPayload(final Modification... mods) {
80 MutableCompositeModification compMod = new MutableCompositeModification();
81 for(Modification mod: mods) {
82 compMod.addModification(mod);
85 return new CompositeModificationPayload(compMod.toSerializable());
88 private CompositeModificationByteStringPayload newLegacyByteStringPayload(final Modification... mods) {
89 MutableCompositeModification compMod = new MutableCompositeModification();
90 for(Modification mod: mods) {
91 compMod.addModification(mod);
94 return new CompositeModificationByteStringPayload(compMod.toSerializable());
97 private ModificationPayload newModificationPayload(final Modification... mods) throws IOException {
98 MutableCompositeModification compMod = new MutableCompositeModification();
99 for(Modification mod: mods) {
100 compMod.addModification(mod);
103 return new ModificationPayload(compMod);
107 public void testApplyHelium2VersionSnapshot() throws Exception {
108 TestActorRef<Shard> shard = TestActorRef.create(getSystem(), newShardProps(),
109 "testApplyHelium2VersionSnapshot");
111 NormalizedNodeToNodeCodec codec = new NormalizedNodeToNodeCodec(SCHEMA_CONTEXT);
113 DataTree store = InMemoryDataTreeFactory.getInstance().create();
114 store.setSchemaContext(SCHEMA_CONTEXT);
116 writeToStore(store, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
118 YangInstanceIdentifier root = YangInstanceIdentifier.builder().build();
119 NormalizedNode<?,?> expected = readStore(store, root);
121 NormalizedNodeMessages.Container encode = codec.encode(expected);
123 ApplySnapshot applySnapshot = new ApplySnapshot(Snapshot.create(
124 encode.getNormalizedNode().toByteString().toByteArray(),
125 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4));
127 shard.underlyingActor().onReceiveCommand(applySnapshot);
129 NormalizedNode<?,?> actual = readStore(shard, root);
131 assertEquals("Root node", expected, actual);
133 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
137 public void testHelium2VersionApplyStateLegacy() throws Exception {
139 TestActorRef<Shard> shard = TestActorRef.create(getSystem(), newShardProps(), "testHelium2VersionApplyStateLegacy");
141 NormalizedNode<?, ?> node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
143 ApplyState applyState = new ApplyState(null, "test", new ReplicatedLogImplEntry(1, 2,
144 newLegacyByteStringPayload(new WriteModification(TestModel.TEST_PATH, node))));
146 shard.underlyingActor().onReceiveCommand(applyState);
148 NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
149 assertEquals("Applied state", node, actual);
151 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
155 public void testHelium2VersionRecovery() throws Exception {
157 DataTree testStore = InMemoryDataTreeFactory.getInstance().create();
158 testStore.setSchemaContext(SCHEMA_CONTEXT);
160 writeToStore(testStore, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
162 NormalizedNode<?, ?> root = readStore(testStore, YangInstanceIdentifier.builder().build());
164 InMemorySnapshotStore.addSnapshot(shardID.toString(), Snapshot.create(
165 new NormalizedNodeToNodeCodec(SCHEMA_CONTEXT).encode(root).
166 getNormalizedNode().toByteString().toByteArray(),
167 Collections.<ReplicatedLogEntry>emptyList(), 0, 1, -1, -1));
169 // Set up the InMemoryJournal.
171 InMemoryJournal.addEntry(shardID.toString(), 0, new ReplicatedLogImplEntry(0, 1, newLegacyPayload(
172 new WriteModification(TestModel.OUTER_LIST_PATH,
173 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build()))));
175 int nListEntries = 16;
176 Set<Integer> listEntryKeys = new HashSet<>();
179 // Add some CompositeModificationPayload entries
181 listEntryKeys.add(Integer.valueOf(i));
182 YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
183 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
184 Modification mod = new MergeModification(path,
185 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
186 InMemoryJournal.addEntry(shardID.toString(), i, new ReplicatedLogImplEntry(i, 1,
187 newLegacyPayload(mod)));
190 // Add some CompositeModificationByteStringPayload entries
191 for(; i <= nListEntries; i++) {
192 listEntryKeys.add(Integer.valueOf(i));
193 YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
194 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
195 Modification mod = new MergeModification(path,
196 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
197 InMemoryJournal.addEntry(shardID.toString(), i, new ReplicatedLogImplEntry(i, 1,
198 newLegacyByteStringPayload(mod)));
201 InMemoryJournal.addEntry(shardID.toString(), nListEntries + 1, new ApplyLogEntries(nListEntries));
203 testRecovery(listEntryKeys);
206 @SuppressWarnings({ "unchecked" })
208 public void testPreLithiumConcurrentThreePhaseCommits() throws Throwable {
209 new ShardTestKit(getSystem()) {{
210 final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
211 newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
212 "testPreLithiumConcurrentThreePhaseCommits");
214 waitUntilLeader(shard);
216 // Setup 3 simulated transactions with mock cohorts backed by real cohorts.
218 ShardDataTree dataStore = shard.underlyingActor().getDataStore();
220 String transactionID1 = "tx1";
221 MutableCompositeModification modification1 = new MutableCompositeModification();
222 ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
223 TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
225 String transactionID2 = "tx2";
226 MutableCompositeModification modification2 = new MutableCompositeModification();
227 ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
228 TestModel.OUTER_LIST_PATH,
229 ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
232 String transactionID3 = "tx3";
233 MutableCompositeModification modification3 = new MutableCompositeModification();
234 ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
235 YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
236 .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
237 ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
241 final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
242 final Timeout timeout = new Timeout(duration);
244 // Simulate the ForwardedReadyTransaction message for the first Tx that would be sent
245 // by the ShardTransaction.
247 shard.tell(new ForwardedReadyTransaction(transactionID1, HELIUM_2_VERSION,
248 cohort1, modification1, true, false), getRef());
249 ReadyTransactionReply readyReply = ReadyTransactionReply.fromSerializable(
250 expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS));
251 assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
253 // Send the CanCommitTransaction message for the first Tx.
255 shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
256 CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
257 expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
258 assertEquals("Can commit", true, canCommitReply.getCanCommit());
260 // Send the ForwardedReadyTransaction for the next 2 Tx's.
262 shard.tell(new ForwardedReadyTransaction(transactionID2, HELIUM_2_VERSION,
263 cohort2, modification2, true, false), getRef());
264 expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS);
266 shard.tell(new ForwardedReadyTransaction(transactionID3, HELIUM_2_VERSION,
267 cohort3, modification3, true, false), getRef());
268 expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS);
270 // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and
271 // processed after the first Tx completes.
273 Future<Object> canCommitFuture1 = Patterns.ask(shard,
274 new CanCommitTransaction(transactionID2).toSerializable(), timeout);
276 Future<Object> canCommitFuture2 = Patterns.ask(shard,
277 new CanCommitTransaction(transactionID3).toSerializable(), timeout);
279 // Send the CommitTransaction message for the first Tx. After it completes, it should
280 // trigger the 2nd Tx to proceed which should in turn then trigger the 3rd.
282 shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
283 expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
285 // Wait for the next 2 Tx's to complete.
287 final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
288 final CountDownLatch commitLatch = new CountDownLatch(2);
290 class OnFutureComplete extends OnComplete<Object> {
291 private final Class<?> expRespType;
293 OnFutureComplete(final Class<?> expRespType) {
294 this.expRespType = expRespType;
298 public void onComplete(final Throwable error, final Object resp) {
300 caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
303 assertEquals("Commit response type", expRespType, resp.getClass());
305 } catch (Exception e) {
311 void onSuccess(final Object resp) throws Exception {
315 class OnCommitFutureComplete extends OnFutureComplete {
316 OnCommitFutureComplete() {
317 super(CommitTransactionReply.SERIALIZABLE_CLASS);
321 public void onComplete(final Throwable error, final Object resp) {
322 super.onComplete(error, resp);
323 commitLatch.countDown();
327 class OnCanCommitFutureComplete extends OnFutureComplete {
328 private final String transactionID;
330 OnCanCommitFutureComplete(final String transactionID) {
331 super(CanCommitTransactionReply.SERIALIZABLE_CLASS);
332 this.transactionID = transactionID;
336 void onSuccess(final Object resp) throws Exception {
337 CanCommitTransactionReply canCommitReply =
338 CanCommitTransactionReply.fromSerializable(resp);
339 assertEquals("Can commit", true, canCommitReply.getCanCommit());
341 Future<Object> commitFuture = Patterns.ask(shard,
342 new CommitTransaction(transactionID).toSerializable(), timeout);
343 commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
347 canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2),
348 getSystem().dispatcher());
350 canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3),
351 getSystem().dispatcher());
353 boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
355 if(caughtEx.get() != null) {
356 throw caughtEx.get();
359 assertEquals("Commits complete", true, done);
361 InOrder inOrder = inOrder(cohort1, cohort2, cohort3);
362 inOrder.verify(cohort1).canCommit();
363 inOrder.verify(cohort1).preCommit();
364 inOrder.verify(cohort1).commit();
365 inOrder.verify(cohort2).canCommit();
366 inOrder.verify(cohort2).preCommit();
367 inOrder.verify(cohort2).commit();
368 inOrder.verify(cohort3).canCommit();
369 inOrder.verify(cohort3).preCommit();
370 inOrder.verify(cohort3).commit();
372 // Verify data in the data store.
374 NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
375 assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
376 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
377 outerList.getValue() instanceof Iterable);
378 Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
379 assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
380 entry instanceof MapEntryNode);
381 MapEntryNode mapEntry = (MapEntryNode)entry;
382 Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
383 mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
384 assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
385 assertEquals(TestModel.ID_QNAME.getLocalName() + " value", 1, idLeaf.get().getValue());
387 verifyLastApplied(shard, 2);
389 shard.tell(PoisonPill.getInstance(), ActorRef.noSender());