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