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