e4bd7780667d37437f2ac3998ffd520e9f4cec56
[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.Ignore;
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.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.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.impl.device.initialization.DeviceInitializerProviderFactory;
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 ConvertorExecutor convertorExecutor;
113     @Mock
114     private KeyedInstanceIdentifier<Node, NodeKey> key;
115     @Before
116     public void setUp() throws Exception {
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             false,
162             false,
163             DeviceInitializerProviderFactory.createDefaultProvider());
164
165         deviceManager.setDeviceInitializationPhaseHandler(deviceInitPhaseHandler);
166         deviceManager.setDeviceTerminationPhaseHandler(deviceTerminationPhaseHandler);
167
168         return deviceManager;
169     }
170
171     public void onDeviceContextLevelUp(final boolean withException) throws Exception {
172         final DeviceManagerImpl deviceManager = prepareDeviceManager();
173         final DeviceState mockedDeviceState = mock(DeviceState.class);
174         when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
175
176         if (withException) {
177             doThrow(new IllegalStateException("dummy")).when(mockedDeviceContext).initialSubmitTransaction();
178         }
179         deviceManager.addDeviceContextToMap(deviceInfo, mockedDeviceContext);
180         deviceManager.onDeviceContextLevelUp(deviceInfo, lifecycleService);
181         if (withException) {
182             verify(mockedDeviceContext).close();
183         } else {
184             verify(mockedDeviceContext).onPublished();
185         }
186     }
187
188     @Test
189     public void deviceDisconnectedTest() throws Exception {
190         final DeviceState deviceState = mock(DeviceState.class);
191
192         final DeviceManagerImpl deviceManager = prepareDeviceManager();
193         injectMockTranslatorLibrary(deviceManager);
194
195         final ConnectionContext connectionContext = buildMockConnectionContext(OFConstants.OFP_VERSION_1_3);
196         when(connectionContext.getNodeId()).thenReturn(mockedNodeId);
197
198         final DeviceContext deviceContext = mock(DeviceContext.class);
199         when(deviceContext.shuttingDownDataStoreTransactions()).thenReturn(Futures.immediateCheckedFuture(null));
200         when(deviceContext.getPrimaryConnectionContext()).thenReturn(connectionContext);
201         when(deviceContext.getDeviceState()).thenReturn(deviceState);
202         when(deviceContext.getState()).thenReturn(OFPContext.CONTEXT_STATE.WORKING);
203
204         final ConcurrentHashMap<DeviceInfo, DeviceContext> deviceContexts = getContextsCollection(deviceManager);
205         deviceContexts.put(deviceInfo, deviceContext);
206
207         deviceManager.onDeviceDisconnected(connectionContext);
208     }
209
210     protected ConnectionContext buildMockConnectionContext(final short ofpVersion) {
211         when(mockFeatures.getVersion()).thenReturn(ofpVersion);
212         when(outboundQueueProvider.reserveEntry()).thenReturn(43L);
213         Mockito.doAnswer(new Answer<Void>() {
214             @Override
215             public Void answer(final InvocationOnMock invocation) throws Throwable {
216                 final FutureCallback<OfHeader> callBack = (FutureCallback<OfHeader>) invocation.getArguments()[2];
217                 callBack.onSuccess(null);
218                 return null;
219             }
220         })
221                 .when(outboundQueueProvider)
222                 .commitEntry(Matchers.anyLong(), Matchers.<MultipartRequestInput>any(), Matchers.<FutureCallback<OfHeader>>any());
223
224         when(mockedConnectionAdapter.registerOutboundQueueHandler(Matchers.<OutboundQueueHandler>any(), Matchers.anyInt(), Matchers.anyLong()))
225                 .thenAnswer(new Answer<OutboundQueueHandlerRegistration<OutboundQueueHandler>>() {
226                     @Override
227                     public OutboundQueueHandlerRegistration<OutboundQueueHandler> answer(final InvocationOnMock invocation) throws Throwable {
228                         final OutboundQueueHandler handler = (OutboundQueueHandler) invocation.getArguments()[0];
229                         handler.onConnectionQueueChanged(outboundQueueProvider);
230                         return null;
231                     }
232                 });
233
234         when(mockConnectionContext.getOutboundQueueProvider()).thenReturn(outboundQueueProvider);
235         return mockConnectionContext;
236     }
237
238     private void injectMockTranslatorLibrary(final DeviceManagerImpl deviceManager) {
239         deviceManager.setTranslatorLibrary(translatorLibrary);
240     }
241
242     @Test
243     public void testClose() throws Exception {
244         final DeviceContext deviceContext = mock(DeviceContext.class);
245         final DeviceManagerImpl deviceManager = prepareDeviceManager();
246         final ConcurrentHashMap<DeviceInfo, DeviceContext> deviceContexts = getContextsCollection(deviceManager);
247         deviceContexts.put(deviceInfo, deviceContext);
248         Assert.assertEquals(1, deviceContexts.size());
249
250         deviceManager.close();
251
252         verify(deviceContext).shutdownConnection();
253         verify(deviceContext, Mockito.never()).close();
254     }
255
256     private static ConcurrentHashMap<DeviceInfo, DeviceContext> getContextsCollection(final DeviceManagerImpl deviceManager) throws NoSuchFieldException, IllegalAccessException {
257         // HACK: contexts collection for testing shall be accessed in some more civilized way
258         final Field contextsField = DeviceManagerImpl.class.getDeclaredField("deviceContexts");
259         Assert.assertNotNull(contextsField);
260         contextsField.setAccessible(true);
261         return (ConcurrentHashMap<DeviceInfo, DeviceContext>) contextsField.get(deviceManager);
262     }
263
264 }