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