Merge "Bug 6110: Fixed bugs in statistics manager due to race condition." into stable...
[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.clustering.EntityOwnershipListenerRegistration;
41 import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
42 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
43 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
44 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
45 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
46 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
47 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandler;
48 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
49 import org.opendaylight.openflowplugin.api.OFConstants;
50 import org.opendaylight.openflowplugin.api.openflow.OFPContext;
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.LifecycleService;
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.core.sal.convertor.ConvertorExecutor;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
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 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
74
75 @RunWith(MockitoJUnitRunner.class)
76 public class DeviceManagerImplTest {
77
78     private static final long TEST_VALUE_GLOBAL_NOTIFICATION_QUOTA = 2000l;
79     private static final int barrierCountLimit = 25600;
80     private static final int barrierIntervalNanos = 500;
81     public static final NodeId DUMMY_NODE_ID = new NodeId("dummyNodeId");
82
83     @Mock
84     CheckedFuture<Void, TransactionCommitFailedException> mockedFuture;
85     @Mock
86     private FeaturesReply mockFeatures;
87     @Mock
88     private OutboundQueue outboundQueueProvider;
89     @Mock
90     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
91     @Mock
92     private DeviceTerminationPhaseHandler deviceTerminationPhaseHandler;
93     @Mock
94     private TranslatorLibrary translatorLibrary;
95     @Mock
96     private ConnectionContext mockConnectionContext;
97     @Mock
98     private ConnectionAdapter mockedConnectionAdapter;
99     @Mock
100     private DeviceContextImpl mockedDeviceContext;
101     @Mock
102     private NodeId mockedNodeId;
103     @Mock
104     private MessageIntelligenceAgency messageIntelligenceAgency;
105     @Mock
106     private DeviceInfo deviceInfo;
107     @Mock
108     private LifecycleService lifecycleService;
109     @Mock
110     private ClusterSingletonServiceProvider clusterSingletonServiceProvider;
111     @Mock
112     private EntityOwnershipService entityOwnershipService;
113     @Mock
114     private EntityOwnershipListenerRegistration entityOwnershipListenerRegistration;
115     @Mock
116     private ConvertorExecutor convertorExecutor;
117     @Mock
118     private KeyedInstanceIdentifier<Node, NodeKey> key;
119     @Before
120     public void setUp() throws Exception {
121         when(mockConnectionContext.getNodeId()).thenReturn(DUMMY_NODE_ID);
122         when(mockConnectionContext.getFeatures()).thenReturn(mockFeatures);
123         when(mockConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
124         when(mockConnectionContext.getDeviceInfo()).thenReturn(deviceInfo);
125         when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockConnectionContext);
126         when(deviceInfo.getNodeId()).thenReturn(DUMMY_NODE_ID);
127
128         final Capabilities capabilitiesV13 = mock(Capabilities.class);
129         final CapabilitiesV10 capabilitiesV10 = mock(CapabilitiesV10.class);
130         when(mockFeatures.getCapabilities()).thenReturn(capabilitiesV13);
131         when(mockFeatures.getCapabilitiesV10()).thenReturn(capabilitiesV10);
132         when(mockFeatures.getDatapathId()).thenReturn(BigInteger.valueOf(21L));
133     }
134
135     @Test
136     public void onDeviceContextLevelUpSuccessTest() throws Exception {
137         onDeviceContextLevelUp(false);
138     }
139
140     private DeviceManagerImpl prepareDeviceManager() {
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         when(entityOwnershipService.registerListener(any(), any())).thenReturn(entityOwnershipListenerRegistration);
153
154         final DeviceManagerImpl deviceManager = new DeviceManagerImpl(
155                 mockedDataBroker,
156                 TEST_VALUE_GLOBAL_NOTIFICATION_QUOTA,
157                 false,
158                 barrierIntervalNanos,
159                 barrierCountLimit,
160                 messageIntelligenceAgency,
161                 true,
162                 clusterSingletonServiceProvider,
163                 entityOwnershipService, new HashedWheelTimer(), convertorExecutor, false, null
164         );
165
166         deviceManager.setDeviceInitializationPhaseHandler(deviceInitPhaseHandler);
167         deviceManager.setDeviceTerminationPhaseHandler(deviceTerminationPhaseHandler);
168
169         return deviceManager;
170     }
171
172     public void onDeviceContextLevelUp(final boolean withException) throws Exception {
173         final DeviceManagerImpl deviceManager = prepareDeviceManager();
174         final DeviceState mockedDeviceState = mock(DeviceState.class);
175         when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
176
177         if (withException) {
178             doThrow(new IllegalStateException("dummy")).when(mockedDeviceContext).initialSubmitTransaction();
179         }
180         deviceManager.addDeviceContextToMap(deviceInfo, mockedDeviceContext);
181         deviceManager.onDeviceContextLevelUp(deviceInfo, lifecycleService);
182         if (withException) {
183             verify(mockedDeviceContext).close();
184         } else {
185             verify(mockedDeviceContext).onPublished();
186         }
187     }
188
189     @Test
190     public void deviceConnectedTest() throws Exception{
191         final DeviceManagerImpl deviceManager = prepareDeviceManager();
192         injectMockTranslatorLibrary(deviceManager);
193         final ConnectionContext mockConnectionContext = buildMockConnectionContext(OFConstants.OFP_VERSION_1_3);
194
195         deviceManager.deviceConnected(mockConnectionContext);
196
197         final InOrder order = inOrder(mockConnectionContext);
198         order.verify(mockConnectionContext).setOutboundQueueProvider(any(OutboundQueueProvider.class));
199         order.verify(mockConnectionContext).setOutboundQueueHandleRegistration(
200                 Mockito.<OutboundQueueHandlerRegistration<OutboundQueueProvider>>any());
201         verify(deviceInitPhaseHandler).onDeviceContextLevelUp(Matchers.<DeviceInfo>any(), Mockito.<LifecycleService>any());
202     }
203
204     @Test
205     public void deviceConnectedV10Test() throws Exception{
206         final DeviceManagerImpl deviceManager = prepareDeviceManager();
207         injectMockTranslatorLibrary(deviceManager);
208         final ConnectionContext mockConnectionContext = buildMockConnectionContext(OFConstants.OFP_VERSION_1_0);
209
210         final PhyPortBuilder phyPort = new PhyPortBuilder()
211                 .setPortNo(41L);
212         when(mockFeatures.getPhyPort()).thenReturn(Collections.singletonList(phyPort.build()));
213         final MessageTranslator<Object, Object> mockedTranslator = mock(MessageTranslator.class);
214         when(mockedTranslator.translate(Matchers.<Object>any(), Matchers.<DeviceInfo>any(), Matchers.any()))
215                 .thenReturn(null);
216         when(translatorLibrary.lookupTranslator(Matchers.<TranslatorKey>any())).thenReturn(mockedTranslator);
217
218         deviceManager.deviceConnected(mockConnectionContext);
219
220         final InOrder order = inOrder(mockConnectionContext);
221         order.verify(mockConnectionContext).setOutboundQueueProvider(any(OutboundQueueProvider.class));
222         order.verify(mockConnectionContext).setOutboundQueueHandleRegistration(
223                 Mockito.<OutboundQueueHandlerRegistration<OutboundQueueProvider>>any());
224         verify(deviceInitPhaseHandler).onDeviceContextLevelUp(Matchers.<DeviceInfo>any(), Mockito.<LifecycleService>any());
225     }
226
227     @Test
228     public void deviceDisconnectedTest() throws Exception {
229         final DeviceState deviceState = mock(DeviceState.class);
230
231         final DeviceManagerImpl deviceManager = prepareDeviceManager();
232         injectMockTranslatorLibrary(deviceManager);
233
234         final ConnectionContext connectionContext = buildMockConnectionContext(OFConstants.OFP_VERSION_1_3);
235         when(connectionContext.getNodeId()).thenReturn(mockedNodeId);
236
237         final DeviceContext deviceContext = mock(DeviceContext.class);
238         when(deviceContext.shuttingDownDataStoreTransactions()).thenReturn(Futures.immediateCheckedFuture(null));
239         when(deviceContext.getPrimaryConnectionContext()).thenReturn(connectionContext);
240         when(deviceContext.getDeviceState()).thenReturn(deviceState);
241         when(deviceContext.getState()).thenReturn(OFPContext.CONTEXT_STATE.WORKING);
242
243         final ConcurrentHashMap<DeviceInfo, DeviceContext> deviceContexts = getContextsCollection(deviceManager);
244         deviceContexts.put(deviceInfo, deviceContext);
245
246         deviceManager.onDeviceDisconnected(connectionContext);
247     }
248
249     protected ConnectionContext buildMockConnectionContext(final short ofpVersion) {
250         when(mockFeatures.getVersion()).thenReturn(ofpVersion);
251         when(outboundQueueProvider.reserveEntry()).thenReturn(43L);
252         Mockito.doAnswer(new Answer<Void>() {
253             @Override
254             public Void answer(final InvocationOnMock invocation) throws Throwable {
255                 final FutureCallback<OfHeader> callBack = (FutureCallback<OfHeader>) invocation.getArguments()[2];
256                 callBack.onSuccess(null);
257                 return null;
258             }
259         })
260                 .when(outboundQueueProvider)
261                 .commitEntry(Matchers.anyLong(), Matchers.<MultipartRequestInput>any(), Matchers.<FutureCallback<OfHeader>>any());
262
263         when(mockedConnectionAdapter.registerOutboundQueueHandler(Matchers.<OutboundQueueHandler>any(), Matchers.anyInt(), Matchers.anyLong()))
264                 .thenAnswer(new Answer<OutboundQueueHandlerRegistration<OutboundQueueHandler>>() {
265                     @Override
266                     public OutboundQueueHandlerRegistration<OutboundQueueHandler> answer(final InvocationOnMock invocation) throws Throwable {
267                         final OutboundQueueHandler handler = (OutboundQueueHandler) invocation.getArguments()[0];
268                         handler.onConnectionQueueChanged(outboundQueueProvider);
269                         return null;
270                     }
271                 });
272
273         when(mockConnectionContext.getOutboundQueueProvider()).thenReturn(outboundQueueProvider);
274         return mockConnectionContext;
275     }
276
277     private void injectMockTranslatorLibrary(final DeviceManagerImpl deviceManager) {
278         deviceManager.setTranslatorLibrary(translatorLibrary);
279     }
280
281     @Test
282     public void testClose() throws Exception {
283         final DeviceContext deviceContext = mock(DeviceContext.class);
284         final DeviceManagerImpl deviceManager = prepareDeviceManager();
285         final ConcurrentHashMap<DeviceInfo, DeviceContext> deviceContexts = getContextsCollection(deviceManager);
286         deviceContexts.put(deviceInfo, deviceContext);
287         Assert.assertEquals(1, deviceContexts.size());
288
289         deviceManager.close();
290
291         verify(deviceContext).shutdownConnection();
292         verify(deviceContext, Mockito.never()).close();
293     }
294
295     private static ConcurrentHashMap<DeviceInfo, DeviceContext> getContextsCollection(final DeviceManagerImpl deviceManager) throws NoSuchFieldException, IllegalAccessException {
296         // HACK: contexts collection for testing shall be accessed in some more civilized way
297         final Field contextsField = DeviceManagerImpl.class.getDeclaredField("deviceContexts");
298         Assert.assertNotNull(contextsField);
299         contextsField.setAccessible(true);
300         return (ConcurrentHashMap<DeviceInfo, DeviceContext>) contextsField.get(deviceManager);
301     }
302
303 }