Adjust for DataTreeCandidateNode API change
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / DataTreeCohortIntegrationTest.java
1 /*
2  * Copyright (c) 2016 Cisco 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;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertSame;
13 import static org.junit.Assert.fail;
14 import static org.mockito.ArgumentMatchers.any;
15 import static org.mockito.ArgumentMatchers.anyCollection;
16 import static org.mockito.Mockito.doReturn;
17 import static org.mockito.Mockito.mock;
18 import static org.mockito.Mockito.reset;
19 import static org.mockito.Mockito.verify;
20 import static org.mockito.Mockito.verifyNoMoreInteractions;
21
22 import akka.actor.ActorSystem;
23 import akka.actor.Address;
24 import akka.actor.AddressFromURIString;
25 import akka.cluster.Cluster;
26 import akka.testkit.javadsl.TestKit;
27 import com.google.common.base.Throwables;
28 import com.google.common.util.concurrent.FluentFuture;
29 import com.typesafe.config.ConfigFactory;
30 import java.util.Collection;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.TimeUnit;
33 import org.junit.AfterClass;
34 import org.junit.BeforeClass;
35 import org.junit.Ignore;
36 import org.junit.Test;
37 import org.mockito.ArgumentCaptor;
38 import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
39 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
40 import org.opendaylight.mdsal.common.api.DataValidationFailedException;
41 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
42 import org.opendaylight.mdsal.common.api.PostCanCommitStep;
43 import org.opendaylight.mdsal.common.api.PostPreCommitStep;
44 import org.opendaylight.mdsal.common.api.ThreePhaseCommitStep;
45 import org.opendaylight.mdsal.dom.api.DOMDataTreeCandidate;
46 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
47 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
48 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
49 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
50 import org.opendaylight.yangtools.concepts.ObjectRegistration;
51 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
52 import org.opendaylight.yangtools.yang.common.Uint64;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
57 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
58 import org.opendaylight.yangtools.yang.data.tree.api.ModificationType;
59 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
60
61 public class DataTreeCohortIntegrationTest {
62
63     private static final DataValidationFailedException FAILED_CAN_COMMIT =
64             new DataValidationFailedException(YangInstanceIdentifier.class, TestModel.TEST_PATH, "Test failure.");
65     private static final FluentFuture<PostCanCommitStep> FAILED_CAN_COMMIT_FUTURE =
66             FluentFutures.immediateFailedFluentFuture(FAILED_CAN_COMMIT);
67
68     private static final DOMDataTreeIdentifier TEST_ID =
69             new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH);
70
71     private static ActorSystem system;
72
73     private final DatastoreContext.Builder datastoreContextBuilder =
74             DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100);
75
76     @BeforeClass
77     public static void setUpClass() {
78         system = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
79         final Address member1Address = AddressFromURIString.parse("akka://cluster-test@127.0.0.1:2558");
80         Cluster.get(system).join(member1Address);
81     }
82
83     @AfterClass
84     public static void tearDownClass() {
85         TestKit.shutdownActorSystem(system);
86         system = null;
87     }
88
89     protected ActorSystem getSystem() {
90         return system;
91     }
92
93     @SuppressWarnings({ "unchecked", "rawtypes" })
94     @Test
95     public void testSuccessfulCanCommitWithNoopPostStep() throws Exception {
96         final DOMDataTreeCommitCohort cohort = mock(DOMDataTreeCommitCohort.class);
97         doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class),
98                 any(EffectiveModelContext.class), anyCollection());
99         ArgumentCaptor<Collection> candidateCapt = ArgumentCaptor.forClass(Collection.class);
100         IntegrationTestKit kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
101
102         try (AbstractDataStore dataStore = kit.setupAbstractDataStore(
103                 DistributedDataStore.class, "testSuccessfulCanCommitWithNoopPostStep", "test-1")) {
104             final ObjectRegistration<DOMDataTreeCommitCohort> cohortReg = dataStore.registerCommitCohort(TEST_ID,
105                     cohort);
106             assertNotNull(cohortReg);
107
108             IntegrationTestKit.verifyShardState(dataStore, "test-1",
109                 state -> assertEquals("Cohort registrations", 1, state.getCommitCohortActors().size()));
110
111             final ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
112             kit.testWriteTransaction(dataStore, TestModel.TEST_PATH, node);
113             verify(cohort).canCommit(any(Object.class), any(EffectiveModelContext.class), candidateCapt.capture());
114             assertDataTreeCandidate((DOMDataTreeCandidate) candidateCapt.getValue().iterator().next(), TEST_ID,
115                     ModificationType.WRITE, node, null);
116
117             reset(cohort);
118             doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class),
119                     any(EffectiveModelContext.class), anyCollection());
120
121             kit.testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
122                     ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
123                     .withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 42))
124                     .build());
125             verify(cohort).canCommit(any(Object.class), any(EffectiveModelContext.class), anyCollection());
126
127             cohortReg.close();
128
129             IntegrationTestKit.verifyShardState(dataStore, "test-1",
130                 state -> assertEquals("Cohort registrations", 0, state.getCommitCohortActors().size()));
131
132             kit.testWriteTransaction(dataStore, TestModel.TEST_PATH, node);
133             verifyNoMoreInteractions(cohort);
134         }
135     }
136
137     @Test
138     public void testFailedCanCommit() throws Exception {
139         final DOMDataTreeCommitCohort failedCohort = mock(DOMDataTreeCommitCohort.class);
140
141         doReturn(FAILED_CAN_COMMIT_FUTURE).when(failedCohort).canCommit(any(Object.class),
142                 any(EffectiveModelContext.class), anyCollection());
143
144         IntegrationTestKit kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
145         try (AbstractDataStore dataStore = kit.setupAbstractDataStore(
146                 DistributedDataStore.class, "testFailedCanCommit", "test-1")) {
147             dataStore.registerCommitCohort(TEST_ID, failedCohort);
148
149             IntegrationTestKit.verifyShardState(dataStore, "test-1",
150                 state -> assertEquals("Cohort registrations", 1, state.getCommitCohortActors().size()));
151
152             DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
153             writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
154             DOMStoreThreePhaseCommitCohort dsCohort = writeTx.ready();
155             try {
156                 dsCohort.canCommit().get(5, TimeUnit.SECONDS);
157                 fail("Exception should be raised.");
158             } catch (ExecutionException e) {
159                 assertSame(FAILED_CAN_COMMIT, Throwables.getRootCause(e));
160             }
161         }
162     }
163
164     @SuppressWarnings({ "unchecked", "rawtypes" })
165     @Test
166     public void testCanCommitWithListEntries() throws Exception {
167         final DOMDataTreeCommitCohort cohort = mock(DOMDataTreeCommitCohort.class);
168         doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class),
169                 any(EffectiveModelContext.class), anyCollection());
170         IntegrationTestKit kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
171
172         try (AbstractDataStore dataStore = kit.setupAbstractDataStore(
173                 DistributedDataStore.class, "testCanCommitWithMultipleListEntries", "cars-1")) {
174             final ObjectRegistration<DOMDataTreeCommitCohort> cohortReg = dataStore.registerCommitCohort(
175                     new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH
176                             .node(CarsModel.CAR_QNAME)), cohort);
177             assertNotNull(cohortReg);
178
179             IntegrationTestKit.verifyShardState(dataStore, "cars-1",
180                 state -> assertEquals("Cohort registrations", 1, state.getCommitCohortActors().size()));
181
182             // First write an empty base container and verify the cohort isn't invoked.
183
184             DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
185             writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
186             writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
187             kit.doCommit(writeTx.ready());
188             verifyNoMoreInteractions(cohort);
189
190             // Write a single car entry and verify the cohort is invoked.
191
192             writeTx = dataStore.newWriteOnlyTransaction();
193             final YangInstanceIdentifier optimaPath = CarsModel.newCarPath("optima");
194             final MapEntryNode optimaNode = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
195             writeTx.write(optimaPath, optimaNode);
196             kit.doCommit(writeTx.ready());
197
198             ArgumentCaptor<Collection> candidateCapture = ArgumentCaptor.forClass(Collection.class);
199             verify(cohort).canCommit(any(Object.class), any(EffectiveModelContext.class), candidateCapture.capture());
200             assertDataTreeCandidate((DOMDataTreeCandidate) candidateCapture.getValue().iterator().next(),
201                     new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, optimaPath), ModificationType.WRITE,
202                     optimaNode, null);
203
204             // Write replace the cars container with 2 new car entries. The cohort should get invoked with 3
205             // DOMDataTreeCandidates: once for each of the 2 new car entries (WRITE mod) and once for the deleted prior
206             // car entry (DELETE mod).
207
208             reset(cohort);
209             doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class),
210                     any(EffectiveModelContext.class), anyCollection());
211
212             writeTx = dataStore.newWriteOnlyTransaction();
213             final YangInstanceIdentifier sportagePath = CarsModel.newCarPath("sportage");
214             final MapEntryNode sportageNode = CarsModel.newCarEntry("sportage", Uint64.valueOf(20000));
215             final YangInstanceIdentifier soulPath = CarsModel.newCarPath("soul");
216             final MapEntryNode soulNode = CarsModel.newCarEntry("soul", Uint64.valueOf(20000));
217             writeTx.write(CarsModel.BASE_PATH, CarsModel.newCarsNode(CarsModel.newCarsMapNode(sportageNode,soulNode)));
218             kit.doCommit(writeTx.ready());
219
220             candidateCapture = ArgumentCaptor.forClass(Collection.class);
221             verify(cohort).canCommit(any(Object.class), any(EffectiveModelContext.class), candidateCapture.capture());
222
223             assertDataTreeCandidate(findCandidate(candidateCapture, sportagePath), new DOMDataTreeIdentifier(
224                     LogicalDatastoreType.CONFIGURATION, sportagePath), ModificationType.WRITE,
225                     sportageNode, null);
226
227             assertDataTreeCandidate(findCandidate(candidateCapture, soulPath), new DOMDataTreeIdentifier(
228                     LogicalDatastoreType.CONFIGURATION, soulPath), ModificationType.WRITE,
229                     soulNode, null);
230
231             assertDataTreeCandidate(findCandidate(candidateCapture, optimaPath), new DOMDataTreeIdentifier(
232                     LogicalDatastoreType.CONFIGURATION, optimaPath), ModificationType.DELETE,
233                     null, optimaNode);
234
235             // Delete the cars container - cohort should be invoked for the 2 deleted car entries.
236
237             reset(cohort);
238             doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class),
239                     any(EffectiveModelContext.class), anyCollection());
240
241             writeTx = dataStore.newWriteOnlyTransaction();
242             writeTx.delete(CarsModel.BASE_PATH);
243             kit.doCommit(writeTx.ready());
244
245             candidateCapture = ArgumentCaptor.forClass(Collection.class);
246             verify(cohort).canCommit(any(Object.class), any(EffectiveModelContext.class), candidateCapture.capture());
247
248             assertDataTreeCandidate(findCandidate(candidateCapture, sportagePath), new DOMDataTreeIdentifier(
249                     LogicalDatastoreType.CONFIGURATION, sportagePath), ModificationType.DELETE,
250                     null, sportageNode);
251
252             assertDataTreeCandidate(findCandidate(candidateCapture, soulPath), new DOMDataTreeIdentifier(
253                     LogicalDatastoreType.CONFIGURATION, soulPath), ModificationType.DELETE,
254                     null, soulNode);
255
256         }
257     }
258
259     @SuppressWarnings("rawtypes")
260     private static DOMDataTreeCandidate findCandidate(final ArgumentCaptor<Collection> candidateCapture,
261             final YangInstanceIdentifier rootPath) {
262         for (Object obj: candidateCapture.getValue()) {
263             DOMDataTreeCandidate candidate = (DOMDataTreeCandidate)obj;
264             if (rootPath.equals(candidate.getRootPath().getRootIdentifier())) {
265                 return candidate;
266             }
267         }
268
269         return null;
270     }
271
272     /**
273      * FIXME: Since we invoke DOMDataTreeCommitCohort#canCommit on preCommit (as that's when we generate a
274      * DataTreeCandidate) and since currently preCommit is a noop in the Shard backend (it is combined with commit),
275      * we can't actually test abort after canCommit.
276      */
277     @Test
278     @Ignore
279     public void testAbortAfterCanCommit() throws Exception {
280         final DOMDataTreeCommitCohort cohortToAbort = mock(DOMDataTreeCommitCohort.class);
281         final PostCanCommitStep stepToAbort = mock(PostCanCommitStep.class);
282         doReturn(ThreePhaseCommitStep.NOOP_ABORT_FUTURE).when(stepToAbort).abort();
283         doReturn(PostPreCommitStep.NOOP_FUTURE).when(stepToAbort).preCommit();
284         doReturn(FluentFutures.immediateFluentFuture(stepToAbort)).when(cohortToAbort).canCommit(any(Object.class),
285                 any(EffectiveModelContext.class), anyCollection());
286
287         IntegrationTestKit kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
288         try (AbstractDataStore dataStore = kit.setupAbstractDataStore(
289                 DistributedDataStore.class, "testAbortAfterCanCommit", "test-1", "cars-1")) {
290             dataStore.registerCommitCohort(TEST_ID, cohortToAbort);
291
292             IntegrationTestKit.verifyShardState(dataStore, "test-1",
293                 state -> assertEquals("Cohort registrations", 1, state.getCommitCohortActors().size()));
294
295             DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
296             writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
297             writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
298             DOMStoreThreePhaseCommitCohort dsCohort = writeTx.ready();
299
300             dsCohort.canCommit().get(5, TimeUnit.SECONDS);
301             dsCohort.preCommit().get(5, TimeUnit.SECONDS);
302             dsCohort.abort().get(5, TimeUnit.SECONDS);
303             verify(stepToAbort).abort();
304         }
305     }
306
307     private static void assertDataTreeCandidate(final DOMDataTreeCandidate candidate,
308             final DOMDataTreeIdentifier expTreeId, final ModificationType expType,
309             final NormalizedNode expDataAfter, final NormalizedNode expDataBefore) {
310         assertNotNull("Expected candidate for path " + expTreeId.getRootIdentifier(), candidate);
311         assertEquals("rootPath", expTreeId, candidate.getRootPath());
312         assertEquals("modificationType", expType, candidate.getRootNode().modificationType());
313         assertEquals("dataAfter", expDataAfter, candidate.getRootNode().dataAfter());
314         assertEquals("dataBefore", expDataBefore, candidate.getRootNode().dataBefore());
315     }
316 }