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