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