Remove to set all devices slave.
[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 java.lang.reflect.Field;
16 import java.math.BigInteger;
17 import java.util.Collections;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Optional;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.Future;
23 import org.junit.Assert;
24 import org.junit.Before;
25 import org.junit.Test;
26 import org.junit.runner.RunWith;
27 import org.mockito.ArgumentCaptor;
28 import org.mockito.Captor;
29 import org.mockito.Matchers;
30 import org.mockito.Mock;
31 import org.mockito.Mockito;
32 import org.mockito.runners.MockitoJUnitRunner;
33 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
34 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
35 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
36 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
37 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
38 import org.opendaylight.openflowplugin.api.OFConstants;
39 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
40 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
41 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
42 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
43 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
44 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
45 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
46 import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
47 import org.opendaylight.openflowplugin.api.openflow.registry.ItemLifeCycleRegistry;
48 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
49 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
50 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
51 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
52 import org.opendaylight.openflowplugin.impl.registry.flow.DeviceFlowRegistryImpl;
53 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
54 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
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.openflowplugin.sm.control.rev150812.ChangeStatisticsWorkModeInputBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsManagerControlService;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsWorkMode;
66 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
67 import org.opendaylight.yangtools.yang.common.RpcResult;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70 import io.netty.util.HashedWheelTimer;
71 import io.netty.util.Timeout;
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 DeviceTerminationPhaseHandler mockedTerminationPhaseHandler;
97     @Mock
98     private RpcProviderRegistry rpcProviderRegistry;
99     @Mock
100     private OutboundQueue outboundQueue;
101     @Mock
102     private MultiMsgCollector multiMagCollector;
103     @Mock
104     private ItemLifeCycleRegistry itemLifeCycleRegistry;
105     @Captor
106     private ArgumentCaptor<ItemLifecycleListener> itemLifeCycleListenerCapt;
107     @Mock
108     private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> serviceControlRegistration;
109     @Mock
110     private DeviceInfo deviceInfo;
111     @Mock
112     private DataBroker dataBroker;
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         statisticsManager = new StatisticsManagerImpl(rpcProviderRegistry, false, new HashedWheelTimer(),
161                 convertorManager, basicTimerDelay, maximumTimerDelay);
162     }
163
164     @Test
165     public void testOnDeviceContextClosed() throws Exception {
166         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
167         final Map<DeviceInfo, StatisticsContext> contextsMap = getContextsMap(statisticsManager);
168
169         contextsMap.put(deviceInfo, statisticContext);
170         Assert.assertEquals(1, contextsMap.size());
171
172         statisticsManager.setDeviceTerminationPhaseHandler(mockedTerminationPhaseHandler);
173         statisticsManager.onDeviceContextLevelDown(deviceInfo);
174         verify(statisticContext).close();
175         verify(mockedTerminationPhaseHandler).onDeviceContextLevelDown(deviceInfo);
176         Assert.assertEquals(1, contextsMap.size());
177     }
178
179     private static Map<DeviceInfo, StatisticsContext> getContextsMap(final StatisticsManagerImpl statisticsManager)
180             throws NoSuchFieldException, IllegalAccessException {
181         // HACK: contexts map for testing shall be accessed in some more civilized way
182         final Field contextsField = StatisticsManagerImpl.class.getDeclaredField("contexts");
183         Assert.assertNotNull(contextsField);
184         contextsField.setAccessible(true);
185         return (Map<DeviceInfo, StatisticsContext>) contextsField.get(statisticsManager);
186     }
187
188     @Test
189     public void testGetStatisticsWorkMode() throws Exception {
190         final Future<RpcResult<GetStatisticsWorkModeOutput>> workMode = statisticsManager.getStatisticsWorkMode();
191         Assert.assertTrue(workMode.isDone());
192         Assert.assertTrue(workMode.get().isSuccessful());
193         Assert.assertNotNull(workMode.get().getResult());
194         Assert.assertEquals(StatisticsWorkMode.COLLECTALL, workMode.get().getResult().getMode());
195     }
196
197     /**
198      * switching to {@link StatisticsWorkMode#FULLYDISABLED}; no pollTimeout and no lifecycleRegistry
199      *
200      * @throws Exception
201      */
202     @Test
203     public void testChangeStatisticsWorkMode1() throws Exception {
204         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
205         when(statisticContext.getPollTimeout()).thenReturn(
206                 Optional.<Timeout>empty());
207         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
208                 Collections.<ItemLifeCycleSource>emptyList());
209
210         when(statisticContext.gainDeviceContext()).thenReturn(mockedDeviceContext);
211         when(statisticContext.gainDeviceState()).thenReturn(mockedDeviceState);
212
213         getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
214
215         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
216                 new ChangeStatisticsWorkModeInputBuilder()
217                         .setMode(StatisticsWorkMode.FULLYDISABLED);
218
219         final Future<RpcResult<Void>> workMode = statisticsManager
220                 .changeStatisticsWorkMode(changeStatisticsWorkModeInputBld.build());
221
222         checkWorkModeChangeOutcome(workMode);
223         verify(itemLifeCycleRegistry).getLifeCycleSources();
224         verify(statisticContext).getPollTimeout();
225     }
226
227     private static void checkWorkModeChangeOutcome(Future<RpcResult<Void>> workMode) throws InterruptedException, ExecutionException {
228         Assert.assertTrue(workMode.isDone());
229         Assert.assertTrue(workMode.get().isSuccessful());
230     }
231
232
233     /**
234      * switching to {@link StatisticsWorkMode#FULLYDISABLED}; with pollTimeout and lifecycleRegistry
235      *
236      * @throws Exception
237      */
238     @Test
239     public void testChangeStatisticsWorkMode2() throws Exception {
240         final Timeout pollTimeout = Mockito.mock(Timeout.class);
241         final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
242         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
243         when(statisticContext.getPollTimeout()).thenReturn(
244                 Optional.of(pollTimeout));
245         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
246                 Collections.singletonList(itemLifecycleSource));
247
248         getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
249
250         when(statisticContext.gainDeviceContext()).thenReturn(mockedDeviceContext);
251         when(statisticContext.gainDeviceState()).thenReturn(mockedDeviceState);
252 //        when(lifecycleService.getDeviceContext()).thenReturn(mockedDeviceContext);
253
254         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
255                 new ChangeStatisticsWorkModeInputBuilder()
256                         .setMode(StatisticsWorkMode.FULLYDISABLED);
257
258         Future<RpcResult<Void>> workMode = statisticsManager.changeStatisticsWorkMode(changeStatisticsWorkModeInputBld.build());
259         checkWorkModeChangeOutcome(workMode);
260
261         verify(itemLifeCycleRegistry).getLifeCycleSources();
262         verify(statisticContext).getPollTimeout();
263         verify(pollTimeout).cancel();
264         verify(itemLifecycleSource).setItemLifecycleListener(Matchers.<ItemLifecycleListener>any());
265     }
266
267     /**
268      * switching to {@link StatisticsWorkMode#FULLYDISABLED} and back
269      * to {@link StatisticsWorkMode#COLLECTALL}; with lifecycleRegistry and pollTimeout
270      *
271      * @throws Exception
272      */
273     @Test
274     public void testChangeStatisticsWorkMode3() throws Exception {
275         final Timeout pollTimeout = Mockito.mock(Timeout.class);
276         final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
277         Mockito.doNothing().when(itemLifecycleSource)
278                 .setItemLifecycleListener(itemLifeCycleListenerCapt.capture());
279
280         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
281         when(statisticContext.getPollTimeout()).thenReturn(
282                 Optional.of(pollTimeout));
283         when(statisticContext.getItemLifeCycleListener()).thenReturn(
284                 Mockito.mock(ItemLifecycleListener.class));
285         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
286                 Collections.singletonList(itemLifecycleSource));
287
288         getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
289
290         when(statisticContext.gainDeviceContext()).thenReturn(mockedDeviceContext);
291         when(statisticContext.gainDeviceState()).thenReturn(mockedDeviceState);
292 //        when(lifecycleService.getDeviceContext()).thenReturn(mockedDeviceContext);
293
294         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
295                 new ChangeStatisticsWorkModeInputBuilder()
296                         .setMode(StatisticsWorkMode.FULLYDISABLED);
297
298         Future<RpcResult<Void>> workMode;
299         workMode = statisticsManager.changeStatisticsWorkMode(
300                 changeStatisticsWorkModeInputBld.build());
301         checkWorkModeChangeOutcome(workMode);
302
303         changeStatisticsWorkModeInputBld.setMode(StatisticsWorkMode.COLLECTALL);
304         workMode = statisticsManager.changeStatisticsWorkMode(
305                 changeStatisticsWorkModeInputBld.build());
306         checkWorkModeChangeOutcome(workMode);
307
308         verify(itemLifeCycleRegistry, times(2)).getLifeCycleSources();
309         verify(statisticContext).getPollTimeout();
310         verify(pollTimeout).cancel();
311
312         final List<ItemLifecycleListener> itemLifeCycleListenerValues = itemLifeCycleListenerCapt.getAllValues();
313         Assert.assertEquals(2, itemLifeCycleListenerValues.size());
314         Assert.assertNotNull(itemLifeCycleListenerValues.get(0));
315         Assert.assertNull(itemLifeCycleListenerValues.get(1));
316     }
317
318     @Test
319     public void testClose() throws Exception {
320         statisticsManager.close();
321         verify(serviceControlRegistration).close();
322     }
323
324     @Test
325     public void testCalculateTimerDelay() throws Exception {
326         final TimeCounter timeCounter = Mockito.mock(TimeCounter.class);
327         when(timeCounter.getAverageTimeBetweenMarks()).thenReturn(2000L, (Long)4000L);
328         statisticsManager.calculateTimerDelay(timeCounter);
329         Assert.assertEquals(3000L, statisticsManager.getCurrentTimerDelay());
330         statisticsManager.calculateTimerDelay(timeCounter);
331         Assert.assertEquals(6000L, statisticsManager.getCurrentTimerDelay());
332     }
333
334     @Test
335     public void testPollStatistics() throws Exception {
336         final StatisticsContext statisticsContext = Mockito.mock(StatisticsContext.class);
337         final TimeCounter mockTimerCounter = Mockito.mock(TimeCounter.class);
338
339         statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
340         verify(mockedDeviceContext).getDeviceState();
341
342         statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
343
344         statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
345
346         when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateCheckedFuture(Boolean.TRUE));
347         when(statisticsContext.isSchedulingEnabled()).thenReturn(Boolean.TRUE);
348         statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
349         verify(mockTimerCounter).markStart();
350         verify(mockTimerCounter).addTimeMark();
351
352         when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateFailedFuture(new Throwable("error msg")));
353         statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
354         verify(mockTimerCounter,times(2)).addTimeMark();
355     }
356 }