2d732f13a425c827406c75ccd37b96c795446de8
[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 import com.google.common.base.Optional;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import io.netty.util.HashedWheelTimer;
17 import io.netty.util.Timeout;
18 import java.lang.reflect.Field;
19 import java.math.BigInteger;
20 import java.util.Collections;
21 import java.util.List;
22 import java.util.Map;
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.invocation.InvocationOnMock;
34 import org.mockito.runners.MockitoJUnitRunner;
35 import org.mockito.stubbing.Answer;
36 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
37 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
38 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
39 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
40 import org.opendaylight.openflowplugin.api.OFConstants;
41 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
42 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
43 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
44 import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
45 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
46 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
47 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
48 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
49 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
50 import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
51 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
52 import org.opendaylight.openflowplugin.api.openflow.registry.ItemLifeCycleRegistry;
53 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
54 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
55 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
56 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
57 import org.opendaylight.openflowplugin.impl.registry.flow.DeviceFlowRegistryImpl;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.ChangeStatisticsWorkModeInputBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsManagerControlService;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsWorkMode;
71 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
72 import org.opendaylight.yangtools.yang.common.RpcResult;
73 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
76
77
78 @RunWith(MockitoJUnitRunner.class)
79 public class StatisticsManagerImplTest {
80
81     private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImplTest.class);
82
83     private static final BigInteger DUMMY_DATAPATH_ID = new BigInteger("444");
84     private static final Short DUMMY_VERSION = OFConstants.OFP_VERSION_1_3;
85     public static final NodeId NODE_ID = new NodeId("ofp-unit-dummy-node-id");
86
87     @Mock
88     RequestContextStack mockedRequestContextStack;
89     @Mock
90     ConnectionContext mockedPrimConnectionContext;
91     @Mock
92     FeaturesReply mockedFeatures;
93     @Mock
94     GetFeaturesOutput mockedFeaturesOutput;
95     @Mock
96     ConnectionAdapter mockedConnectionAdapter;
97     @Mock
98     MessageSpy mockedMessagSpy;
99     @Mock
100     DeviceContext mockedDeviceContext;
101     @Mock
102     DeviceState mockedDeviceState;
103     @Mock
104     DeviceInitializationPhaseHandler mockedDevicePhaseHandler;
105     @Mock
106     DeviceTerminationPhaseHandler mockedTerminationPhaseHandler;
107     @Mock
108     private RpcProviderRegistry rpcProviderRegistry;
109     @Mock
110     private HashedWheelTimer hashedWheelTimer;
111     @Mock
112     private OutboundQueue outboundQueue;
113     @Mock
114     private MultiMsgCollector multiMagCollector;
115     @Mock
116     private ItemLifeCycleRegistry itemLifeCycleRegistry;
117     @Captor
118     private ArgumentCaptor<ItemLifecycleListener> itemLifeCycleListenerCapt;
119     @Mock
120     private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> serviceControlRegistration;
121     @Mock
122     private DeviceManager deviceManager;
123     @Mock
124     private LifecycleConductor conductor;
125     @Mock
126     private GetFeaturesOutput featuresOutput;
127     @Mock
128     private DeviceInitializationPhaseHandler deviceInitializationPhaseHandler;
129     @Mock
130     private DeviceInfo deviceInfo;
131
132     private RequestContext<List<MultipartReply>> currentRequestContext;
133     private StatisticsManagerImpl statisticsManager;
134
135
136     @Before
137     public void initialization() {
138         final KeyedInstanceIdentifier<Node, NodeKey> nodePath = KeyedInstanceIdentifier
139                 .create(Nodes.class)
140                 .child(Node.class, new NodeKey(new NodeId("openflow:10")));
141
142         when(mockedFeatures.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
143         when(mockedFeatures.getVersion()).thenReturn(DUMMY_VERSION);
144         when(mockedFeaturesOutput.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
145         when(mockedFeaturesOutput.getVersion()).thenReturn(DUMMY_VERSION);
146
147         when(mockedPrimConnectionContext.getFeatures()).thenReturn(mockedFeatures);
148         when(mockedPrimConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
149         when(mockedPrimConnectionContext.getConnectionState()).thenReturn(ConnectionContext.CONNECTION_STATE.WORKING);
150         when(mockedPrimConnectionContext.getNodeId()).thenReturn(NODE_ID);
151         when(mockedPrimConnectionContext.getOutboundQueueProvider()).thenReturn(outboundQueue);
152
153         when(mockedDeviceState.isFlowStatisticsAvailable()).thenReturn(Boolean.TRUE);
154         when(mockedDeviceState.isGroupAvailable()).thenReturn(Boolean.TRUE);
155         when(mockedDeviceState.isMetersAvailable()).thenReturn(Boolean.TRUE);
156         when(mockedDeviceState.isPortStatisticsAvailable()).thenReturn(Boolean.TRUE);
157         when(mockedDeviceState.isQueueStatisticsAvailable()).thenReturn(Boolean.TRUE);
158         when(mockedDeviceState.isTableStatisticsAvailable()).thenReturn(Boolean.TRUE);
159         when(mockedDeviceState.getFeatures()).thenReturn(featuresOutput);
160         when(mockedDeviceState.getNodeInstanceIdentifier()).thenReturn(nodePath);
161
162         when(deviceInfo.getNodeId()).thenReturn(NODE_ID);
163         when(mockedDeviceState.getNodeId()).thenReturn(NODE_ID);
164
165         when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedPrimConnectionContext);
166         when(mockedDeviceContext.getMessageSpy()).thenReturn(mockedMessagSpy);
167         when(mockedDeviceContext.getDeviceFlowRegistry()).thenReturn(new DeviceFlowRegistryImpl());
168         when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
169         when(mockedDeviceContext.getMultiMsgCollector(
170                 Matchers.<RequestContext<List<MultipartReply>>>any())).thenAnswer(
171                 new Answer<MultiMsgCollector>() {
172                     @Override
173                     public MultiMsgCollector answer(InvocationOnMock invocation) throws Throwable {
174                         currentRequestContext = (RequestContext<List<MultipartReply>>) invocation.getArguments()[0];
175                         return multiMagCollector;
176                     }
177                 }
178         );
179         when(mockedDeviceContext.getItemLifeCycleSourceRegistry()).thenReturn(itemLifeCycleRegistry);
180         when(rpcProviderRegistry.addRpcImplementation(
181                 Matchers.eq(StatisticsManagerControlService.class),
182                 Matchers.<StatisticsManagerControlService>any())).thenReturn(serviceControlRegistration);
183
184         statisticsManager = new StatisticsManagerImpl(rpcProviderRegistry, false, conductor);
185         statisticsManager.setDeviceInitializationPhaseHandler(deviceInitializationPhaseHandler);
186         when(deviceManager.getDeviceContextFromNodeId(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
187         when(conductor.getDeviceContext(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
188     }
189
190     @Test
191     public void testOnDeviceContextLevelUp() throws Exception {
192         Mockito.doAnswer(new Answer<Void>() {
193             @Override
194             public Void answer(InvocationOnMock invocation) throws Throwable {
195                 final FutureCallback<OfHeader> callback = (FutureCallback<OfHeader>) invocation.getArguments()[2];
196                 LOG.debug("committing entry: {}", ((MultipartRequestInput) invocation.getArguments()[1]).getType());
197                 callback.onSuccess(null);
198                 currentRequestContext.setResult(RpcResultBuilder.<List<MultipartReply>>success().build());
199                 return null;
200             }
201         }).when(outboundQueue)
202                 .commitEntry(Matchers.anyLong(), Matchers.<OfHeader>any(), Matchers.<FutureCallback<OfHeader>>any());
203
204         statisticsManager.setDeviceInitializationPhaseHandler(mockedDevicePhaseHandler);
205         statisticsManager.onDeviceContextLevelUp(deviceInfo);
206         verify(mockedDevicePhaseHandler).onDeviceContextLevelUp(deviceInfo);
207     }
208
209     @Test
210     public void testOnDeviceContextClosed() throws Exception {
211         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
212         final Map<DeviceInfo, StatisticsContext> contextsMap = getContextsMap(statisticsManager);
213
214         contextsMap.put(deviceInfo, statisticContext);
215         Assert.assertEquals(1, contextsMap.size());
216
217         statisticsManager.setDeviceTerminationPhaseHandler(mockedTerminationPhaseHandler);
218         statisticsManager.onDeviceContextLevelDown(deviceInfo);
219         verify(statisticContext).close();
220         verify(mockedTerminationPhaseHandler).onDeviceContextLevelDown(deviceInfo);
221         Assert.assertEquals(0, contextsMap.size());
222     }
223
224     private static Map<DeviceInfo, StatisticsContext> getContextsMap(final StatisticsManagerImpl statisticsManager)
225             throws NoSuchFieldException, IllegalAccessException {
226         // HACK: contexts map for testing shall be accessed in some more civilized way
227         final Field contextsField = StatisticsManagerImpl.class.getDeclaredField("contexts");
228         Assert.assertNotNull(contextsField);
229         contextsField.setAccessible(true);
230         return (Map<DeviceInfo, StatisticsContext>) contextsField.get(statisticsManager);
231     }
232
233     @Test
234     public void testGetStatisticsWorkMode() throws Exception {
235         final Future<RpcResult<GetStatisticsWorkModeOutput>> workMode = statisticsManager.getStatisticsWorkMode();
236         Assert.assertTrue(workMode.isDone());
237         Assert.assertTrue(workMode.get().isSuccessful());
238         Assert.assertNotNull(workMode.get().getResult());
239         Assert.assertEquals(StatisticsWorkMode.COLLECTALL, workMode.get().getResult().getMode());
240     }
241
242     /**
243      * switching to {@link StatisticsWorkMode#FULLYDISABLED}; no pollTimeout and no lifecycleRegistry
244      *
245      * @throws Exception
246      */
247     @Test
248     public void testChangeStatisticsWorkMode1() throws Exception {
249         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
250         when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
251         when(statisticContext.getPollTimeout()).thenReturn(
252                 Optional.<Timeout>absent());
253         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
254                 Collections.<ItemLifeCycleSource>emptyList());
255
256         getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
257
258         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
259                 new ChangeStatisticsWorkModeInputBuilder()
260                         .setMode(StatisticsWorkMode.FULLYDISABLED);
261
262         final Future<RpcResult<Void>> workMode = statisticsManager
263                 .changeStatisticsWorkMode(changeStatisticsWorkModeInputBld.build());
264
265         checkWorkModeChangeOutcome(workMode);
266         Mockito.verify(itemLifeCycleRegistry).getLifeCycleSources();
267         Mockito.verify(statisticContext).getPollTimeout();
268     }
269
270     private static void checkWorkModeChangeOutcome(Future<RpcResult<Void>> workMode) throws InterruptedException, java.util.concurrent.ExecutionException {
271         Assert.assertTrue(workMode.isDone());
272         Assert.assertTrue(workMode.get().isSuccessful());
273     }
274
275
276     /**
277      * switching to {@link StatisticsWorkMode#FULLYDISABLED}; with pollTimeout and lifecycleRegistry
278      *
279      * @throws Exception
280      */
281     @Test
282     public void testChangeStatisticsWorkMode2() throws Exception {
283         final Timeout pollTimeout = Mockito.mock(Timeout.class);
284         final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
285         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
286         when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
287         when(statisticContext.getPollTimeout()).thenReturn(
288                 Optional.of(pollTimeout));
289         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
290                 Collections.singletonList(itemLifecycleSource));
291
292         getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
293
294         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
295                 new ChangeStatisticsWorkModeInputBuilder()
296                         .setMode(StatisticsWorkMode.FULLYDISABLED);
297
298         Future<RpcResult<Void>> workMode = statisticsManager.changeStatisticsWorkMode(changeStatisticsWorkModeInputBld.build());
299         checkWorkModeChangeOutcome(workMode);
300
301         Mockito.verify(itemLifeCycleRegistry).getLifeCycleSources();
302         Mockito.verify(statisticContext).getPollTimeout();
303         Mockito.verify(pollTimeout).cancel();
304         Mockito.verify(itemLifecycleSource).setItemLifecycleListener(Matchers.<ItemLifecycleListener>any());
305     }
306
307     /**
308      * switching to {@link StatisticsWorkMode#FULLYDISABLED} and back
309      * to {@link StatisticsWorkMode#COLLECTALL}; with lifecycleRegistry and pollTimeout
310      *
311      * @throws Exception
312      */
313     @Test
314     public void testChangeStatisticsWorkMode3() throws Exception {
315         final Timeout pollTimeout = Mockito.mock(Timeout.class);
316         final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
317         Mockito.doNothing().when(itemLifecycleSource)
318                 .setItemLifecycleListener(itemLifeCycleListenerCapt.capture());
319
320         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
321         when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
322         when(statisticContext.getPollTimeout()).thenReturn(
323                 Optional.of(pollTimeout));
324         when(statisticContext.getItemLifeCycleListener()).thenReturn(
325                 Mockito.mock(ItemLifecycleListener.class));
326         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
327                 Collections.singletonList(itemLifecycleSource));
328
329         getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
330
331         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
332                 new ChangeStatisticsWorkModeInputBuilder()
333                         .setMode(StatisticsWorkMode.FULLYDISABLED);
334
335         Future<RpcResult<Void>> workMode;
336         workMode = statisticsManager.changeStatisticsWorkMode(
337                 changeStatisticsWorkModeInputBld.build());
338         checkWorkModeChangeOutcome(workMode);
339
340         changeStatisticsWorkModeInputBld.setMode(StatisticsWorkMode.COLLECTALL);
341         workMode = statisticsManager.changeStatisticsWorkMode(
342                 changeStatisticsWorkModeInputBld.build());
343         checkWorkModeChangeOutcome(workMode);
344
345         Mockito.verify(itemLifeCycleRegistry, Mockito.times(2)).getLifeCycleSources();
346         Mockito.verify(statisticContext).getPollTimeout();
347         Mockito.verify(pollTimeout).cancel();
348
349         final List<ItemLifecycleListener> itemLifeCycleListenerValues = itemLifeCycleListenerCapt.getAllValues();
350         Assert.assertEquals(2, itemLifeCycleListenerValues.size());
351         Assert.assertNotNull(itemLifeCycleListenerValues.get(0));
352         Assert.assertNull(itemLifeCycleListenerValues.get(1));
353     }
354
355     @Test
356     public void testClose() throws Exception {
357         statisticsManager.close();
358         Mockito.verify(serviceControlRegistration).close();
359     }
360
361     @Test
362     public void testCalculateTimerDelay() throws Exception {
363         final TimeCounter timeCounter = Mockito.mock(TimeCounter.class);
364         when(timeCounter.getAverageTimeBetweenMarks()).thenReturn(2000L, (Long)4000L);
365
366         statisticsManager.calculateTimerDelay(timeCounter);
367         Assert.assertEquals(3000L, StatisticsManagerImpl.getCurrentTimerDelay());
368         statisticsManager.calculateTimerDelay(timeCounter);
369         Assert.assertEquals(6000L, StatisticsManagerImpl.getCurrentTimerDelay());
370     }
371
372     @Test
373     public void testPollStatistics() throws Exception {
374         final StatisticsContext statisticsContext = Mockito.mock(StatisticsContext.class);
375         final TimeCounter mockTimerCounter = Mockito.mock(TimeCounter.class);
376
377         statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
378         verify(mockedDeviceContext).getDeviceState();
379
380         when(mockedDeviceContext.getDeviceState().isValid()).thenReturn(true);
381         statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
382         // TODO Make scheduleNextPolling visible for tests?
383
384         when(mockedDeviceContext.getDeviceState().isStatisticsPollingEnabled()).thenReturn(true);
385         statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
386         // TODO Make scheduleNextPolling visible for tests?
387
388         when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateCheckedFuture(Boolean.TRUE));
389         when(statisticsContext.isSchedulingEnabled()).thenReturn(Boolean.TRUE);
390         statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
391         Mockito.verify(mockTimerCounter).markStart();
392         Mockito.verify(mockTimerCounter).addTimeMark();
393
394         when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateFailedFuture(new Throwable("error msg")));
395         statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
396         Mockito.verify(mockTimerCounter,times(2)).addTimeMark();
397     }
398 }