Bug:3260-Recovery misses flows installed on single node
[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.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;
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 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 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 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();
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         ApplySnapshot applySnapshot = new ApplySnapshot(Snapshot.create(
124                 encode.getNormalizedNode().toByteString().toByteArray(),
125                 Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4));
126
127         shard.underlyingActor().onReceiveCommand(applySnapshot);
128
129         NormalizedNode<?,?> actual = readStore(shard, root);
130
131         assertEquals("Root node", expected, actual);
132
133         shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
134     }
135
136     @Test
137     public void testHelium2VersionApplyStateLegacy() throws Exception {
138
139         TestActorRef<Shard> shard = TestActorRef.create(getSystem(), newShardProps(), "testHelium2VersionApplyStateLegacy");
140
141         NormalizedNode<?, ?> node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
142
143         ApplyState applyState = new ApplyState(null, "test", new ReplicatedLogImplEntry(1, 2,
144                 newLegacyByteStringPayload(new WriteModification(TestModel.TEST_PATH, node))));
145
146         shard.underlyingActor().onReceiveCommand(applyState);
147
148         NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
149         assertEquals("Applied state", node, actual);
150
151         shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
152     }
153
154     @Test
155     public void testHelium2VersionRecovery() throws Exception {
156
157         DataTree testStore = InMemoryDataTreeFactory.getInstance().create();
158         testStore.setSchemaContext(SCHEMA_CONTEXT);
159
160         writeToStore(testStore, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
161
162         NormalizedNode<?, ?> root = readStore(testStore, YangInstanceIdentifier.builder().build());
163
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));
168
169         InMemoryJournal.addEntry(shardID.toString(), 0, new String("Dummy data as snapshot sequence number is " +
170                 "set to 0 in InMemorySnapshotStore and journal recovery seq number will start from 1"));
171
172         // Set up the InMemoryJournal.
173
174         InMemoryJournal.addEntry(shardID.toString(), 1, new ReplicatedLogImplEntry(0, 1, newLegacyPayload(
175                   new WriteModification(TestModel.OUTER_LIST_PATH,
176                           ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build()))));
177
178         int nListEntries = 16;
179         Set<Integer> listEntryKeys = new HashSet<>();
180         int i = 1;
181
182         // Add some CompositeModificationPayload entries
183         for(; i <= 8; i++) {
184             listEntryKeys.add(Integer.valueOf(i));
185             YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
186                     .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
187             Modification mod = new MergeModification(path,
188                     ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
189             InMemoryJournal.addEntry(shardID.toString(), i+1, new ReplicatedLogImplEntry(i, 1,
190                     newLegacyPayload(mod)));
191         }
192
193         // Add some CompositeModificationByteStringPayload entries
194         for(; i <= nListEntries; i++) {
195             listEntryKeys.add(Integer.valueOf(i));
196             YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
197                     .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
198             Modification mod = new MergeModification(path,
199                     ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
200             InMemoryJournal.addEntry(shardID.toString(), i+1, new ReplicatedLogImplEntry(i, 1,
201                     newLegacyByteStringPayload(mod)));
202         }
203
204         InMemoryJournal.addEntry(shardID.toString(), nListEntries + 2, new ApplyLogEntries(nListEntries));
205
206         testRecovery(listEntryKeys);
207     }
208
209     @SuppressWarnings({ "unchecked" })
210     @Test
211     public void testPreLithiumConcurrentThreePhaseCommits() throws Throwable {
212         new ShardTestKit(getSystem()) {{
213             final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
214                     newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
215                     "testPreLithiumConcurrentThreePhaseCommits");
216
217             waitUntilLeader(shard);
218
219             // Setup 3 simulated transactions with mock cohorts backed by real cohorts.
220
221             ShardDataTree dataStore = shard.underlyingActor().getDataStore();
222
223             String transactionID1 = "tx1";
224             MutableCompositeModification modification1 = new MutableCompositeModification();
225             ShardDataTreeCohort cohort1 = setupMockWriteTransaction("cohort1", dataStore,
226                     TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME), modification1);
227
228             String transactionID2 = "tx2";
229             MutableCompositeModification modification2 = new MutableCompositeModification();
230             ShardDataTreeCohort cohort2 = setupMockWriteTransaction("cohort2", dataStore,
231                     TestModel.OUTER_LIST_PATH,
232                     ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(),
233                     modification2);
234
235             String transactionID3 = "tx3";
236             MutableCompositeModification modification3 = new MutableCompositeModification();
237             ShardDataTreeCohort cohort3 = setupMockWriteTransaction("cohort3", dataStore,
238                     YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
239                         .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
240                     ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
241                     modification3);
242
243             long timeoutSec = 5;
244             final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
245             final Timeout timeout = new Timeout(duration);
246
247             // Simulate the ForwardedReadyTransaction message for the first Tx that would be sent
248             // by the ShardTransaction.
249
250             shard.tell(new ForwardedReadyTransaction(transactionID1, HELIUM_2_VERSION,
251                     cohort1, modification1, true, false), getRef());
252             ReadyTransactionReply readyReply = ReadyTransactionReply.fromSerializable(
253                     expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS));
254             assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
255
256             // Send the CanCommitTransaction message for the first Tx.
257
258             shard.tell(new CanCommitTransaction(transactionID1).toSerializable(), getRef());
259             CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
260                     expectMsgClass(duration, CanCommitTransactionReply.SERIALIZABLE_CLASS));
261             assertEquals("Can commit", true, canCommitReply.getCanCommit());
262
263             // Send the ForwardedReadyTransaction for the next 2 Tx's.
264
265             shard.tell(new ForwardedReadyTransaction(transactionID2, HELIUM_2_VERSION,
266                     cohort2, modification2, true, false), getRef());
267             expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS);
268
269             shard.tell(new ForwardedReadyTransaction(transactionID3, HELIUM_2_VERSION,
270                     cohort3, modification3, true, false), getRef());
271             expectMsgClass(duration, ReadyTransactionReply.SERIALIZABLE_CLASS);
272
273             // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and
274             // processed after the first Tx completes.
275
276             Future<Object> canCommitFuture1 = Patterns.ask(shard,
277                     new CanCommitTransaction(transactionID2).toSerializable(), timeout);
278
279             Future<Object> canCommitFuture2 = Patterns.ask(shard,
280                     new CanCommitTransaction(transactionID3).toSerializable(), timeout);
281
282             // Send the CommitTransaction message for the first Tx. After it completes, it should
283             // trigger the 2nd Tx to proceed which should in turn then trigger the 3rd.
284
285             shard.tell(new CommitTransaction(transactionID1).toSerializable(), getRef());
286             expectMsgClass(duration, CommitTransactionReply.SERIALIZABLE_CLASS);
287
288             // Wait for the next 2 Tx's to complete.
289
290             final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
291             final CountDownLatch commitLatch = new CountDownLatch(2);
292
293             class OnFutureComplete extends OnComplete<Object> {
294                 private final Class<?> expRespType;
295
296                 OnFutureComplete(final Class<?> expRespType) {
297                     this.expRespType = expRespType;
298                 }
299
300                 @Override
301                 public void onComplete(final Throwable error, final Object resp) {
302                     if(error != null) {
303                         caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
304                     } else {
305                         try {
306                             assertEquals("Commit response type", expRespType, resp.getClass());
307                             onSuccess(resp);
308                         } catch (Exception e) {
309                             caughtEx.set(e);
310                         }
311                     }
312                 }
313
314                 void onSuccess(final Object resp) throws Exception {
315                 }
316             }
317
318             class OnCommitFutureComplete extends OnFutureComplete {
319                 OnCommitFutureComplete() {
320                     super(CommitTransactionReply.SERIALIZABLE_CLASS);
321                 }
322
323                 @Override
324                 public void onComplete(final Throwable error, final Object resp) {
325                     super.onComplete(error, resp);
326                     commitLatch.countDown();
327                 }
328             }
329
330             class OnCanCommitFutureComplete extends OnFutureComplete {
331                 private final String transactionID;
332
333                 OnCanCommitFutureComplete(final String transactionID) {
334                     super(CanCommitTransactionReply.SERIALIZABLE_CLASS);
335                     this.transactionID = transactionID;
336                 }
337
338                 @Override
339                 void onSuccess(final Object resp) throws Exception {
340                     CanCommitTransactionReply canCommitReply =
341                             CanCommitTransactionReply.fromSerializable(resp);
342                     assertEquals("Can commit", true, canCommitReply.getCanCommit());
343
344                     Future<Object> commitFuture = Patterns.ask(shard,
345                             new CommitTransaction(transactionID).toSerializable(), timeout);
346                     commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
347                 }
348             }
349
350             canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2),
351                     getSystem().dispatcher());
352
353             canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3),
354                     getSystem().dispatcher());
355
356             boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
357
358             if(caughtEx.get() != null) {
359                 throw caughtEx.get();
360             }
361
362             assertEquals("Commits complete", true, done);
363
364             InOrder inOrder = inOrder(cohort1, cohort2, cohort3);
365             inOrder.verify(cohort1).canCommit();
366             inOrder.verify(cohort1).preCommit();
367             inOrder.verify(cohort1).commit();
368             inOrder.verify(cohort2).canCommit();
369             inOrder.verify(cohort2).preCommit();
370             inOrder.verify(cohort2).commit();
371             inOrder.verify(cohort3).canCommit();
372             inOrder.verify(cohort3).preCommit();
373             inOrder.verify(cohort3).commit();
374
375             // Verify data in the data store.
376
377             NormalizedNode<?, ?> outerList = readStore(shard, TestModel.OUTER_LIST_PATH);
378             assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
379             assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
380                     outerList.getValue() instanceof Iterable);
381             Object entry = ((Iterable<Object>)outerList.getValue()).iterator().next();
382             assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
383                        entry instanceof MapEntryNode);
384             MapEntryNode mapEntry = (MapEntryNode)entry;
385             Optional<DataContainerChild<? extends PathArgument, ?>> idLeaf =
386                     mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
387             assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
388             assertEquals(TestModel.ID_QNAME.getLocalName() + " value", 1, idLeaf.get().getValue());
389
390             verifyLastApplied(shard, 2);
391
392             shard.tell(PoisonPill.getInstance(), ActorRef.noSender());
393         }};
394     }
395 }