Merge "Bug 6110: Fixed bugs in statistics manager due to race condition." into stable...
[openflowplugin.git] / openflowplugin-impl / src / test / java / org / opendaylight / openflowplugin / impl / services / MultipartRequestOnTheFlyCallbackTest.java
1 /*
2  * Copyright (c) 2015 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.openflowplugin.impl.services;
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.Matchers.eq;
14 import static org.mockito.Mockito.mock;
15 import static org.mockito.Mockito.spy;
16 import static org.mockito.Mockito.times;
17 import static org.mockito.Mockito.verify;
18 import static org.mockito.Mockito.when;
19
20 import com.google.common.base.Optional;
21 import com.google.common.util.concurrent.CheckedFuture;
22 import com.google.common.util.concurrent.Futures;
23 import java.math.BigInteger;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.concurrent.ExecutionException;
27 import org.junit.Before;
28 import org.junit.Test;
29 import org.junit.runner.RunWith;
30 import org.mockito.Matchers;
31 import org.mockito.Mock;
32 import org.mockito.Mockito;
33 import org.mockito.runners.MockitoJUnitRunner;
34 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
35 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
36 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
37 import org.opendaylight.openflowplugin.api.OFConstants;
38 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
39 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
40 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
41 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
42 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
43 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
44 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
45 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
46 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.EventIdentifier;
47 import org.opendaylight.openflowplugin.impl.rpc.AbstractRequestContext;
48 import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.MessageIntelligenceAgencyImpl;
49 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
50 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.FlowModFlags;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntry;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.MatchBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyFlowCaseBuilder;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.flow._case.MultipartReplyFlowBuilder;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.flow._case.multipart.reply.flow.FlowStatsBuilder;
73 import org.opendaylight.yangtools.yang.binding.DataObject;
74 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
75 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
76 import org.opendaylight.yangtools.yang.common.RpcError;
77 import org.opendaylight.yangtools.yang.common.RpcResult;
78 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
79
80 @RunWith(MockitoJUnitRunner.class)
81 public class MultipartRequestOnTheFlyCallbackTest {
82
83     private static final String DUMMY_NODE_ID = "dummyNodeId";
84     private static final String DUMMY_EVENT_NAME = "dummy event name 1";
85     private static final String DUMMY_DEVICE_ID = "dummy device id 1";
86     private static final Long DUMMY_XID = 55L;
87     private static final KeyedInstanceIdentifier<Node, NodeKey> NODE_PATH = KeyedInstanceIdentifier
88             .create(Nodes.class)
89             .child(Node.class, new NodeKey(new NodeId("uf-node:123")));
90
91     @Mock
92     private DeviceContext mockedDeviceContext;
93     @Mock
94     private RequestContext<List<MultipartReply>> mockedRequestContext;
95     @Mock
96     private ConnectionContext mockedPrimaryConnection;
97     @Mock
98     private NodeId mockedNodeId;
99     @Mock
100     private FeaturesReply mockedFeaturesReply;
101     @Mock
102     private DeviceState mockedDeviceState;
103     @Mock
104     private DeviceInfo mockedDeviceInfo;
105     @Mock
106     private GetFeaturesOutput mocketGetFeaturesOutput;
107     @Mock
108     private DeviceFlowRegistry mockedFlowRegistry;
109     @Mock
110     private FlowDescriptor mockedFlowDescriptor;
111     @Mock
112     private ReadOnlyTransaction mockedReadOnlyTx;
113
114     private AbstractRequestContext<List<MultipartReply>> dummyRequestContext;
115     private final EventIdentifier dummyEventIdentifier = new EventIdentifier(DUMMY_EVENT_NAME, DUMMY_DEVICE_ID);
116     private MultipartRequestOnTheFlyCallback multipartRequestOnTheFlyCallback;
117     private final short tableId = 0;
118
119     @Before
120     public void initialization() throws Exception{
121         when(mockedDeviceContext.getMessageSpy()).thenReturn(new MessageIntelligenceAgencyImpl());
122         when(mockedNodeId.toString()).thenReturn(DUMMY_NODE_ID);
123         when(mockedPrimaryConnection.getNodeId()).thenReturn(mockedNodeId);
124         when(mockedPrimaryConnection.getFeatures()).thenReturn(mockedFeaturesReply);
125         when(mockedFeaturesReply.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
126         when(mockedFeaturesReply.getDatapathId()).thenReturn(BigInteger.valueOf(123L));
127
128         when(mocketGetFeaturesOutput.getTables()).thenReturn(tableId);
129         when(mocketGetFeaturesOutput.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
130         when(mocketGetFeaturesOutput.getDatapathId()).thenReturn(BigInteger.valueOf(123L));
131
132         when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedPrimaryConnection);
133         when(mockedDeviceInfo.getNodeInstanceIdentifier()).thenReturn(NODE_PATH);
134         when(mockedDeviceInfo.getNodeId()).thenReturn(mockedNodeId);
135         when(mockedDeviceInfo.getDatapathId()).thenReturn(BigInteger.TEN);
136         when(mockedDeviceInfo.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
137
138         when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
139         when(mockedDeviceContext.getDeviceInfo()).thenReturn(mockedDeviceInfo);
140         when(mockedDeviceContext.getDeviceFlowRegistry()).thenReturn(mockedFlowRegistry);
141         when(mockedFlowRegistry.retrieveIdForFlow(Matchers.any(FlowRegistryKey.class))).thenReturn(mockedFlowDescriptor);
142
143         final InstanceIdentifier<FlowCapableNode> nodePath = mockedDeviceInfo.getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
144         final FlowCapableNodeBuilder flowNodeBuilder = new FlowCapableNodeBuilder();
145         flowNodeBuilder.setTable(Collections.<Table> emptyList());
146         final Optional<FlowCapableNode> flowNodeOpt = Optional.of(flowNodeBuilder.build());
147
148         final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowNodeFuture = Futures.immediateCheckedFuture(flowNodeOpt);
149         final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowNodeFutureSpy = spy(flowNodeFuture);
150         when(mockedReadOnlyTx.read(LogicalDatastoreType.OPERATIONAL, nodePath)).thenReturn(flowNodeFutureSpy);
151         when(flowNodeFutureSpy.get()).thenReturn(flowNodeOpt);
152         when(mockedDeviceContext.getReadTransaction()).thenReturn(mockedReadOnlyTx);
153
154         dummyRequestContext = new AbstractRequestContext<List<MultipartReply>>(DUMMY_XID) {
155
156             @Override
157             public void close() {
158                 //NOOP
159             }
160         };
161
162         final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();
163         multipartRequestOnTheFlyCallback = new MultipartRequestOnTheFlyCallback(dummyRequestContext, String.class,
164                 mockedDeviceContext.getMessageSpy(),dummyEventIdentifier, mockedDeviceInfo,
165                 mockedDeviceContext.getDeviceFlowRegistry(), mockedDeviceContext, convertorManager);
166     }
167
168
169     @Test
170     public void testOnSuccessWithNull() throws Exception {
171         multipartRequestOnTheFlyCallback.onSuccess(null);
172         final RpcResult<List<MultipartReply>> expectedRpcResult = RpcResultBuilder.success(Collections.<MultipartReply>emptyList()).build();
173         final RpcResult<List<MultipartReply>> actualResult = dummyRequestContext.getFuture().get();
174         assertEquals(expectedRpcResult.getErrors(), actualResult.getErrors());
175         assertEquals(expectedRpcResult.getResult(), actualResult.getResult());
176         assertEquals(expectedRpcResult.isSuccessful(), actualResult.isSuccessful());
177     }
178
179     @Test
180     public void testOnSuccessWithNotMultiNoMultipart() throws Exception {
181         final HelloMessage mockedHelloMessage = mock(HelloMessage.class);
182         multipartRequestOnTheFlyCallback.onSuccess(mockedHelloMessage);
183
184         final RpcResult<List<MultipartReply>> expectedRpcResult =
185                 RpcResultBuilder.<List<MultipartReply>>failed().withError(RpcError.ErrorType.APPLICATION,
186                         String.format("Unexpected response type received %s.", mockedHelloMessage.getClass())).build();
187         final RpcResult<List<MultipartReply>> actualResult = dummyRequestContext.getFuture().get();
188         assertNotNull(actualResult.getErrors());
189         assertEquals(1, actualResult.getErrors().size());
190
191         final RpcError actualError = actualResult.getErrors().iterator().next();
192         assertEquals(actualError.getMessage(), String.format("Unexpected response type received %s.", mockedHelloMessage.getClass()));
193         assertEquals(actualError.getErrorType(),RpcError.ErrorType.APPLICATION);
194         assertEquals(expectedRpcResult.getResult(), actualResult.getResult());
195         assertEquals(expectedRpcResult.isSuccessful(), actualResult.isSuccessful());
196
197         Mockito.verify(mockedDeviceContext, Mockito.never()).writeToTransaction(Matchers.eq(LogicalDatastoreType.OPERATIONAL),
198                 Matchers.<InstanceIdentifier>any(), Matchers.<DataObject>any());
199         Mockito.verify(mockedDeviceContext).submitTransaction();
200     }
201
202     /**
203      * not the last reply
204      *
205      * @throws ExecutionException
206      * @throws InterruptedException
207      */
208     @Test
209     public void testOnSuccessWithValidMultipart1() throws Exception {
210         final MatchBuilder matchBuilder = new MatchBuilder()
211                 .setMatchEntry(Collections.<MatchEntry>emptyList());
212         final FlowStatsBuilder flowStatsBuilder = new FlowStatsBuilder()
213                 .setTableId(tableId)
214                 .setPriority(2)
215                 .setCookie(BigInteger.ZERO)
216                 .setByteCount(BigInteger.TEN)
217                 .setPacketCount(BigInteger.ONE)
218                 .setDurationSec(11L)
219                 .setDurationNsec(12L)
220                 .setMatch(matchBuilder.build())
221                 .setFlags(new FlowModFlags(true, false, false, false, false));
222         final MultipartReplyFlowBuilder multipartReplyFlowBuilder = new MultipartReplyFlowBuilder()
223                 .setFlowStats(Collections.singletonList(flowStatsBuilder.build()));
224         final MultipartReplyFlowCaseBuilder multipartReplyFlowCaseBuilder = new MultipartReplyFlowCaseBuilder()
225                 .setMultipartReplyFlow(multipartReplyFlowBuilder.build());
226         final MultipartReplyMessageBuilder mpReplyMessage = new MultipartReplyMessageBuilder()
227                 .setType(MultipartType.OFPMPFLOW)
228                 .setFlags(new MultipartRequestFlags(true))
229                 .setMultipartReplyBody(multipartReplyFlowCaseBuilder.build())
230                 .setXid(21L);
231
232         final InstanceIdentifier<FlowCapableNode> nodePath = mockedDeviceInfo.getNodeInstanceIdentifier()
233                 .augmentation(FlowCapableNode.class);
234         final FlowCapableNodeBuilder flowNodeBuilder = new FlowCapableNodeBuilder();
235         final TableBuilder tableDataBld = new TableBuilder();
236         tableDataBld.setId(tableId);
237         flowNodeBuilder.setTable(Collections.singletonList(tableDataBld.build()));
238         final Optional<FlowCapableNode> flowNodeOpt = Optional.of(flowNodeBuilder.build());
239         final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowNodeFuture = Futures
240                 .immediateCheckedFuture(flowNodeOpt);
241         final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowNodeFutureSpy = spy(flowNodeFuture);
242
243         when(mockedReadOnlyTx.read(LogicalDatastoreType.OPERATIONAL, nodePath)).thenReturn(flowNodeFutureSpy);
244         when(flowNodeFutureSpy.get()).thenReturn(flowNodeOpt);
245         when(mockedDeviceContext.getReadTransaction()).thenReturn(mockedReadOnlyTx);
246
247         multipartRequestOnTheFlyCallback.onSuccess(mpReplyMessage.build());
248         final InstanceIdentifier<Table> tableIdent = nodePath.child(Table.class, new TableKey(tableId));
249
250         verify(mockedReadOnlyTx, times(1)).read(LogicalDatastoreType.OPERATIONAL, nodePath);
251         verify(mockedReadOnlyTx, times(1)).close();
252         verify(mockedDeviceContext, times(1)).writeToTransaction(eq(LogicalDatastoreType.OPERATIONAL),
253                 eq(tableIdent), Matchers.<Table> any());
254         /*
255          * One call for Table one call for Flow
256          * we are not able to create Flow InstanceIdentifier because we are missing FlowId
257          */
258         verify(mockedDeviceContext, times(2)).writeToTransaction(eq(LogicalDatastoreType.OPERATIONAL),
259                 Matchers.<InstanceIdentifier> any(), Matchers.<DataObject> any());
260     }
261
262     /**
263      * the last reply
264      *
265      * @throws ExecutionException
266      * @throws InterruptedException
267      */
268     @Test
269     public void testOnSuccessWithValidMultipart2() throws Exception {
270         final MatchBuilder matchBuilder = new MatchBuilder()
271                 .setMatchEntry(Collections.<MatchEntry>emptyList());
272         final FlowStatsBuilder flowStatsBuilder = new FlowStatsBuilder()
273                 .setTableId(tableId)
274                 .setPriority(2)
275                 .setCookie(BigInteger.ZERO)
276                 .setByteCount(BigInteger.TEN)
277                 .setPacketCount(BigInteger.ONE)
278                 .setDurationSec(11L)
279                 .setDurationNsec(12L)
280                 .setMatch(matchBuilder.build())
281                 .setFlags(new FlowModFlags(true, false, false, false, false));
282         final MultipartReplyFlowBuilder multipartReplyFlowBuilder = new MultipartReplyFlowBuilder()
283                 .setFlowStats(Collections.singletonList(flowStatsBuilder.build()));
284         final MultipartReplyFlowCaseBuilder multipartReplyFlowCaseBuilder = new MultipartReplyFlowCaseBuilder()
285                 .setMultipartReplyFlow(multipartReplyFlowBuilder.build());
286         final MultipartReplyMessageBuilder mpReplyMessage = new MultipartReplyMessageBuilder()
287                 .setType(MultipartType.OFPMPFLOW)
288                 .setFlags(new MultipartRequestFlags(false))
289                 .setMultipartReplyBody(multipartReplyFlowCaseBuilder.build())
290                 .setXid(21L);
291
292         final InstanceIdentifier<FlowCapableNode> nodePath = mockedDeviceInfo.getNodeInstanceIdentifier()
293                 .augmentation(FlowCapableNode.class);
294         final FlowCapableNodeBuilder flowNodeBuilder = new FlowCapableNodeBuilder();
295         final TableBuilder tableDataBld = new TableBuilder();
296         tableDataBld.setId(tableId);
297         flowNodeBuilder.setTable(Collections.singletonList(tableDataBld.build()));
298         final Optional<FlowCapableNode> flowNodeOpt = Optional.of(flowNodeBuilder.build());
299         final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowNodeFuture = Futures
300                 .immediateCheckedFuture(flowNodeOpt);
301         final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowNodeFutureSpy = spy(flowNodeFuture);
302
303         when(mockedReadOnlyTx.read(LogicalDatastoreType.OPERATIONAL, nodePath)).thenReturn(flowNodeFutureSpy);
304         when(flowNodeFutureSpy.get()).thenReturn(flowNodeOpt);
305         when(mockedDeviceContext.getReadTransaction()).thenReturn(mockedReadOnlyTx);
306
307         multipartRequestOnTheFlyCallback.onSuccess(mpReplyMessage.build());
308         final InstanceIdentifier<Table> tableIdent = nodePath.child(Table.class, new TableKey(tableId));
309
310         verify(mockedReadOnlyTx, times(1)).read(LogicalDatastoreType.OPERATIONAL, nodePath);
311         verify(mockedReadOnlyTx, times(1)).close();
312         verify(mockedDeviceContext, times(1)).writeToTransaction(eq(LogicalDatastoreType.OPERATIONAL),
313                 eq(tableIdent), Matchers.<Table> any());
314         /*
315          * One call for Table one call for Flow
316          * we are not able to create Flow InstanceIdentifier because we are missing FlowId
317          */
318         verify(mockedDeviceContext, times(2)).writeToTransaction(eq(LogicalDatastoreType.OPERATIONAL),
319                 Matchers.<InstanceIdentifier> any(), Matchers.<DataObject> any());
320     }
321 }