Bug 5540 - Remove ConvertorManager singleton
[openflowplugin.git] / openflowplugin-impl / src / test / java / org / opendaylight / openflowplugin / impl / device / DeviceManagerImplTest.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
9 package org.opendaylight.openflowplugin.impl.device;
10
11 import static org.mockito.Matchers.any;
12 import static org.mockito.Mockito.doThrow;
13 import static org.mockito.Mockito.inOrder;
14 import static org.mockito.Mockito.mock;
15 import static org.mockito.Mockito.verify;
16 import static org.mockito.Mockito.when;
17
18 import com.google.common.util.concurrent.CheckedFuture;
19 import com.google.common.util.concurrent.FutureCallback;
20 import com.google.common.util.concurrent.Futures;
21 import io.netty.util.TimerTask;
22 import java.lang.reflect.Field;
23 import java.math.BigInteger;
24 import java.util.Collections;
25 import java.util.concurrent.ConcurrentHashMap;
26 import java.util.concurrent.TimeUnit;
27 import org.junit.Assert;
28 import org.junit.Before;
29 import org.junit.Test;
30 import org.junit.runner.RunWith;
31 import org.mockito.InOrder;
32 import org.mockito.Matchers;
33 import org.mockito.Mock;
34 import org.mockito.Mockito;
35 import org.mockito.invocation.InvocationOnMock;
36 import org.mockito.runners.MockitoJUnitRunner;
37 import org.mockito.stubbing.Answer;
38 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
39 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
40 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
41 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
42 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
43 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
44 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
45 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandler;
46 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
47 import org.opendaylight.openflowplugin.api.OFConstants;
48 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
49 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
50 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
51 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
52 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
53 import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
54 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
55 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
56 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
57 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
58 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
59 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
60 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
61 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
62 import org.opendaylight.openflowplugin.openflow.md.util.OpenflowPortsUtil;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.CapabilitiesV10;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.features.reply.PhyPortBuilder;
70
71 @RunWith(MockitoJUnitRunner.class)
72 public class DeviceManagerImplTest {
73
74     private static final long TEST_VALUE_GLOBAL_NOTIFICATION_QUOTA = 2000l;
75     private static final int barrierCountLimit = 25600;
76     private static final int barrierIntervalNanos = 500;
77     public static final NodeId DUMMY_NODE_ID = new NodeId("dummyNodeId");
78
79     @Mock
80     CheckedFuture<Void, TransactionCommitFailedException> mockedFuture;
81     @Mock
82     private FeaturesReply mockFeatures;
83     @Mock
84     private OutboundQueue outboundQueueProvider;
85     @Mock
86     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
87     @Mock
88     private DeviceTerminationPhaseHandler deviceTerminationPhaseHandler;
89     @Mock
90     private TranslatorLibrary translatorLibrary;
91     @Mock
92     private ConnectionContext mockConnectionContext;
93     @Mock
94     private ConnectionAdapter mockedConnectionAdapter;
95     @Mock
96     private DeviceContextImpl mockedDeviceContext;
97     @Mock
98     private NodeId mockedNodeId;
99     @Mock
100     private LifecycleConductor lifecycleConductor;
101     @Mock
102     private MessageIntelligenceAgency messageIntelligenceAgency;
103     @Mock
104     private DeviceInfo deviceInfo;
105
106     @Before
107     public void setUp() throws Exception {
108         OpenflowPortsUtil.init();
109
110         when(mockConnectionContext.getNodeId()).thenReturn(DUMMY_NODE_ID);
111         when(mockConnectionContext.getFeatures()).thenReturn(mockFeatures);
112         when(mockConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
113         when(mockConnectionContext.getDeviceInfo()).thenReturn(deviceInfo);
114         when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockConnectionContext);
115         when(deviceInfo.getNodeId()).thenReturn(DUMMY_NODE_ID);
116
117         final Capabilities capabilitiesV13 = mock(Capabilities.class);
118         final CapabilitiesV10 capabilitiesV10 = mock(CapabilitiesV10.class);
119         when(mockFeatures.getCapabilities()).thenReturn(capabilitiesV13);
120         when(mockFeatures.getCapabilitiesV10()).thenReturn(capabilitiesV10);
121         when(mockFeatures.getDatapathId()).thenReturn(BigInteger.valueOf(21L));
122
123         when(lifecycleConductor.getMessageIntelligenceAgency()).thenReturn(messageIntelligenceAgency);
124     }
125
126     @Test(expected = IllegalStateException.class)
127     public void onDeviceContextLevelUpFailTest() throws Exception {
128         onDeviceContextLevelUp(true);
129     }
130
131     @Test
132     public void onDeviceContextLevelUpSuccessTest() throws Exception {
133         onDeviceContextLevelUp(false);
134     }
135
136     private DeviceManagerImpl prepareDeviceManager() {
137         return prepareDeviceManager(false);
138     }
139
140     private DeviceManagerImpl prepareDeviceManager(final boolean withException) {
141         final DataBroker mockedDataBroker = mock(DataBroker.class);
142         final WriteTransaction mockedWriteTransaction = mock(WriteTransaction.class);
143
144         final BindingTransactionChain mockedTxChain = mock(BindingTransactionChain.class);
145         final WriteTransaction mockedWTx = mock(WriteTransaction.class);
146         when(mockedTxChain.newWriteOnlyTransaction()).thenReturn(mockedWTx);
147         when(mockedDataBroker.createTransactionChain(any(TransactionChainListener.class))).thenReturn
148                 (mockedTxChain);
149         when(mockedDataBroker.newWriteOnlyTransaction()).thenReturn(mockedWriteTransaction);
150
151         when(mockedWriteTransaction.submit()).thenReturn(mockedFuture);
152
153         final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();
154         final DeviceManagerImpl deviceManager = new DeviceManagerImpl(mockedDataBroker,
155                 TEST_VALUE_GLOBAL_NOTIFICATION_QUOTA, false, barrierIntervalNanos, barrierCountLimit, lifecycleConductor, true, convertorManager);
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 }