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