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.DeviceManager;
44 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
45 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
46 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
47 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
48 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
49 import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
50 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
51 import org.opendaylight.openflowplugin.api.openflow.registry.ItemLifeCycleRegistry;
52 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
53 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
54 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
55 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
56 import org.opendaylight.openflowplugin.impl.registry.flow.DeviceFlowRegistryImpl;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.ChangeStatisticsWorkModeInputBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsManagerControlService;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsWorkMode;
70 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
71 import org.opendaylight.yangtools.yang.common.RpcResult;
72 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
77 @RunWith(MockitoJUnitRunner.class)
78 public class StatisticsManagerImplTest {
80 private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImplTest.class);
82 private static final BigInteger DUMMY_DATAPATH_ID = new BigInteger("444");
83 private static final Short DUMMY_VERSION = OFConstants.OFP_VERSION_1_3;
86 RequestContextStack mockedRequestContextStack;
88 ConnectionContext mockedPrimConnectionContext;
90 FeaturesReply mockedFeatures;
92 GetFeaturesOutput mockedFeaturesOutput;
94 ConnectionAdapter mockedConnectionAdapter;
96 MessageSpy mockedMessagSpy;
98 DeviceContext mockedDeviceContext;
100 DeviceState mockedDeviceState;
102 DeviceInitializationPhaseHandler mockedDevicePhaseHandler;
104 DeviceTerminationPhaseHandler mockedTerminationPhaseHandler;
106 private RpcProviderRegistry rpcProviderRegistry;
108 private HashedWheelTimer hashedWheelTimer;
110 private OutboundQueue outboundQueue;
112 private MultiMsgCollector multiMagCollector;
114 private ItemLifeCycleRegistry itemLifeCycleRegistry;
116 private ArgumentCaptor<ItemLifecycleListener> itemLifeCycleListenerCapt;
118 private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> serviceControlRegistration;
120 private DeviceManager deviceManager;
122 private LifecycleConductor conductor;
124 private GetFeaturesOutput featuresOutput;
126 private DeviceInitializationPhaseHandler deviceInitializationPhaseHandler;
128 private RequestContext<List<MultipartReply>> currentRequestContext;
129 private StatisticsManagerImpl statisticsManager;
133 public void initialization() {
134 final KeyedInstanceIdentifier<Node, NodeKey> nodePath = KeyedInstanceIdentifier
136 .child(Node.class, new NodeKey(new NodeId("openflow:10")));
138 when(mockedFeatures.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
139 when(mockedFeatures.getVersion()).thenReturn(DUMMY_VERSION);
140 when(mockedFeaturesOutput.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
141 when(mockedFeaturesOutput.getVersion()).thenReturn(DUMMY_VERSION);
143 when(mockedPrimConnectionContext.getFeatures()).thenReturn(mockedFeatures);
144 when(mockedPrimConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
145 when(mockedPrimConnectionContext.getConnectionState()).thenReturn(ConnectionContext.CONNECTION_STATE.WORKING);
146 when(mockedPrimConnectionContext.getNodeId()).thenReturn(new NodeId("ut-node:123"));
147 when(mockedPrimConnectionContext.getOutboundQueueProvider()).thenReturn(outboundQueue);
149 when(mockedDeviceState.isFlowStatisticsAvailable()).thenReturn(Boolean.TRUE);
150 when(mockedDeviceState.isGroupAvailable()).thenReturn(Boolean.TRUE);
151 when(mockedDeviceState.isMetersAvailable()).thenReturn(Boolean.TRUE);
152 when(mockedDeviceState.isPortStatisticsAvailable()).thenReturn(Boolean.TRUE);
153 when(mockedDeviceState.isQueueStatisticsAvailable()).thenReturn(Boolean.TRUE);
154 when(mockedDeviceState.isTableStatisticsAvailable()).thenReturn(Boolean.TRUE);
155 when(mockedDeviceState.getFeatures()).thenReturn(featuresOutput);
156 when(mockedDeviceState.getNodeInstanceIdentifier()).thenReturn(nodePath);
158 when(mockedDeviceState.getNodeId()).thenReturn(new NodeId("ofp-unit-dummy-node-id"));
160 when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedPrimConnectionContext);
161 when(mockedDeviceContext.getMessageSpy()).thenReturn(mockedMessagSpy);
162 when(mockedDeviceContext.getDeviceFlowRegistry()).thenReturn(new DeviceFlowRegistryImpl());
163 when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
164 when(mockedDeviceContext.getMultiMsgCollector(
165 Matchers.<RequestContext<List<MultipartReply>>>any())).thenAnswer(
166 new Answer<MultiMsgCollector>() {
168 public MultiMsgCollector answer(InvocationOnMock invocation) throws Throwable {
169 currentRequestContext = (RequestContext<List<MultipartReply>>) invocation.getArguments()[0];
170 return multiMagCollector;
174 when(mockedDeviceContext.getItemLifeCycleSourceRegistry()).thenReturn(itemLifeCycleRegistry);
175 when(rpcProviderRegistry.addRpcImplementation(
176 Matchers.eq(StatisticsManagerControlService.class),
177 Matchers.<StatisticsManagerControlService>any())).thenReturn(serviceControlRegistration);
179 statisticsManager = new StatisticsManagerImpl(rpcProviderRegistry, false, conductor);
180 statisticsManager.setDeviceInitializationPhaseHandler(deviceInitializationPhaseHandler);
181 when(deviceManager.getDeviceContextFromNodeId(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
182 when(conductor.getDeviceContext(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
186 public void testOnDeviceContextLevelUp() throws Exception {
187 Mockito.doAnswer(new Answer<Void>() {
189 public Void answer(InvocationOnMock invocation) throws Throwable {
190 final FutureCallback<OfHeader> callback = (FutureCallback<OfHeader>) invocation.getArguments()[2];
191 LOG.debug("committing entry: {}", ((MultipartRequestInput) invocation.getArguments()[1]).getType());
192 callback.onSuccess(null);
193 currentRequestContext.setResult(RpcResultBuilder.<List<MultipartReply>>success().build());
196 }).when(outboundQueue)
197 .commitEntry(Matchers.anyLong(), Matchers.<OfHeader>any(), Matchers.<FutureCallback<OfHeader>>any());
199 statisticsManager.setDeviceInitializationPhaseHandler(mockedDevicePhaseHandler);
200 statisticsManager.onDeviceContextLevelUp(mockedDeviceContext.getDeviceState().getNodeId());
201 verify(mockedDevicePhaseHandler).onDeviceContextLevelUp(mockedDeviceContext.getDeviceState().getNodeId());
205 public void testOnDeviceContextClosed() throws Exception {
206 final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
207 final Map<NodeId, StatisticsContext> contextsMap = getContextsMap(statisticsManager);
209 contextsMap.put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
210 Assert.assertEquals(1, contextsMap.size());
212 statisticsManager.setDeviceTerminationPhaseHandler(mockedTerminationPhaseHandler);
213 statisticsManager.onDeviceContextLevelDown(mockedDeviceContext);
214 verify(statisticContext).close();
215 verify(mockedTerminationPhaseHandler).onDeviceContextLevelDown(mockedDeviceContext);
216 Assert.assertEquals(0, contextsMap.size());
219 private static Map<NodeId, StatisticsContext> getContextsMap(final StatisticsManagerImpl statisticsManager)
220 throws NoSuchFieldException, IllegalAccessException {
221 // HACK: contexts map for testing shall be accessed in some more civilized way
222 final Field contextsField = StatisticsManagerImpl.class.getDeclaredField("contexts");
223 Assert.assertNotNull(contextsField);
224 contextsField.setAccessible(true);
225 return (Map<NodeId, StatisticsContext>) contextsField.get(statisticsManager);
229 public void testGetStatisticsWorkMode() throws Exception {
230 final Future<RpcResult<GetStatisticsWorkModeOutput>> workMode = statisticsManager.getStatisticsWorkMode();
231 Assert.assertTrue(workMode.isDone());
232 Assert.assertTrue(workMode.get().isSuccessful());
233 Assert.assertNotNull(workMode.get().getResult());
234 Assert.assertEquals(StatisticsWorkMode.COLLECTALL, workMode.get().getResult().getMode());
238 * switching to {@link StatisticsWorkMode#FULLYDISABLED}; no pollTimeout and no lifecycleRegistry
243 public void testChangeStatisticsWorkMode1() throws Exception {
244 final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
245 when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
246 when(statisticContext.getPollTimeout()).thenReturn(
247 Optional.<Timeout>absent());
248 when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
249 Collections.<ItemLifeCycleSource>emptyList());
251 getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
253 final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
254 new ChangeStatisticsWorkModeInputBuilder()
255 .setMode(StatisticsWorkMode.FULLYDISABLED);
257 final Future<RpcResult<Void>> workMode = statisticsManager
258 .changeStatisticsWorkMode(changeStatisticsWorkModeInputBld.build());
260 checkWorkModeChangeOutcome(workMode);
261 Mockito.verify(itemLifeCycleRegistry).getLifeCycleSources();
262 Mockito.verify(statisticContext).getPollTimeout();
265 private static void checkWorkModeChangeOutcome(Future<RpcResult<Void>> workMode) throws InterruptedException, java.util.concurrent.ExecutionException {
266 Assert.assertTrue(workMode.isDone());
267 Assert.assertTrue(workMode.get().isSuccessful());
272 * switching to {@link StatisticsWorkMode#FULLYDISABLED}; with pollTimeout and lifecycleRegistry
277 public void testChangeStatisticsWorkMode2() throws Exception {
278 final Timeout pollTimeout = Mockito.mock(Timeout.class);
279 final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
280 final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
281 when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
282 when(statisticContext.getPollTimeout()).thenReturn(
283 Optional.of(pollTimeout));
284 when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
285 Collections.singletonList(itemLifecycleSource));
287 getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
289 final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
290 new ChangeStatisticsWorkModeInputBuilder()
291 .setMode(StatisticsWorkMode.FULLYDISABLED);
293 Future<RpcResult<Void>> workMode = statisticsManager.changeStatisticsWorkMode(changeStatisticsWorkModeInputBld.build());
294 checkWorkModeChangeOutcome(workMode);
296 Mockito.verify(itemLifeCycleRegistry).getLifeCycleSources();
297 Mockito.verify(statisticContext).getPollTimeout();
298 Mockito.verify(pollTimeout).cancel();
299 Mockito.verify(itemLifecycleSource).setItemLifecycleListener(Matchers.<ItemLifecycleListener>any());
303 * switching to {@link StatisticsWorkMode#FULLYDISABLED} and back
304 * to {@link StatisticsWorkMode#COLLECTALL}; with lifecycleRegistry and pollTimeout
309 public void testChangeStatisticsWorkMode3() throws Exception {
310 final Timeout pollTimeout = Mockito.mock(Timeout.class);
311 final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
312 Mockito.doNothing().when(itemLifecycleSource)
313 .setItemLifecycleListener(itemLifeCycleListenerCapt.capture());
315 final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
316 when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
317 when(statisticContext.getPollTimeout()).thenReturn(
318 Optional.of(pollTimeout));
319 when(statisticContext.getItemLifeCycleListener()).thenReturn(
320 Mockito.mock(ItemLifecycleListener.class));
321 when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
322 Collections.singletonList(itemLifecycleSource));
324 getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
326 final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
327 new ChangeStatisticsWorkModeInputBuilder()
328 .setMode(StatisticsWorkMode.FULLYDISABLED);
330 Future<RpcResult<Void>> workMode;
331 workMode = statisticsManager.changeStatisticsWorkMode(
332 changeStatisticsWorkModeInputBld.build());
333 checkWorkModeChangeOutcome(workMode);
335 changeStatisticsWorkModeInputBld.setMode(StatisticsWorkMode.COLLECTALL);
336 workMode = statisticsManager.changeStatisticsWorkMode(
337 changeStatisticsWorkModeInputBld.build());
338 checkWorkModeChangeOutcome(workMode);
340 Mockito.verify(itemLifeCycleRegistry, Mockito.times(2)).getLifeCycleSources();
341 Mockito.verify(statisticContext).getPollTimeout();
342 Mockito.verify(pollTimeout).cancel();
344 final List<ItemLifecycleListener> itemLifeCycleListenerValues = itemLifeCycleListenerCapt.getAllValues();
345 Assert.assertEquals(2, itemLifeCycleListenerValues.size());
346 Assert.assertNotNull(itemLifeCycleListenerValues.get(0));
347 Assert.assertNull(itemLifeCycleListenerValues.get(1));
351 public void testClose() throws Exception {
352 statisticsManager.close();
353 Mockito.verify(serviceControlRegistration).close();
357 public void testCalculateTimerDelay() throws Exception {
358 final TimeCounter timeCounter = Mockito.mock(TimeCounter.class);
359 when(timeCounter.getAverageTimeBetweenMarks()).thenReturn((Long)2000L, (Long)4000L);
361 statisticsManager.calculateTimerDelay(timeCounter);
362 Assert.assertEquals(3000L, StatisticsManagerImpl.getCurrentTimerDelay());
363 statisticsManager.calculateTimerDelay(timeCounter);
364 Assert.assertEquals(6000L, StatisticsManagerImpl.getCurrentTimerDelay());
368 public void testPollStatistics() throws Exception {
369 final StatisticsContext statisticsContext = Mockito.mock(StatisticsContext.class);
370 final TimeCounter mockTimerCounter = Mockito.mock(TimeCounter.class);
372 statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
373 verify(mockedDeviceContext).getDeviceState();
375 when(mockedDeviceContext.getDeviceState().isValid()).thenReturn(true);
376 statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
377 // TODO Make scheduleNextPolling visible for tests?
379 when(mockedDeviceContext.getDeviceState().isStatisticsPollingEnabled()).thenReturn(true);
380 statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
381 // TODO Make scheduleNextPolling visible for tests?
383 when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateCheckedFuture(Boolean.TRUE));
384 when(statisticsContext.isSchedulingEnabled()).thenReturn(Boolean.TRUE);
385 statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
386 Mockito.verify(mockTimerCounter).markStart();
387 Mockito.verify(mockTimerCounter).addTimeMark();
389 when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateFailedFuture(new Throwable("error msg")));
390 statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
391 Mockito.verify(mockTimerCounter,times(2)).addTimeMark();