Merge "BUG 6179 - Turning off flow removed notification"
[openflowplugin.git] / openflowplugin-impl / src / test / java / org / opendaylight / openflowplugin / impl / device / DeviceManagerImplTest.java
1 /*
2  *
3  *  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
4  *  *
5  *  * This program and the accompanying materials are made available under the
6  *  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  *  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  *
9  *
10  */
11
12 package org.opendaylight.openflowplugin.impl.device;
13
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Mockito.doThrow;
16 import static org.mockito.Mockito.inOrder;
17 import static org.mockito.Mockito.mock;
18 import static org.mockito.Mockito.verify;
19 import static org.mockito.Mockito.when;
20
21 import com.google.common.util.concurrent.CheckedFuture;
22 import com.google.common.util.concurrent.FutureCallback;
23 import com.google.common.util.concurrent.Futures;
24 import io.netty.util.TimerTask;
25 import java.lang.reflect.Field;
26 import java.math.BigInteger;
27 import java.util.Collections;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.TimeUnit;
30 import org.junit.Assert;
31 import org.junit.Before;
32 import org.junit.Test;
33 import org.junit.runner.RunWith;
34 import org.mockito.InOrder;
35 import org.mockito.Matchers;
36 import org.mockito.Mock;
37 import org.mockito.Mockito;
38 import org.mockito.invocation.InvocationOnMock;
39 import org.mockito.runners.MockitoJUnitRunner;
40 import org.mockito.stubbing.Answer;
41 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
42 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
43 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
44 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
45 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
46 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
47 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
48 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandler;
49 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
50 import org.opendaylight.openflowplugin.api.OFConstants;
51 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
52 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
53 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
54 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
55 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
56 import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
57 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
58 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
59 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
60 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
61 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
62 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
63 import org.opendaylight.openflowplugin.openflow.md.util.OpenflowPortsUtil;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.CapabilitiesV10;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.features.reply.PhyPortBuilder;
71
72 @RunWith(MockitoJUnitRunner.class)
73 public class DeviceManagerImplTest {
74
75     private static final long TEST_VALUE_GLOBAL_NOTIFICATION_QUOTA = 2000l;
76     private static final int barrierCountLimit = 25600;
77     private static final int barrierIntervalNanos = 500;
78     public static final NodeId DUMMY_NODE_ID = new NodeId("dummyNodeId");
79
80     @Mock
81     CheckedFuture<Void, TransactionCommitFailedException> mockedFuture;
82     @Mock
83     private FeaturesReply mockFeatures;
84     @Mock
85     private OutboundQueue outboundQueueProvider;
86     @Mock
87     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
88     @Mock
89     private DeviceTerminationPhaseHandler deviceTerminationPhaseHandler;
90     @Mock
91     private TranslatorLibrary translatorLibrary;
92     @Mock
93     private ConnectionContext mockConnectionContext;
94     @Mock
95     private ConnectionAdapter mockedConnectionAdapter;
96     @Mock
97     private DeviceContextImpl mockedDeviceContext;
98     @Mock
99     private NodeId mockedNodeId;
100     @Mock
101     private LifecycleConductor lifecycleConductor;
102     @Mock
103     private MessageIntelligenceAgency messageIntelligenceAgency;
104     @Mock
105     private DeviceInfo deviceInfo;
106
107     @Before
108     public void setUp() throws Exception {
109         OpenflowPortsUtil.init();
110
111         when(mockConnectionContext.getNodeId()).thenReturn(DUMMY_NODE_ID);
112         when(mockConnectionContext.getFeatures()).thenReturn(mockFeatures);
113         when(mockConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
114         when(mockConnectionContext.getDeviceInfo()).thenReturn(deviceInfo);
115         when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockConnectionContext);
116         when(deviceInfo.getNodeId()).thenReturn(DUMMY_NODE_ID);
117
118         final Capabilities capabilitiesV13 = mock(Capabilities.class);
119         final CapabilitiesV10 capabilitiesV10 = mock(CapabilitiesV10.class);
120         when(mockFeatures.getCapabilities()).thenReturn(capabilitiesV13);
121         when(mockFeatures.getCapabilitiesV10()).thenReturn(capabilitiesV10);
122         when(mockFeatures.getDatapathId()).thenReturn(BigInteger.valueOf(21L));
123
124         when(lifecycleConductor.getMessageIntelligenceAgency()).thenReturn(messageIntelligenceAgency);
125     }
126
127     @Test(expected = IllegalStateException.class)
128     public void onDeviceContextLevelUpFailTest() throws Exception {
129         onDeviceContextLevelUp(true);
130     }
131
132     @Test
133     public void onDeviceContextLevelUpSuccessTest() throws Exception {
134         onDeviceContextLevelUp(false);
135     }
136
137     private DeviceManagerImpl prepareDeviceManager() {
138         return prepareDeviceManager(false);
139     }
140
141     private DeviceManagerImpl prepareDeviceManager(final boolean withException) {
142         final DataBroker mockedDataBroker = mock(DataBroker.class);
143         final WriteTransaction mockedWriteTransaction = mock(WriteTransaction.class);
144
145         final BindingTransactionChain mockedTxChain = mock(BindingTransactionChain.class);
146         final WriteTransaction mockedWTx = mock(WriteTransaction.class);
147         when(mockedTxChain.newWriteOnlyTransaction()).thenReturn(mockedWTx);
148         when(mockedDataBroker.createTransactionChain(any(TransactionChainListener.class))).thenReturn
149                 (mockedTxChain);
150         when(mockedDataBroker.newWriteOnlyTransaction()).thenReturn(mockedWriteTransaction);
151
152         when(mockedWriteTransaction.submit()).thenReturn(mockedFuture);
153
154         final DeviceManagerImpl deviceManager = new DeviceManagerImpl(mockedDataBroker,
155                 TEST_VALUE_GLOBAL_NOTIFICATION_QUOTA, false, barrierIntervalNanos, barrierCountLimit, lifecycleConductor, true);
156
157         deviceManager.setDeviceInitializationPhaseHandler(deviceInitPhaseHandler);
158         deviceManager.setDeviceTerminationPhaseHandler(deviceTerminationPhaseHandler);
159
160         return deviceManager;
161     }
162
163     public void onDeviceContextLevelUp(final boolean withException) throws Exception {
164         final DeviceManagerImpl deviceManager = prepareDeviceManager(withException);
165         final DeviceState mockedDeviceState = mock(DeviceState.class);
166         when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
167
168         if (withException) {
169             doThrow(new IllegalStateException("dummy")).when(mockedDeviceContext).initialSubmitTransaction();
170         }
171         deviceManager.addDeviceContextToMap(deviceInfo, mockedDeviceContext);
172         deviceManager.onDeviceContextLevelUp(deviceInfo);
173         if (withException) {
174             verify(mockedDeviceContext).close();
175         } else {
176             verify(mockedDeviceContext).initialSubmitTransaction();
177             verify(mockedDeviceContext).onPublished();
178         }
179     }
180
181     @Test
182     public void deviceConnectedTest() throws Exception{
183         final DeviceManagerImpl deviceManager = prepareDeviceManager();
184         injectMockTranslatorLibrary(deviceManager);
185         final ConnectionContext mockConnectionContext = buildMockConnectionContext(OFConstants.OFP_VERSION_1_3);
186
187         deviceManager.deviceConnected(mockConnectionContext);
188
189         final InOrder order = inOrder(mockConnectionContext);
190         order.verify(mockConnectionContext).setOutboundQueueProvider(any(OutboundQueueProvider.class));
191         order.verify(mockConnectionContext).setOutboundQueueHandleRegistration(
192                 Mockito.<OutboundQueueHandlerRegistration<OutboundQueueProvider>>any());
193         verify(deviceInitPhaseHandler).onDeviceContextLevelUp(Matchers.<DeviceInfo>any());
194     }
195
196     @Test
197     public void deviceConnectedV10Test() throws Exception{
198         final DeviceManagerImpl deviceManager = prepareDeviceManager();
199         injectMockTranslatorLibrary(deviceManager);
200         final ConnectionContext mockConnectionContext = buildMockConnectionContext(OFConstants.OFP_VERSION_1_0);
201
202         final PhyPortBuilder phyPort = new PhyPortBuilder()
203                 .setPortNo(41L);
204         when(mockFeatures.getPhyPort()).thenReturn(Collections.singletonList(phyPort.build()));
205         final MessageTranslator<Object, Object> mockedTranslator = mock(MessageTranslator.class);
206         when(mockedTranslator.translate(Matchers.<Object>any(), Matchers.<DeviceInfo>any(), Matchers.any()))
207                 .thenReturn(null);
208         when(translatorLibrary.lookupTranslator(Matchers.<TranslatorKey>any())).thenReturn(mockedTranslator);
209
210         deviceManager.deviceConnected(mockConnectionContext);
211
212         final InOrder order = inOrder(mockConnectionContext);
213         order.verify(mockConnectionContext).setOutboundQueueProvider(any(OutboundQueueProvider.class));
214         order.verify(mockConnectionContext).setOutboundQueueHandleRegistration(
215                 Mockito.<OutboundQueueHandlerRegistration<OutboundQueueProvider>>any());
216         verify(deviceInitPhaseHandler).onDeviceContextLevelUp(Matchers.<DeviceInfo>any());
217     }
218
219     @Test
220     public void deviceDisconnectedTest() throws Exception {
221         final DeviceState deviceState = mock(DeviceState.class);
222
223         final DeviceManagerImpl deviceManager = prepareDeviceManager();
224         injectMockTranslatorLibrary(deviceManager);
225
226         final ConnectionContext connectionContext = buildMockConnectionContext(OFConstants.OFP_VERSION_1_3);
227         when(connectionContext.getNodeId()).thenReturn(mockedNodeId);
228
229         final DeviceContext deviceContext = mock(DeviceContext.class);
230         when(deviceContext.shuttingDownDataStoreTransactions()).thenReturn(Futures.immediateCheckedFuture(null));
231         when(deviceContext.getPrimaryConnectionContext()).thenReturn(connectionContext);
232         when(deviceContext.getDeviceState()).thenReturn(deviceState);
233
234         final ConcurrentHashMap<DeviceInfo, DeviceContext> deviceContexts = getContextsCollection(deviceManager);
235         deviceContexts.put(deviceInfo, deviceContext);
236
237         deviceManager.onDeviceDisconnected(connectionContext);
238
239         verify(lifecycleConductor).newTimeout(Mockito.<TimerTask>any(), Mockito.anyLong(), Mockito.<TimeUnit>any());
240     }
241
242     protected ConnectionContext buildMockConnectionContext(final short ofpVersion) {
243         when(mockFeatures.getVersion()).thenReturn(ofpVersion);
244         when(outboundQueueProvider.reserveEntry()).thenReturn(43L);
245         Mockito.doAnswer(new Answer<Void>() {
246             @Override
247             public Void answer(final InvocationOnMock invocation) throws Throwable {
248                 final FutureCallback<OfHeader> callBack = (FutureCallback<OfHeader>) invocation.getArguments()[2];
249                 callBack.onSuccess(null);
250                 return null;
251             }
252         })
253                 .when(outboundQueueProvider)
254                 .commitEntry(Matchers.anyLong(), Matchers.<MultipartRequestInput>any(), Matchers.<FutureCallback<OfHeader>>any());
255
256         when(mockedConnectionAdapter.registerOutboundQueueHandler(Matchers.<OutboundQueueHandler>any(), Matchers.anyInt(), Matchers.anyLong()))
257                 .thenAnswer(new Answer<OutboundQueueHandlerRegistration<OutboundQueueHandler>>() {
258                     @Override
259                     public OutboundQueueHandlerRegistration<OutboundQueueHandler> answer(final InvocationOnMock invocation) throws Throwable {
260                         final OutboundQueueHandler handler = (OutboundQueueHandler) invocation.getArguments()[0];
261                         handler.onConnectionQueueChanged(outboundQueueProvider);
262                         return null;
263                     }
264                 });
265
266         when(mockConnectionContext.getOutboundQueueProvider()).thenReturn(outboundQueueProvider);
267         return mockConnectionContext;
268     }
269
270     private void injectMockTranslatorLibrary(final DeviceManagerImpl deviceManager) {
271         deviceManager.setTranslatorLibrary(translatorLibrary);
272     }
273
274     @Test
275     public void testClose() throws Exception {
276         final DeviceContext deviceContext = mock(DeviceContext.class);
277         final DeviceManagerImpl deviceManager = prepareDeviceManager();
278         final ConcurrentHashMap<DeviceInfo, DeviceContext> deviceContexts = getContextsCollection(deviceManager);
279         deviceContexts.put(deviceInfo, deviceContext);
280         Assert.assertEquals(1, deviceContexts.size());
281
282         deviceManager.close();
283
284         verify(deviceContext).shutdownConnection();
285         verify(deviceContext, Mockito.never()).close();
286     }
287
288     private static ConcurrentHashMap<DeviceInfo, DeviceContext> getContextsCollection(final DeviceManagerImpl deviceManager) throws NoSuchFieldException, IllegalAccessException {
289         // HACK: contexts collection for testing shall be accessed in some more civilized way
290         final Field contextsField = DeviceManagerImpl.class.getDeclaredField("deviceContexts");
291         Assert.assertNotNull(contextsField);
292         contextsField.setAccessible(true);
293         return (ConcurrentHashMap<DeviceInfo, DeviceContext>) contextsField.get(deviceManager);
294     }
295
296 }