BUG-865: specify DataTreeType explicitly
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / compat / PreLithiumShardTest.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.datastore.compat;
9
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;
26 import java.util.Set;
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.ApplyState;
54 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
55 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
56 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
57 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
58 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
59 import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
62 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
63 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
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;
71
72 /**
73  * Unit tests for backwards compatibility with pre-Lithium versions.
74  *
75  * @author Thomas Pantelis
76  */
77 public class PreLithiumShardTest extends AbstractShardTest {
78
79     private static CompositeModificationPayload newLegacyPayload(final Modification... mods) {
80         MutableCompositeModification compMod = new MutableCompositeModification();
81         for(Modification mod: mods) {
82             compMod.addModification(mod);
83         }
84
85         return new CompositeModificationPayload(compMod.toSerializable());
86     }
87
88     private static CompositeModificationByteStringPayload newLegacyByteStringPayload(final Modification... mods) {
89         MutableCompositeModification compMod = new MutableCompositeModification();
90         for(Modification mod: mods) {
91             compMod.addModification(mod);
92         }
93
94         return new CompositeModificationByteStringPayload(compMod.toSerializable());
95     }
96
97     private static ModificationPayload newModificationPayload(final Modification... mods) throws IOException {
98         MutableCompositeModification compMod = new MutableCompositeModification();
99         for(Modification mod: mods) {
100             compMod.addModification(mod);
101         }
102
103         return new ModificationPayload(compMod);
104     }
105
106     @Test
107     public void testApplyHelium2VersionSnapshot() throws Exception {
108         TestActorRef<Shard> shard = TestActorRef.create(getSystem(), newShardProps(),
109                 "testApplyHelium2VersionSnapshot");
110
111         NormalizedNodeToNodeCodec codec = new NormalizedNodeToNodeCodec(SCHEMA_CONTEXT);
112
113         DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
114         store.setSchemaContext(SCHEMA_CONTEXT);
115
116         writeToStore(store, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
117
118         YangInstanceIdentifier root = YangInstanceIdentifier.builder().build();
119         NormalizedNode<?,?> expected = readStore(store, root);
120
121         NormalizedNodeMessages.Container encode = codec.encode(expected);
122
123         Snapshot snapshot = Snapshot.create(encode.getNormalizedNode().toByteString().toByteArray(),
124                 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4);
125
126         shard.underlyingActor().getRaftActorSnapshotCohort().applySnapshot(snapshot.getState());
127
128         NormalizedNode<?,?> actual = readStore(shard, root);
129
130         assertEquals("Root node", expected, actual);
131
132         shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
133     }
134
135     @Test
136     public void testHelium2VersionApplyStateLegacy() throws Exception {
137         new ShardTestKit(getSystem()) {{
138             TestActorRef<Shard> shard = TestActorRef.create(getSystem(), newShardProps(),
139                     "testHelium2VersionApplyStateLegacy");
140
141             waitUntilLeader(shard);
142
143             NormalizedNode<?, ?> node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
144
145             ApplyState applyState = new ApplyState(null, "test", new ReplicatedLogImplEntry(1, 2,
146                     newLegacyByteStringPayload(new WriteModification(TestModel.TEST_PATH, node))));
147
148             shard.underlyingActor().onReceiveCommand(applyState);
149
150             NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
151             assertEquals("Applied state", node, actual);
152
153             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
154         }};
155     }
156
157     @Test
158     public void testHelium2VersionRecovery() throws Exception {
159
160         DataTree testStore = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
161         testStore.setSchemaContext(SCHEMA_CONTEXT);
162
163         writeToStore(testStore, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
164
165         NormalizedNode<?, ?> root = readStore(testStore, YangInstanceIdentifier.builder().build());
166
167         InMemorySnapshotStore.addSnapshot(shardID.toString(), Snapshot.create(
168                 new NormalizedNodeToNodeCodec(SCHEMA_CONTEXT).encode(root).
169                                 getNormalizedNode().toByteString().toByteArray(),
170                                 Collections.<ReplicatedLogEntry>emptyList(), 0, 1, -1, -1));
171
172         InMemoryJournal.addEntry(shardID.toString(), 0, new String("Dummy data as snapshot sequence number is " +
173                 "set to 0 in InMemorySnapshotStore and journal recovery seq number will start from 1"));
174
175         // Set up the InMemoryJournal.
176
177         InMemoryJournal.addEntry(shardID.toString(), 1, new ReplicatedLogImplEntry(0, 1, newLegacyPayload(
178                   new WriteModification(TestModel.OUTER_LIST_PATH,
179                           ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build()))));
180
181         int nListEntries = 16;
182         Set<Integer> listEntryKeys = new HashSet<>();
183         int i = 1;
184
185         // Add some CompositeModificationPayload entries
186         for(; i <= 8; i++) {
187             listEntryKeys.add(Integer.valueOf(i));
188             YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
189                     .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
190             Modification mod = new MergeModification(path,
191                     ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
192             InMemoryJournal.addEntry(shardID.toString(), i+1, new ReplicatedLogImplEntry(i, 1,
193                     newLegacyPayload(mod)));
194         }
195
196         // Add some CompositeModificationByteStringPayload entries
197         for(; i <= nListEntries; i++) {
198             listEntryKeys.add(Integer.valueOf(i));
199             YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
200                     .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
201             Modification mod = new MergeModification(path,
202                     ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
203             InMemoryJournal.addEntry(shardID.toString(), i+1, new ReplicatedLogImplEntry(i, 1,
204                     newLegacyByteStringPayload(mod)));
205         }
206
207         InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2, new ApplyLogEntries(nListEntries));
208
209         testRecovery(listEntryKeys);
210     }
211
212     @SuppressWarnings({ "unchecked" })
213     @Test
214     public void testPreLithiumConcurrentThreePhaseCommits() throws Throwable {
215         new ShardTestKit(getSystem()) {{
216             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
217                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
218                     "testPreLithiumConcurrentThreePhaseCommits");
219
220             waitUntilLeader(shard);
221
222             // Setup 3 simulated transactions with mock cohorts backed by real cohorts.
223
224             ShardDataTree dataStore = shard.underlyingActor().getDataStore();
225
226             String transactionID1 = "tx1";
227             MutableCompositeModification modification1 = new MutableCompositeModification();
228             ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
229                     TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
230
231             String transactionID2 = "tx2";
232             MutableCompositeModification modification2 = new MutableCompositeModification();
233             ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
234                     TestModel.OUTER_LIST_PATH,
235                     ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
236                     modification2);
237
238             String transactionID3 = "tx3";
239             MutableCompositeModification modification3 = new MutableCompositeModification();
240             ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
241                     YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
242                         .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
243                     ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
244                     modification3);
245
246             long timeoutSec = 5;
247             final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
248             final Timeout timeout = new Timeout(duration);
249
250             // Simulate the ForwardedReadyTransaction message for the first Tx that would be sent
251             // by the ShardTransaction.
252
253             shard.tell(new ForwardedReadyTransaction(transactionID1, HELIUM_2_VERSION,
254                     cohort1, modification1, true, false), getRef());
255             ReadyTransactionReply readyReply = ReadyTransactionReply.fromSerializable(
256                     expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS));
257             assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
258
259             // Send the CanCommitTransaction message for the first Tx.
260
261             shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
262             CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
263                     expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
264             assertEquals("Can commit", true, canCommitReply.getCanCommit());
265
266             // Send the ForwardedReadyTransaction for the next 2 Tx's.
267
268             shard.tell(new ForwardedReadyTransaction(transactionID2, HELIUM_2_VERSION,
269                     cohort2, modification2, true, false), getRef());
270             expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS);
271
272             shard.tell(new ForwardedReadyTransaction(transactionID3, HELIUM_2_VERSION,
273                     cohort3, modification3, true, false), getRef());
274             expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS);
275
276             // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and
277             // processed after the first Tx completes.
278
279             Future<Object> canCommitFuture1 = Patterns.ask(shard,
280                     new CanCommitTransaction(transactionID2).toSerializable(), timeout);
281
282             Future<Object> canCommitFuture2 = Patterns.ask(shard,
283                     new CanCommitTransaction(transactionID3).toSerializable(), timeout);
284
285             // Send the CommitTransaction message for the first Tx. After it completes, it should
286             // trigger the 2nd Tx to proceed which should in turn then trigger the 3rd.
287
288             shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
289             expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
290
291             // Wait for the next 2 Tx's to complete.
292
293             final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
294             final CountDownLatch commitLatch = new CountDownLatch(2);
295
296             class OnFutureComplete extends OnComplete<Object> {
297                 private final Class<?> expRespType;
298
299                 OnFutureComplete(final Class<?> expRespType) {
300                     this.expRespType = expRespType;
301                 }
302
303                 @Override
304                 public void onComplete(final Throwable error, final Object resp) {
305                     if(error != null) {
306                         caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
307                     } else {
308                         try {
309                             assertEquals("Commit response type", expRespType, resp.getClass());
310                             onSuccess(resp);
311                         } catch (Exception e) {
312                             caughtEx.set(e);
313                         }
314                     }
315                 }
316
317                 void onSuccess(final Object resp) throws Exception {
318                 }
319             }
320
321             class OnCommitFutureComplete extends OnFutureComplete {
322                 OnCommitFutureComplete() {
323                     super(CommitTransactionReply.SERIALIZABLE_CLASS);
324                 }
325
326                 @Override
327                 public void onComplete(final Throwable error, final Object resp) {
328                     super.onComplete(error, resp);
329                     commitLatch.countDown();
330                 }
331             }
332
333             class OnCanCommitFutureComplete extends OnFutureComplete {
334                 private final String transactionID;
335
336                 OnCanCommitFutureComplete(final String transactionID) {
337                     super(CanCommitTransactionReply.SERIALIZABLE_CLASS);
338                     this.transactionID = transactionID;
339                 }
340
341                 @Override
342                 void onSuccess(final Object resp) throws Exception {
343                     CanCommitTransactionReply canCommitReply =
344                             CanCommitTransactionReply.fromSerializable(resp);
345                     assertEquals("Can commit", true, canCommitReply.getCanCommit());
346
347                     Future<Object> commitFuture = Patterns.ask(shard,
348                             new CommitTransaction(transactionID).toSerializable(), timeout);
349                     commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
350                 }
351             }
352
353             canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2),
354                     getSystem().dispatcher());
355
356             canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3),
357                     getSystem().dispatcher());
358
359             boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
360
361             if(caughtEx.get() != null) {
362                 throw caughtEx.get();
363             }
364
365             assertEquals("Commits complete", true, done);
366
367             InOrder inOrder = inOrder(cohort1, cohort2, cohort3);
368             inOrder.verify(cohort1).canCommit();
369             inOrder.verify(cohort1).preCommit();
370             inOrder.verify(cohort1).commit();
371             inOrder.verify(cohort2).canCommit();
372             inOrder.verify(cohort2).preCommit();
373             inOrder.verify(cohort2).commit();
374             inOrder.verify(cohort3).canCommit();
375             inOrder.verify(cohort3).preCommit();
376             inOrder.verify(cohort3).commit();
377
378             // Verify data in the data store.
379
380             NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
381             assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
382             assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
383                     outerList.getValue() instanceof Iterable);
384             Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
385             assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
386                        entry instanceof MapEntryNode);
387             MapEntryNode mapEntry = (MapEntryNode)entry;
388             Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
389                     mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
390             assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
391             assertEquals(TestModel.ID_QNAME.getLocalName() + " value", 1, idLeaf.get().getValue());
392
393             verifyLastApplied(shard, 2);
394
395             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
396         }};
397     }
398 }