Merge changes from topic 'ofj-models-to-ofp-models'
[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.DeviceState;
54 import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
55 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
56 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
57 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
58 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleService;
59 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
60 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
61 import org.opendaylight.openflowplugin.impl.device.initialization.DeviceInitializerProviderFactory;
62 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.CapabilitiesV10;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.features.reply.PhyPortBuilder;
72 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
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     @Mock
113     private KeyedInstanceIdentifier<Node, NodeKey> key;
114     @Before
115     public void setUp() throws Exception {
116         when(mockConnectionContext.getNodeId()).thenReturn(DUMMY_NODE_ID);
117         when(mockConnectionContext.getFeatures()).thenReturn(mockFeatures);
118         when(mockConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
119         when(mockConnectionContext.getDeviceInfo()).thenReturn(deviceInfo);
120         when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockConnectionContext);
121         when(deviceInfo.getNodeId()).thenReturn(DUMMY_NODE_ID);
122
123         final Capabilities capabilitiesV13 = mock(Capabilities.class);
124         final CapabilitiesV10 capabilitiesV10 = mock(CapabilitiesV10.class);
125         when(mockFeatures.getCapabilities()).thenReturn(capabilitiesV13);
126         when(mockFeatures.getCapabilitiesV10()).thenReturn(capabilitiesV10);
127         when(mockFeatures.getDatapathId()).thenReturn(BigInteger.valueOf(21L));
128     }
129
130     @Test
131     public void onDeviceContextLevelUpSuccessTest() throws Exception {
132         onDeviceContextLevelUp(false);
133     }
134
135     private DeviceManagerImpl prepareDeviceManager() {
136         final DataBroker mockedDataBroker = mock(DataBroker.class);
137         final WriteTransaction mockedWriteTransaction = mock(WriteTransaction.class);
138
139         final BindingTransactionChain mockedTxChain = mock(BindingTransactionChain.class);
140         final WriteTransaction mockedWTx = mock(WriteTransaction.class);
141         when(mockedTxChain.newWriteOnlyTransaction()).thenReturn(mockedWTx);
142         when(mockedDataBroker.createTransactionChain(any(TransactionChainListener.class))).thenReturn
143                 (mockedTxChain);
144         when(mockedDataBroker.newWriteOnlyTransaction()).thenReturn(mockedWriteTransaction);
145
146         when(mockedWriteTransaction.submit()).thenReturn(mockedFuture);
147
148         final DeviceManagerImpl deviceManager = new DeviceManagerImpl(
149             mockedDataBroker,
150             TEST_VALUE_GLOBAL_NOTIFICATION_QUOTA,
151             false,
152             barrierIntervalNanos,
153             barrierCountLimit,
154             messageIntelligenceAgency,
155             true,
156             clusterSingletonServiceProvider,
157             null,
158             new HashedWheelTimer(),
159             convertorExecutor,
160             false,
161             false,
162             DeviceInitializerProviderFactory.createDefaultProvider());
163
164         deviceManager.setDeviceInitializationPhaseHandler(deviceInitPhaseHandler);
165         deviceManager.setDeviceTerminationPhaseHandler(deviceTerminationPhaseHandler);
166
167         return deviceManager;
168     }
169
170     public void onDeviceContextLevelUp(final boolean withException) throws Exception {
171         final DeviceManagerImpl deviceManager = prepareDeviceManager();
172         final DeviceState mockedDeviceState = mock(DeviceState.class);
173         when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
174
175         if (withException) {
176             doThrow(new IllegalStateException("dummy")).when(mockedDeviceContext).initialSubmitTransaction();
177         }
178         deviceManager.addDeviceContextToMap(deviceInfo, mockedDeviceContext);
179         deviceManager.onDeviceContextLevelUp(deviceInfo, lifecycleService);
180         if (withException) {
181             verify(mockedDeviceContext).close();
182         } else {
183             verify(mockedDeviceContext).onPublished();
184         }
185     }
186
187     @Test
188     public void deviceConnectedTest() throws Exception{
189         final DeviceManagerImpl deviceManager = prepareDeviceManager();
190         injectMockTranslatorLibrary(deviceManager);
191         final ConnectionContext mockConnectionContext = buildMockConnectionContext(OFConstants.OFP_VERSION_1_3);
192
193         deviceManager.deviceConnected(mockConnectionContext);
194
195         final InOrder order = inOrder(mockConnectionContext);
196         order.verify(mockConnectionContext).setOutboundQueueProvider(any(OutboundQueueProvider.class));
197         order.verify(mockConnectionContext).setOutboundQueueHandleRegistration(
198                 Mockito.<OutboundQueueHandlerRegistration<OutboundQueueProvider>>any());
199         verify(deviceInitPhaseHandler).onDeviceContextLevelUp(Matchers.<DeviceInfo>any(), Mockito.<LifecycleService>any());
200     }
201
202     @Test
203     public void deviceConnectedV10Test() throws Exception{
204         final DeviceManagerImpl deviceManager = prepareDeviceManager();
205         injectMockTranslatorLibrary(deviceManager);
206         final ConnectionContext mockConnectionContext = buildMockConnectionContext(OFConstants.OFP_VERSION_1_0);
207
208         final PhyPortBuilder phyPort = new PhyPortBuilder()
209                 .setPortNo(41L);
210         when(mockFeatures.getPhyPort()).thenReturn(Collections.singletonList(phyPort.build()));
211         final MessageTranslator<Object, Object> mockedTranslator = mock(MessageTranslator.class);
212         when(mockedTranslator.translate(Matchers.<Object>any(), Matchers.<DeviceInfo>any(), Matchers.any()))
213                 .thenReturn(null);
214         when(translatorLibrary.lookupTranslator(Matchers.<TranslatorKey>any())).thenReturn(mockedTranslator);
215
216         deviceManager.deviceConnected(mockConnectionContext);
217
218         final InOrder order = inOrder(mockConnectionContext);
219         order.verify(mockConnectionContext).setOutboundQueueProvider(any(OutboundQueueProvider.class));
220         order.verify(mockConnectionContext).setOutboundQueueHandleRegistration(
221                 Mockito.<OutboundQueueHandlerRegistration<OutboundQueueProvider>>any());
222         verify(deviceInitPhaseHandler).onDeviceContextLevelUp(Matchers.<DeviceInfo>any(), Mockito.<LifecycleService>any());
223     }
224
225     @Test
226     public void deviceDisconnectedTest() throws Exception {
227         final DeviceState deviceState = mock(DeviceState.class);
228
229         final DeviceManagerImpl deviceManager = prepareDeviceManager();
230         injectMockTranslatorLibrary(deviceManager);
231
232         final ConnectionContext connectionContext = buildMockConnectionContext(OFConstants.OFP_VERSION_1_3);
233         when(connectionContext.getNodeId()).thenReturn(mockedNodeId);
234
235         final DeviceContext deviceContext = mock(DeviceContext.class);
236         when(deviceContext.shuttingDownDataStoreTransactions()).thenReturn(Futures.immediateCheckedFuture(null));
237         when(deviceContext.getPrimaryConnectionContext()).thenReturn(connectionContext);
238         when(deviceContext.getDeviceState()).thenReturn(deviceState);
239         when(deviceContext.getState()).thenReturn(OFPContext.CONTEXT_STATE.WORKING);
240
241         final ConcurrentHashMap<DeviceInfo, DeviceContext> deviceContexts = getContextsCollection(deviceManager);
242         deviceContexts.put(deviceInfo, deviceContext);
243
244         deviceManager.onDeviceDisconnected(connectionContext);
245     }
246
247     protected ConnectionContext buildMockConnectionContext(final short ofpVersion) {
248         when(mockFeatures.getVersion()).thenReturn(ofpVersion);
249         when(outboundQueueProvider.reserveEntry()).thenReturn(43L);
250         Mockito.doAnswer(new Answer<Void>() {
251             @Override
252             public Void answer(final InvocationOnMock invocation) throws Throwable {
253                 final FutureCallback<OfHeader> callBack = (FutureCallback<OfHeader>) invocation.getArguments()[2];
254                 callBack.onSuccess(null);
255                 return null;
256             }
257         })
258                 .when(outboundQueueProvider)
259                 .commitEntry(Matchers.anyLong(), Matchers.<MultipartRequestInput>any(), Matchers.<FutureCallback<OfHeader>>any());
260
261         when(mockedConnectionAdapter.registerOutboundQueueHandler(Matchers.<OutboundQueueHandler>any(), Matchers.anyInt(), Matchers.anyLong()))
262                 .thenAnswer(new Answer<OutboundQueueHandlerRegistration<OutboundQueueHandler>>() {
263                     @Override
264                     public OutboundQueueHandlerRegistration<OutboundQueueHandler> answer(final InvocationOnMock invocation) throws Throwable {
265                         final OutboundQueueHandler handler = (OutboundQueueHandler) invocation.getArguments()[0];
266                         handler.onConnectionQueueChanged(outboundQueueProvider);
267                         return null;
268                     }
269                 });
270
271         when(mockConnectionContext.getOutboundQueueProvider()).thenReturn(outboundQueueProvider);
272         return mockConnectionContext;
273     }
274
275     private void injectMockTranslatorLibrary(final DeviceManagerImpl deviceManager) {
276         deviceManager.setTranslatorLibrary(translatorLibrary);
277     }
278
279     @Test
280     public void testClose() throws Exception {
281         final DeviceContext deviceContext = mock(DeviceContext.class);
282         final DeviceManagerImpl deviceManager = prepareDeviceManager();
283         final ConcurrentHashMap<DeviceInfo, DeviceContext> deviceContexts = getContextsCollection(deviceManager);
284         deviceContexts.put(deviceInfo, deviceContext);
285         Assert.assertEquals(1, deviceContexts.size());
286
287         deviceManager.close();
288
289         verify(deviceContext).shutdownConnection();
290         verify(deviceContext, Mockito.never()).close();
291     }
292
293     private static ConcurrentHashMap<DeviceInfo, DeviceContext> getContextsCollection(final DeviceManagerImpl deviceManager) throws NoSuchFieldException, IllegalAccessException {
294         // HACK: contexts collection for testing shall be accessed in some more civilized way
295         final Field contextsField = DeviceManagerImpl.class.getDeclaredField("deviceContexts");
296         Assert.assertNotNull(contextsField);
297         contextsField.setAccessible(true);
298         return (ConcurrentHashMap<DeviceInfo, DeviceContext>) contextsField.get(deviceManager);
299     }
300
301 }