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