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