Encapsulate OpenFlowPlugin configuration
[openflowplugin.git] / openflowplugin-impl / src / test / java / org / opendaylight / openflowplugin / impl / statistics / StatisticsManagerImplTest.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.statistics;
9
10 import static org.mockito.Mockito.times;
11 import static org.mockito.Mockito.verify;
12 import static org.mockito.Mockito.when;
13
14 import com.google.common.util.concurrent.Futures;
15 import io.netty.util.HashedWheelTimer;
16 import io.netty.util.Timeout;
17 import java.lang.reflect.Field;
18 import java.math.BigInteger;
19 import java.util.Collections;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.concurrent.ExecutionException;
23 import java.util.concurrent.Future;
24 import org.junit.Assert;
25 import org.junit.Before;
26 import org.junit.Test;
27 import org.junit.runner.RunWith;
28 import org.mockito.ArgumentCaptor;
29 import org.mockito.Captor;
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.DataBroker;
35 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
36 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
37 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
38 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
39 import org.opendaylight.openflowplugin.api.OFConstants;
40 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
41 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
42 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
43 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
44 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
45 import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
46 import org.opendaylight.openflowplugin.api.openflow.registry.ItemLifeCycleRegistry;
47 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
48 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
49 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
50 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
51 import org.opendaylight.openflowplugin.impl.registry.flow.DeviceFlowRegistryImpl;
52 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
53 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
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.protocol.rev130731.FeaturesReply;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.provider.config.rev160510.NonZeroUint32Type;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.provider.config.rev160510.OpenflowProviderConfigBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.ChangeStatisticsWorkModeInputBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsManagerControlService;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsWorkMode;
66 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
67 import org.opendaylight.yangtools.yang.common.RpcResult;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71
72 @RunWith(MockitoJUnitRunner.class)
73 public class StatisticsManagerImplTest {
74
75     private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImplTest.class);
76
77     public static final NodeId NODE_ID = new NodeId("ofp-unit-dummy-node-id");
78
79     @Mock
80     private ConnectionContext mockedPrimConnectionContext;
81     @Mock
82     private FeaturesReply mockedFeatures;
83     @Mock
84     private ConnectionAdapter mockedConnectionAdapter;
85     @Mock
86     private MessageSpy mockedMessagSpy;
87     @Mock
88     private DeviceContext mockedDeviceContext;
89     @Mock
90     private DeviceState mockedDeviceState;
91     @Mock
92     private DeviceInfo mockedDeviceInfo;
93     @Mock
94     private RpcProviderRegistry rpcProviderRegistry;
95     @Mock
96     private OutboundQueue outboundQueue;
97     @Mock
98     private MultiMsgCollector multiMagCollector;
99     @Mock
100     private ItemLifeCycleRegistry itemLifeCycleRegistry;
101     @Captor
102     private ArgumentCaptor<ItemLifecycleListener> itemLifeCycleListenerCapt;
103     @Mock
104     private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> serviceControlRegistration;
105     @Mock
106     private DeviceInfo deviceInfo;
107     @Mock
108     private DataBroker dataBroker;
109
110     private RequestContext<List<MultipartReply>> currentRequestContext;
111     private StatisticsManagerImpl statisticsManager;
112
113
114     @Before
115     public void initialization() {
116         final KeyedInstanceIdentifier<Node, NodeKey> nodePath = KeyedInstanceIdentifier
117                 .create(Nodes.class)
118                 .child(Node.class, new NodeKey(new NodeId("openflow:10")));
119
120         when(mockedPrimConnectionContext.getFeatures()).thenReturn(mockedFeatures);
121         when(mockedPrimConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
122         when(mockedPrimConnectionContext.getConnectionState()).thenReturn(ConnectionContext.CONNECTION_STATE.WORKING);
123         when(mockedPrimConnectionContext.getNodeId()).thenReturn(NODE_ID);
124         when(mockedPrimConnectionContext.getOutboundQueueProvider()).thenReturn(outboundQueue);
125
126         when(mockedDeviceState.isFlowStatisticsAvailable()).thenReturn(Boolean.TRUE);
127         when(mockedDeviceState.isGroupAvailable()).thenReturn(Boolean.TRUE);
128         when(mockedDeviceState.isMetersAvailable()).thenReturn(Boolean.TRUE);
129         when(mockedDeviceState.isPortStatisticsAvailable()).thenReturn(Boolean.TRUE);
130         when(mockedDeviceState.isQueueStatisticsAvailable()).thenReturn(Boolean.TRUE);
131         when(mockedDeviceState.isTableStatisticsAvailable()).thenReturn(Boolean.TRUE);
132         when(mockedDeviceInfo.getNodeInstanceIdentifier()).thenReturn(nodePath);
133         when(mockedDeviceInfo.getDatapathId()).thenReturn(BigInteger.TEN);
134         when(mockedDeviceInfo.getNodeId()).thenReturn(NODE_ID);
135
136         when(mockedDeviceContext.getDeviceInfo()).thenReturn(mockedDeviceInfo);
137         when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedPrimConnectionContext);
138         when(mockedDeviceContext.getMessageSpy()).thenReturn(mockedMessagSpy);
139         when(mockedDeviceContext.getDeviceFlowRegistry()).thenReturn(new DeviceFlowRegistryImpl(OFConstants.OFP_VERSION_1_3, dataBroker, nodePath));
140         when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
141         when(mockedDeviceContext.getMultiMsgCollector(
142                 Matchers.<RequestContext<List<MultipartReply>>>any())).thenAnswer(
143                 invocation -> {
144                     currentRequestContext = (RequestContext<List<MultipartReply>>) invocation.getArguments()[0];
145                     return multiMagCollector;
146                 }
147         );
148         when(mockedDeviceContext.getItemLifeCycleSourceRegistry()).thenReturn(itemLifeCycleRegistry);
149         when(rpcProviderRegistry.addRpcImplementation(
150                 Matchers.eq(StatisticsManagerControlService.class),
151                 Matchers.<StatisticsManagerControlService>any())).thenReturn(serviceControlRegistration);
152
153         final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();
154         final long basicTimerDelay = 3000L;
155         final long maximumTimerDelay = 900000L;
156
157         statisticsManager = new StatisticsManagerImpl(
158                 new OpenflowProviderConfigBuilder()
159                         .setBasicTimerDelay(new NonZeroUint32Type(basicTimerDelay))
160                         .setMaximumTimerDelay(new NonZeroUint32Type(maximumTimerDelay))
161                         .setIsStatisticsPollingOn(false)
162                         .build(), rpcProviderRegistry, new HashedWheelTimer(),
163                 convertorManager);
164     }
165
166     private static Map<DeviceInfo, StatisticsContext> getContextsMap(final StatisticsManagerImpl statisticsManager)
167             throws NoSuchFieldException, IllegalAccessException {
168         // HACK: contexts map for testing shall be accessed in some more civilized way
169         final Field contextsField = StatisticsManagerImpl.class.getDeclaredField("contexts");
170         Assert.assertNotNull(contextsField);
171         contextsField.setAccessible(true);
172         return (Map<DeviceInfo, StatisticsContext>) contextsField.get(statisticsManager);
173     }
174
175     @Test
176     public void testGetStatisticsWorkMode() throws Exception {
177         final Future<RpcResult<GetStatisticsWorkModeOutput>> workMode = statisticsManager.getStatisticsWorkMode();
178         Assert.assertTrue(workMode.isDone());
179         Assert.assertTrue(workMode.get().isSuccessful());
180         Assert.assertNotNull(workMode.get().getResult());
181         Assert.assertEquals(StatisticsWorkMode.COLLECTALL, workMode.get().getResult().getMode());
182     }
183
184     /**
185      * switching to {@link StatisticsWorkMode#FULLYDISABLED}; no pollTimeout and no lifecycleRegistry
186      *
187      * @throws Exception
188      */
189     @Test
190     public void testChangeStatisticsWorkMode1() throws Exception {
191         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
192         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
193                 Collections.<ItemLifeCycleSource>emptyList());
194
195         when(statisticContext.gainDeviceContext()).thenReturn(mockedDeviceContext);
196         when(statisticContext.gainDeviceState()).thenReturn(mockedDeviceState);
197
198         getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
199
200         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
201                 new ChangeStatisticsWorkModeInputBuilder()
202                         .setMode(StatisticsWorkMode.FULLYDISABLED);
203
204         final Future<RpcResult<Void>> workMode = statisticsManager
205                 .changeStatisticsWorkMode(changeStatisticsWorkModeInputBld.build());
206
207         checkWorkModeChangeOutcome(workMode);
208         verify(itemLifeCycleRegistry).getLifeCycleSources();
209         verify(statisticContext).stopGatheringData();
210     }
211
212     private static void checkWorkModeChangeOutcome(Future<RpcResult<Void>> workMode) throws InterruptedException, ExecutionException {
213         Assert.assertTrue(workMode.isDone());
214         Assert.assertTrue(workMode.get().isSuccessful());
215     }
216
217
218     /**
219      * switching to {@link StatisticsWorkMode#FULLYDISABLED}; with pollTimeout and lifecycleRegistry
220      *
221      * @throws Exception
222      */
223     @Test
224     public void testChangeStatisticsWorkMode2() throws Exception {
225         final Timeout pollTimeout = Mockito.mock(Timeout.class);
226         final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
227         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
228         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
229                 Collections.singletonList(itemLifecycleSource));
230
231         getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
232
233         when(statisticContext.gainDeviceContext()).thenReturn(mockedDeviceContext);
234         when(statisticContext.gainDeviceState()).thenReturn(mockedDeviceState);
235 //        when(lifecycleService.getDeviceContext()).thenReturn(mockedDeviceContext);
236
237         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
238                 new ChangeStatisticsWorkModeInputBuilder()
239                         .setMode(StatisticsWorkMode.FULLYDISABLED);
240
241         Future<RpcResult<Void>> workMode = statisticsManager.changeStatisticsWorkMode(changeStatisticsWorkModeInputBld.build());
242         checkWorkModeChangeOutcome(workMode);
243
244         verify(itemLifeCycleRegistry).getLifeCycleSources();
245         verify(statisticContext).stopGatheringData();
246         verify(itemLifecycleSource).setItemLifecycleListener(Matchers.<ItemLifecycleListener>any());
247     }
248
249     /**
250      * switching to {@link StatisticsWorkMode#FULLYDISABLED} and back
251      * to {@link StatisticsWorkMode#COLLECTALL}; with lifecycleRegistry and pollTimeout
252      *
253      * @throws Exception
254      */
255     @Test
256     public void testChangeStatisticsWorkMode3() throws Exception {
257         final Timeout pollTimeout = Mockito.mock(Timeout.class);
258         final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
259         Mockito.doNothing().when(itemLifecycleSource)
260                 .setItemLifecycleListener(itemLifeCycleListenerCapt.capture());
261
262         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
263         when(statisticContext.getItemLifeCycleListener()).thenReturn(
264                 Mockito.mock(ItemLifecycleListener.class));
265         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
266                 Collections.singletonList(itemLifecycleSource));
267
268         getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
269
270         when(statisticContext.gainDeviceContext()).thenReturn(mockedDeviceContext);
271         when(statisticContext.gainDeviceState()).thenReturn(mockedDeviceState);
272 //        when(lifecycleService.getDeviceContext()).thenReturn(mockedDeviceContext);
273
274         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
275                 new ChangeStatisticsWorkModeInputBuilder()
276                         .setMode(StatisticsWorkMode.FULLYDISABLED);
277
278         Future<RpcResult<Void>> workMode;
279         workMode = statisticsManager.changeStatisticsWorkMode(
280                 changeStatisticsWorkModeInputBld.build());
281         checkWorkModeChangeOutcome(workMode);
282
283         changeStatisticsWorkModeInputBld.setMode(StatisticsWorkMode.COLLECTALL);
284         workMode = statisticsManager.changeStatisticsWorkMode(
285                 changeStatisticsWorkModeInputBld.build());
286         checkWorkModeChangeOutcome(workMode);
287
288         verify(itemLifeCycleRegistry, times(2)).getLifeCycleSources();
289         verify(statisticContext).stopGatheringData();
290
291         final List<ItemLifecycleListener> itemLifeCycleListenerValues = itemLifeCycleListenerCapt.getAllValues();
292         Assert.assertEquals(2, itemLifeCycleListenerValues.size());
293         Assert.assertNotNull(itemLifeCycleListenerValues.get(0));
294         Assert.assertNull(itemLifeCycleListenerValues.get(1));
295     }
296
297     @Test
298     public void testClose() throws Exception {
299         statisticsManager.close();
300         verify(serviceControlRegistration).close();
301     }
302
303     @Test
304     public void testCalculateTimerDelay() throws Exception {
305         final TimeCounter timeCounter = Mockito.mock(TimeCounter.class);
306         when(timeCounter.getAverageTimeBetweenMarks()).thenReturn(2000L, (Long)4000L);
307         statisticsManager.calculateTimerDelay(timeCounter);
308         Assert.assertEquals(3000L, statisticsManager.getCurrentTimerDelay());
309         statisticsManager.calculateTimerDelay(timeCounter);
310         Assert.assertEquals(6000L, statisticsManager.getCurrentTimerDelay());
311     }
312
313     @Test
314     public void testPollStatistics() throws Exception {
315         final StatisticsContext statisticsContext = Mockito.mock(StatisticsContext.class);
316         final TimeCounter mockTimerCounter = Mockito.mock(TimeCounter.class);
317
318         statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
319         verify(mockedDeviceContext).getDeviceState();
320
321         statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
322
323         statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
324
325         when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateCheckedFuture(Boolean.TRUE));
326         when(statisticsContext.isSchedulingEnabled()).thenReturn(Boolean.TRUE);
327         statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
328         verify(mockTimerCounter).markStart();
329         verify(mockTimerCounter).addTimeMark();
330
331         when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateFailedFuture(new Throwable("error msg")));
332         statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
333         verify(mockTimerCounter,times(2)).addTimeMark();
334     }
335 }