Merge "BUG-5839: Removing groups and meters on being stale-marked"
[openflowplugin.git] / openflowplugin-impl / src / test / java / org / opendaylight / openflowplugin / impl / statistics / StatisticsManagerImplTest.java
1 package org.opendaylight.openflowplugin.impl.statistics;
2
3 import static org.mockito.Mockito.verify;
4 import static org.mockito.Mockito.when;
5
6 import com.google.common.base.Optional;
7 import com.google.common.util.concurrent.FutureCallback;
8 import io.netty.util.HashedWheelTimer;
9 import io.netty.util.Timeout;
10 import io.netty.util.TimerTask;
11 import java.lang.reflect.Field;
12 import java.math.BigInteger;
13 import java.util.Collections;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.concurrent.Future;
17 import java.util.concurrent.TimeUnit;
18 import org.junit.Assert;
19 import org.junit.Before;
20 import org.junit.Test;
21 import org.junit.runner.RunWith;
22 import org.mockito.ArgumentCaptor;
23 import org.mockito.Captor;
24 import org.mockito.Matchers;
25 import org.mockito.Mock;
26 import org.mockito.Mockito;
27 import org.mockito.invocation.InvocationOnMock;
28 import org.mockito.runners.MockitoJUnitRunner;
29 import org.mockito.stubbing.Answer;
30 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
31 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
32 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
33 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
34 import org.opendaylight.openflowplugin.api.OFConstants;
35 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
36 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
37 import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
38 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
39 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
40 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
41 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
42 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
43 import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
44 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
45 import org.opendaylight.openflowplugin.api.openflow.registry.ItemLifeCycleRegistry;
46 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
47 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
48 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
49 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
50 import org.opendaylight.openflowplugin.impl.registry.flow.DeviceFlowRegistryImpl;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.ChangeStatisticsWorkModeInputBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsManagerControlService;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsWorkMode;
60 import org.opendaylight.yangtools.yang.common.RpcResult;
61 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65
66 @RunWith(MockitoJUnitRunner.class)
67 public class StatisticsManagerImplTest {
68
69     private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImplTest.class);
70
71     private static final BigInteger DUMMY_DATAPATH_ID = new BigInteger("444");
72     private static final Short DUMMY_VERSION = OFConstants.OFP_VERSION_1_3;
73
74     @Mock
75     RequestContextStack mockedRequestContextStack;
76     @Mock
77     ConnectionContext mockedPrimConnectionContext;
78     @Mock
79     FeaturesReply mockedFeatures;
80     @Mock
81     ConnectionAdapter mockedConnectionAdapter;
82     @Mock
83     MessageSpy mockedMessagSpy;
84     @Mock
85     DeviceContext mockedDeviceContext;
86     @Mock
87     DeviceState mockedDeviceState;
88     @Mock
89     DeviceInitializationPhaseHandler mockedDevicePhaseHandler;
90     @Mock
91     DeviceTerminationPhaseHandler mockedTerminationPhaseHandler;
92     @Mock
93     private RpcProviderRegistry rpcProviderRegistry;
94     @Mock
95     private HashedWheelTimer hashedWheelTimer;
96     @Mock
97     private OutboundQueue outboundQueue;
98     @Mock
99     private MultiMsgCollector multiMagCollector;
100     @Mock
101     private ItemLifeCycleRegistry itemLifeCycleRegistry;
102     @Captor
103     private ArgumentCaptor<ItemLifecycleListener> itemLifeCycleListenerCapt;
104     @Mock
105     private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> serviceControlRegistration;
106     @Mock
107     private DeviceManager deviceManager;
108     @Mock
109     private LifecycleConductor conductor;
110
111     private RequestContext<List<MultipartReply>> currentRequestContext;
112     private StatisticsManagerImpl statisticsManager;
113
114     @Before
115     public void initialization() {
116         when(mockedFeatures.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
117         when(mockedFeatures.getVersion()).thenReturn(DUMMY_VERSION);
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(new NodeId("ut-node:123"));
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
132         when(mockedDeviceState.getNodeId()).thenReturn(new NodeId("ofp-unit-dummy-node-id"));
133
134         when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedPrimConnectionContext);
135         when(mockedDeviceContext.getMessageSpy()).thenReturn(mockedMessagSpy);
136         when(mockedDeviceContext.getDeviceFlowRegistry()).thenReturn(new DeviceFlowRegistryImpl());
137         when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
138         when(mockedDeviceContext.getMultiMsgCollector(
139                 Matchers.<RequestContext<List<MultipartReply>>>any())).thenAnswer(
140                 new Answer<MultiMsgCollector>() {
141                     @Override
142                     public MultiMsgCollector answer(InvocationOnMock invocation) throws Throwable {
143                         currentRequestContext = (RequestContext<List<MultipartReply>>) invocation.getArguments()[0];
144                         return multiMagCollector;
145                     }
146                 }
147         );
148         when(mockedDeviceContext.getItemLifeCycleSourceRegistry()).thenReturn(itemLifeCycleRegistry);
149         when(rpcProviderRegistry.addRpcImplementation(
150                 Matchers.eq(StatisticsManagerControlService.class),
151                 Matchers.<StatisticsManagerControlService>any())).thenReturn(serviceControlRegistration);
152
153         statisticsManager = new StatisticsManagerImpl(rpcProviderRegistry, false, conductor);
154         when(deviceManager.getDeviceContextFromNodeId(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
155         when(conductor.getDeviceContext(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
156     }
157
158     @Test
159     public void testOnDeviceContextLevelUp() throws Exception {
160         statisticsManager = new StatisticsManagerImpl(rpcProviderRegistry, true, conductor);
161         Mockito.doAnswer(new Answer<Void>() {
162             @Override
163             public Void answer(final InvocationOnMock invocation) throws Throwable {
164                 final FutureCallback<OfHeader> callback = (FutureCallback<OfHeader>) invocation.getArguments()[2];
165                 LOG.debug("committing entry: {}", ((MultipartRequestInput) invocation.getArguments()[1]).getType());
166                 callback.onSuccess(null);
167                 currentRequestContext.setResult(RpcResultBuilder.<List<MultipartReply>>success().build());
168                 return null;
169             }
170         }).when(outboundQueue)
171                 .commitEntry(Matchers.anyLong(), Matchers.<OfHeader>any(), Matchers.<FutureCallback<OfHeader>>any());
172
173         statisticsManager.setDeviceInitializationPhaseHandler(mockedDevicePhaseHandler);
174         statisticsManager.onDeviceContextLevelUp(mockedDeviceContext.getDeviceState().getNodeId());
175
176         verify(mockedDeviceContext, Mockito.never()).reserveXidForDeviceMessage();
177         verify(mockedDeviceState).setDeviceSynchronized(true);
178         verify(mockedDevicePhaseHandler).onDeviceContextLevelUp(mockedDeviceContext.getDeviceState().getNodeId());
179         verify(hashedWheelTimer, Mockito.never()).newTimeout(Matchers.<TimerTask>any(), Matchers.anyLong(), Matchers.<TimeUnit>any());
180     }
181
182     @Test
183     public void testOnDeviceContextClosed() throws Exception {
184         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
185         final Map<NodeId, StatisticsContext> contextsMap = getContextsMap(statisticsManager);
186
187         contextsMap.put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
188         Assert.assertEquals(1, contextsMap.size());
189
190         statisticsManager.setDeviceTerminationPhaseHandler(mockedTerminationPhaseHandler);
191         statisticsManager.onDeviceContextLevelDown(mockedDeviceContext);
192         verify(statisticContext).close();
193         verify(mockedTerminationPhaseHandler).onDeviceContextLevelDown(mockedDeviceContext);
194         Assert.assertEquals(0, contextsMap.size());
195     }
196
197     private static Map<NodeId, StatisticsContext> getContextsMap(final StatisticsManagerImpl statisticsManager)
198             throws NoSuchFieldException, IllegalAccessException {
199         // HACK: contexts map for testing shall be accessed in some more civilized way
200         final Field contextsField = StatisticsManagerImpl.class.getDeclaredField("contexts");
201         Assert.assertNotNull(contextsField);
202         contextsField.setAccessible(true);
203         return (Map<NodeId, StatisticsContext>) contextsField.get(statisticsManager);
204     }
205
206     @Test
207     public void testGetStatisticsWorkMode() throws Exception {
208         final Future<RpcResult<GetStatisticsWorkModeOutput>> workMode = statisticsManager.getStatisticsWorkMode();
209         Assert.assertTrue(workMode.isDone());
210         Assert.assertTrue(workMode.get().isSuccessful());
211         Assert.assertNotNull(workMode.get().getResult());
212         Assert.assertEquals(StatisticsWorkMode.COLLECTALL, workMode.get().getResult().getMode());
213     }
214
215     /**
216      * switching to {@link StatisticsWorkMode#FULLYDISABLED}; no pollTimeout and no lifecycleRegistry
217      *
218      * @throws Exception
219      */
220     @Test
221     public void testChangeStatisticsWorkMode1() throws Exception {
222         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
223         when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
224         when(statisticContext.getPollTimeout()).thenReturn(
225                 Optional.<Timeout>absent());
226         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
227                 Collections.<ItemLifeCycleSource>emptyList());
228
229         getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
230
231         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
232                 new ChangeStatisticsWorkModeInputBuilder()
233                         .setMode(StatisticsWorkMode.FULLYDISABLED);
234
235         final Future<RpcResult<Void>> workMode = statisticsManager
236                 .changeStatisticsWorkMode(changeStatisticsWorkModeInputBld.build());
237
238         checkWorkModeChangeOutcome(workMode);
239         Mockito.verify(itemLifeCycleRegistry).getLifeCycleSources();
240         Mockito.verify(statisticContext).getPollTimeout();
241     }
242
243     private static void checkWorkModeChangeOutcome(Future<RpcResult<Void>> workMode) throws InterruptedException, java.util.concurrent.ExecutionException {
244         Assert.assertTrue(workMode.isDone());
245         Assert.assertTrue(workMode.get().isSuccessful());
246     }
247
248
249     /**
250      * switching to {@link StatisticsWorkMode#FULLYDISABLED}; with pollTimeout and lifecycleRegistry
251      *
252      * @throws Exception
253      */
254     @Test
255     public void testChangeStatisticsWorkMode2() throws Exception {
256         final Timeout pollTimeout = Mockito.mock(Timeout.class);
257         final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
258         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
259         when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
260         when(statisticContext.getPollTimeout()).thenReturn(
261                 Optional.of(pollTimeout));
262         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
263                 Collections.singletonList(itemLifecycleSource));
264
265         getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
266
267         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
268                 new ChangeStatisticsWorkModeInputBuilder()
269                         .setMode(StatisticsWorkMode.FULLYDISABLED);
270
271         Future<RpcResult<Void>> workMode = statisticsManager.changeStatisticsWorkMode(changeStatisticsWorkModeInputBld.build());
272         checkWorkModeChangeOutcome(workMode);
273
274         Mockito.verify(itemLifeCycleRegistry).getLifeCycleSources();
275         Mockito.verify(statisticContext).getPollTimeout();
276         Mockito.verify(pollTimeout).cancel();
277         Mockito.verify(itemLifecycleSource).setItemLifecycleListener(Matchers.<ItemLifecycleListener>any());
278     }
279
280     /**
281      * switching to {@link StatisticsWorkMode#FULLYDISABLED} and back
282      * to {@link StatisticsWorkMode#COLLECTALL}; with lifecycleRegistry and pollTimeout
283      *
284      * @throws Exception
285      */
286     @Test
287     public void testChangeStatisticsWorkMode3() throws Exception {
288         final Timeout pollTimeout = Mockito.mock(Timeout.class);
289         final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
290         Mockito.doNothing().when(itemLifecycleSource)
291                 .setItemLifecycleListener(itemLifeCycleListenerCapt.capture());
292
293         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
294         when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
295         when(statisticContext.getPollTimeout()).thenReturn(
296                 Optional.of(pollTimeout));
297         when(statisticContext.getItemLifeCycleListener()).thenReturn(
298                 Mockito.mock(ItemLifecycleListener.class));
299         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
300                 Collections.singletonList(itemLifecycleSource));
301
302         getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
303
304         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
305                 new ChangeStatisticsWorkModeInputBuilder()
306                         .setMode(StatisticsWorkMode.FULLYDISABLED);
307
308         Future<RpcResult<Void>> workMode;
309         workMode = statisticsManager.changeStatisticsWorkMode(
310                 changeStatisticsWorkModeInputBld.build());
311         checkWorkModeChangeOutcome(workMode);
312
313         changeStatisticsWorkModeInputBld.setMode(StatisticsWorkMode.COLLECTALL);
314         workMode = statisticsManager.changeStatisticsWorkMode(
315                 changeStatisticsWorkModeInputBld.build());
316         checkWorkModeChangeOutcome(workMode);
317
318         Mockito.verify(itemLifeCycleRegistry, Mockito.times(2)).getLifeCycleSources();
319         Mockito.verify(statisticContext).getPollTimeout();
320         Mockito.verify(pollTimeout).cancel();
321
322         final List<ItemLifecycleListener> itemLifeCycleListenerValues = itemLifeCycleListenerCapt.getAllValues();
323         Assert.assertEquals(2, itemLifeCycleListenerValues.size());
324         Assert.assertNotNull(itemLifeCycleListenerValues.get(0));
325         Assert.assertNull(itemLifeCycleListenerValues.get(1));
326     }
327
328     @Test
329     public void testClose() throws Exception {
330         statisticsManager.close();
331         Mockito.verify(serviceControlRegistration).close();
332     }
333
334     @Test
335     public void testCalculateTimerDelay() throws Exception {
336         final TimeCounter timeCounter = Mockito.mock(TimeCounter.class);
337         when(timeCounter.getAverageTimeBetweenMarks()).thenReturn((Long)2000L, (Long)4000L);
338
339         statisticsManager.calculateTimerDelay(timeCounter);
340         Assert.assertEquals(3000L, StatisticsManagerImpl.getCurrentTimerDelay());
341         statisticsManager.calculateTimerDelay(timeCounter);
342         Assert.assertEquals(6000L, StatisticsManagerImpl.getCurrentTimerDelay());
343     }
344 }