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