2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.openflowplugin.impl.statistics;
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;
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;
78 @RunWith(MockitoJUnitRunner.class)
79 public class StatisticsManagerImplTest {
81 private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImplTest.class);
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");
88 RequestContextStack mockedRequestContextStack;
90 ConnectionContext mockedPrimConnectionContext;
92 FeaturesReply mockedFeatures;
94 GetFeaturesOutput mockedFeaturesOutput;
96 ConnectionAdapter mockedConnectionAdapter;
98 MessageSpy mockedMessagSpy;
100 DeviceContext mockedDeviceContext;
102 DeviceState mockedDeviceState;
104 DeviceInfo mockedDeviceInfo;
106 DeviceInitializationPhaseHandler mockedDevicePhaseHandler;
108 DeviceTerminationPhaseHandler mockedTerminationPhaseHandler;
110 private RpcProviderRegistry rpcProviderRegistry;
112 private HashedWheelTimer hashedWheelTimer;
114 private OutboundQueue outboundQueue;
116 private MultiMsgCollector multiMagCollector;
118 private ItemLifeCycleRegistry itemLifeCycleRegistry;
120 private ArgumentCaptor<ItemLifecycleListener> itemLifeCycleListenerCapt;
122 private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> serviceControlRegistration;
124 private DeviceManager deviceManager;
126 private LifecycleConductor conductor;
128 private GetFeaturesOutput featuresOutput;
130 private DeviceInitializationPhaseHandler deviceInitializationPhaseHandler;
132 private DeviceInfo deviceInfo;
134 private RequestContext<List<MultipartReply>> currentRequestContext;
135 private StatisticsManagerImpl statisticsManager;
139 public void initialization() {
140 final KeyedInstanceIdentifier<Node, NodeKey> nodePath = KeyedInstanceIdentifier
142 .child(Node.class, new NodeKey(new NodeId("openflow:10")));
144 when(mockedFeatures.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
145 when(mockedFeatures.getVersion()).thenReturn(DUMMY_VERSION);
146 when(mockedFeaturesOutput.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
147 when(mockedFeaturesOutput.getVersion()).thenReturn(DUMMY_VERSION);
149 when(mockedPrimConnectionContext.getFeatures()).thenReturn(mockedFeatures);
150 when(mockedPrimConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
151 when(mockedPrimConnectionContext.getConnectionState()).thenReturn(ConnectionContext.CONNECTION_STATE.WORKING);
152 when(mockedPrimConnectionContext.getNodeId()).thenReturn(NODE_ID);
153 when(mockedPrimConnectionContext.getOutboundQueueProvider()).thenReturn(outboundQueue);
155 when(mockedDeviceState.isFlowStatisticsAvailable()).thenReturn(Boolean.TRUE);
156 when(mockedDeviceState.isGroupAvailable()).thenReturn(Boolean.TRUE);
157 when(mockedDeviceState.isMetersAvailable()).thenReturn(Boolean.TRUE);
158 when(mockedDeviceState.isPortStatisticsAvailable()).thenReturn(Boolean.TRUE);
159 when(mockedDeviceState.isQueueStatisticsAvailable()).thenReturn(Boolean.TRUE);
160 when(mockedDeviceState.isTableStatisticsAvailable()).thenReturn(Boolean.TRUE);
162 when(deviceInfo.getNodeInstanceIdentifier()).thenReturn(nodePath);
163 when(deviceInfo.getNodeId()).thenReturn(NODE_ID);
165 when(mockedDeviceContext.getDeviceInfo()).thenReturn(deviceInfo);
166 when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedPrimConnectionContext);
167 when(mockedDeviceContext.getMessageSpy()).thenReturn(mockedMessagSpy);
168 when(mockedDeviceContext.getDeviceFlowRegistry()).thenReturn(new DeviceFlowRegistryImpl());
169 when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
170 when(mockedDeviceContext.getMultiMsgCollector(
171 Matchers.<RequestContext<List<MultipartReply>>>any())).thenAnswer(
172 new Answer<MultiMsgCollector>() {
174 public MultiMsgCollector answer(InvocationOnMock invocation) throws Throwable {
175 currentRequestContext = (RequestContext<List<MultipartReply>>) invocation.getArguments()[0];
176 return multiMagCollector;
180 when(mockedDeviceContext.getItemLifeCycleSourceRegistry()).thenReturn(itemLifeCycleRegistry);
181 when(rpcProviderRegistry.addRpcImplementation(
182 Matchers.eq(StatisticsManagerControlService.class),
183 Matchers.<StatisticsManagerControlService>any())).thenReturn(serviceControlRegistration);
185 statisticsManager = new StatisticsManagerImpl(rpcProviderRegistry, false, conductor);
186 statisticsManager.setDeviceInitializationPhaseHandler(deviceInitializationPhaseHandler);
187 when(deviceManager.getDeviceContextFromNodeId(deviceInfo)).thenReturn(mockedDeviceContext);
188 when(conductor.getDeviceContext(deviceInfo)).thenReturn(mockedDeviceContext);
192 public void testOnDeviceContextLevelUp() throws Exception {
193 Mockito.doAnswer(new Answer<Void>() {
195 public Void answer(InvocationOnMock invocation) throws Throwable {
196 final FutureCallback<OfHeader> callback = (FutureCallback<OfHeader>) invocation.getArguments()[2];
197 LOG.debug("committing entry: {}", ((MultipartRequestInput) invocation.getArguments()[1]).getType());
198 callback.onSuccess(null);
199 currentRequestContext.setResult(RpcResultBuilder.<List<MultipartReply>>success().build());
202 }).when(outboundQueue)
203 .commitEntry(Matchers.anyLong(), Matchers.<OfHeader>any(), Matchers.<FutureCallback<OfHeader>>any());
205 statisticsManager.setDeviceInitializationPhaseHandler(mockedDevicePhaseHandler);
206 statisticsManager.onDeviceContextLevelUp(deviceInfo);
207 verify(mockedDevicePhaseHandler).onDeviceContextLevelUp(deviceInfo);
211 public void testOnDeviceContextClosed() throws Exception {
212 final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
213 final Map<DeviceInfo, StatisticsContext> contextsMap = getContextsMap(statisticsManager);
215 contextsMap.put(deviceInfo, statisticContext);
216 Assert.assertEquals(1, contextsMap.size());
218 statisticsManager.setDeviceTerminationPhaseHandler(mockedTerminationPhaseHandler);
219 statisticsManager.onDeviceContextLevelDown(deviceInfo);
220 verify(statisticContext).close();
221 verify(mockedTerminationPhaseHandler).onDeviceContextLevelDown(deviceInfo);
222 Assert.assertEquals(0, contextsMap.size());
225 private static Map<DeviceInfo, StatisticsContext> getContextsMap(final StatisticsManagerImpl statisticsManager)
226 throws NoSuchFieldException, IllegalAccessException {
227 // HACK: contexts map for testing shall be accessed in some more civilized way
228 final Field contextsField = StatisticsManagerImpl.class.getDeclaredField("contexts");
229 Assert.assertNotNull(contextsField);
230 contextsField.setAccessible(true);
231 return (Map<DeviceInfo, StatisticsContext>) contextsField.get(statisticsManager);
235 public void testGetStatisticsWorkMode() throws Exception {
236 final Future<RpcResult<GetStatisticsWorkModeOutput>> workMode = statisticsManager.getStatisticsWorkMode();
237 Assert.assertTrue(workMode.isDone());
238 Assert.assertTrue(workMode.get().isSuccessful());
239 Assert.assertNotNull(workMode.get().getResult());
240 Assert.assertEquals(StatisticsWorkMode.COLLECTALL, workMode.get().getResult().getMode());
244 * switching to {@link StatisticsWorkMode#FULLYDISABLED}; no pollTimeout and no lifecycleRegistry
249 public void testChangeStatisticsWorkMode1() throws Exception {
250 final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
251 when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
252 when(statisticContext.getPollTimeout()).thenReturn(
253 Optional.<Timeout>absent());
254 when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
255 Collections.<ItemLifeCycleSource>emptyList());
257 getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
259 final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
260 new ChangeStatisticsWorkModeInputBuilder()
261 .setMode(StatisticsWorkMode.FULLYDISABLED);
263 final Future<RpcResult<Void>> workMode = statisticsManager
264 .changeStatisticsWorkMode(changeStatisticsWorkModeInputBld.build());
266 checkWorkModeChangeOutcome(workMode);
267 Mockito.verify(itemLifeCycleRegistry).getLifeCycleSources();
268 Mockito.verify(statisticContext).getPollTimeout();
271 private static void checkWorkModeChangeOutcome(Future<RpcResult<Void>> workMode) throws InterruptedException, java.util.concurrent.ExecutionException {
272 Assert.assertTrue(workMode.isDone());
273 Assert.assertTrue(workMode.get().isSuccessful());
278 * switching to {@link StatisticsWorkMode#FULLYDISABLED}; with pollTimeout and lifecycleRegistry
283 public void testChangeStatisticsWorkMode2() throws Exception {
284 final Timeout pollTimeout = Mockito.mock(Timeout.class);
285 final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
286 final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
287 when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
288 when(statisticContext.getPollTimeout()).thenReturn(
289 Optional.of(pollTimeout));
290 when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
291 Collections.singletonList(itemLifecycleSource));
293 getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
295 final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
296 new ChangeStatisticsWorkModeInputBuilder()
297 .setMode(StatisticsWorkMode.FULLYDISABLED);
299 Future<RpcResult<Void>> workMode = statisticsManager.changeStatisticsWorkMode(changeStatisticsWorkModeInputBld.build());
300 checkWorkModeChangeOutcome(workMode);
302 Mockito.verify(itemLifeCycleRegistry).getLifeCycleSources();
303 Mockito.verify(statisticContext).getPollTimeout();
304 Mockito.verify(pollTimeout).cancel();
305 Mockito.verify(itemLifecycleSource).setItemLifecycleListener(Matchers.<ItemLifecycleListener>any());
309 * switching to {@link StatisticsWorkMode#FULLYDISABLED} and back
310 * to {@link StatisticsWorkMode#COLLECTALL}; with lifecycleRegistry and pollTimeout
315 public void testChangeStatisticsWorkMode3() throws Exception {
316 final Timeout pollTimeout = Mockito.mock(Timeout.class);
317 final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
318 Mockito.doNothing().when(itemLifecycleSource)
319 .setItemLifecycleListener(itemLifeCycleListenerCapt.capture());
321 final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
322 when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
323 when(statisticContext.getPollTimeout()).thenReturn(
324 Optional.of(pollTimeout));
325 when(statisticContext.getItemLifeCycleListener()).thenReturn(
326 Mockito.mock(ItemLifecycleListener.class));
327 when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
328 Collections.singletonList(itemLifecycleSource));
330 getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
332 final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
333 new ChangeStatisticsWorkModeInputBuilder()
334 .setMode(StatisticsWorkMode.FULLYDISABLED);
336 Future<RpcResult<Void>> workMode;
337 workMode = statisticsManager.changeStatisticsWorkMode(
338 changeStatisticsWorkModeInputBld.build());
339 checkWorkModeChangeOutcome(workMode);
341 changeStatisticsWorkModeInputBld.setMode(StatisticsWorkMode.COLLECTALL);
342 workMode = statisticsManager.changeStatisticsWorkMode(
343 changeStatisticsWorkModeInputBld.build());
344 checkWorkModeChangeOutcome(workMode);
346 Mockito.verify(itemLifeCycleRegistry, Mockito.times(2)).getLifeCycleSources();
347 Mockito.verify(statisticContext).getPollTimeout();
348 Mockito.verify(pollTimeout).cancel();
350 final List<ItemLifecycleListener> itemLifeCycleListenerValues = itemLifeCycleListenerCapt.getAllValues();
351 Assert.assertEquals(2, itemLifeCycleListenerValues.size());
352 Assert.assertNotNull(itemLifeCycleListenerValues.get(0));
353 Assert.assertNull(itemLifeCycleListenerValues.get(1));
357 public void testClose() throws Exception {
358 statisticsManager.close();
359 Mockito.verify(serviceControlRegistration).close();
363 public void testCalculateTimerDelay() throws Exception {
364 final TimeCounter timeCounter = Mockito.mock(TimeCounter.class);
365 when(timeCounter.getAverageTimeBetweenMarks()).thenReturn(2000L, (Long)4000L);
367 statisticsManager.calculateTimerDelay(timeCounter);
368 Assert.assertEquals(3000L, StatisticsManagerImpl.getCurrentTimerDelay());
369 statisticsManager.calculateTimerDelay(timeCounter);
370 Assert.assertEquals(6000L, StatisticsManagerImpl.getCurrentTimerDelay());
374 public void testPollStatistics() throws Exception {
375 final StatisticsContext statisticsContext = Mockito.mock(StatisticsContext.class);
376 final TimeCounter mockTimerCounter = Mockito.mock(TimeCounter.class);
378 statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
379 verify(mockedDeviceContext).getDeviceInfo();
381 when(mockedDeviceContext.getDeviceState().isValid()).thenReturn(true);
382 statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
383 // TODO Make scheduleNextPolling visible for tests?
385 when(mockedDeviceContext.getDeviceState().isStatisticsPollingEnabled()).thenReturn(true);
386 statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
387 // TODO Make scheduleNextPolling visible for tests?
389 when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateCheckedFuture(Boolean.TRUE));
390 when(statisticsContext.isSchedulingEnabled()).thenReturn(Boolean.TRUE);
391 statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
392 Mockito.verify(mockTimerCounter).markStart();
393 Mockito.verify(mockTimerCounter).addTimeMark();
395 when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateFailedFuture(new Throwable("error msg")));
396 statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
397 Mockito.verify(mockTimerCounter,times(2)).addTimeMark();