Merge "Post "Clustering optimization" updates"
[openflowplugin.git] / openflowplugin-impl / src / test / java / org / opendaylight / openflowplugin / impl / device / DeviceManagerImplTest.java
1 /*
2  *
3  *  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
4  *  *
5  *  * This program and the accompanying materials are made available under the
6  *  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  *  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  *
9  *
10  */
11
12 package org.opendaylight.openflowplugin.impl.device;
13
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Mockito.doThrow;
16 import static org.mockito.Mockito.inOrder;
17 import static org.mockito.Mockito.mock;
18 import static org.mockito.Mockito.verify;
19 import static org.mockito.Mockito.when;
20 import com.google.common.util.concurrent.CheckedFuture;
21 import com.google.common.util.concurrent.FutureCallback;
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.openflowjava.protocol.api.connection.ConnectionAdapter;
43 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
44 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandler;
45 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
46 import org.opendaylight.openflowplugin.api.OFConstants;
47 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
48 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
49 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
50 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
51 import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
52 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
53 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
54 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
55 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
56 import org.opendaylight.openflowplugin.openflow.md.util.OpenflowPortsUtil;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.CapabilitiesV10;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.features.reply.PhyPortBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
68 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
69 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
70
71 @RunWith(MockitoJUnitRunner.class)
72 public class DeviceManagerImplTest {
73
74     private static final boolean TEST_VALUE_SWITCH_FEATURE_MANDATORY = true;
75     private static final long TEST_VALUE_GLOBAL_NOTIFICATION_QUOTA = 2000l;
76     private static final KeyedInstanceIdentifier<Node, NodeKey> DUMMY_NODE_II = InstanceIdentifier.create(Nodes.class)
77             .child(Node.class, new NodeKey(new NodeId("dummyNodeId")));
78     private static final Short DUMMY_TABLE_ID = 1;
79     private static final Long DUMMY_MAX_METER = 544L;
80     private static final String DUMMY_DATAPATH_ID = "44";
81     private static final Long DUMMY_PORT_NUMBER = 21L;
82     private static final int barrierCountLimit = 25600;
83     private static final int barrierIntervalNanos = 500;
84
85     @Mock
86     CheckedFuture<Void, TransactionCommitFailedException> mockedFuture;
87     @Mock
88     private FeaturesReply mockFeatures;
89     @Mock
90     private OutboundQueue outboundQueueProvider;
91     @Mock
92     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
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
104     @Before
105     public void setUp() throws Exception {
106         OpenflowPortsUtil.init();
107
108         when(mockConnectionContext.getNodeId()).thenReturn(new NodeId("dummyNodeId"));
109         when(mockConnectionContext.getFeatures()).thenReturn(mockFeatures);
110         when(mockConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
111         when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockConnectionContext);
112
113         final Capabilities capabilitiesV13 = Mockito.mock(Capabilities.class);
114         final CapabilitiesV10 capabilitiesV10 = Mockito.mock(CapabilitiesV10.class);
115         when(mockFeatures.getCapabilities()).thenReturn(capabilitiesV13);
116         when(mockFeatures.getCapabilitiesV10()).thenReturn(capabilitiesV10);
117         when(mockFeatures.getDatapathId()).thenReturn(BigInteger.valueOf(21L));
118     }
119
120     @Test(expected = IllegalStateException.class)
121     public void onDeviceContextLevelUpFailTest() throws Exception {
122         onDeviceContextLevelUp(true);
123     }
124
125     @Test
126     public void onDeviceContextLevelUpSuccessTest() throws Exception {
127         onDeviceContextLevelUp(false);
128     }
129
130     private DeviceManagerImpl prepareDeviceManager() {
131         return prepareDeviceManager(false);
132     }
133
134     private DeviceManagerImpl prepareDeviceManager(final boolean withException) {
135         final DataBroker mockedDataBroker = mock(DataBroker.class);
136         final WriteTransaction mockedWriteTransaction = mock(WriteTransaction.class);
137
138         final BindingTransactionChain mockedTxChain = mock(BindingTransactionChain.class);
139         final WriteTransaction mockedWTx = mock(WriteTransaction.class);
140         when(mockedTxChain.newWriteOnlyTransaction()).thenReturn(mockedWTx);
141         when(mockedDataBroker.createTransactionChain(any(TransactionChainListener.class))).thenReturn
142                 (mockedTxChain);
143         when(mockedDataBroker.newWriteOnlyTransaction()).thenReturn(mockedWriteTransaction);
144
145         when(mockedWriteTransaction.submit()).thenReturn(mockedFuture);
146
147         final MessageIntelligenceAgency mockedMessageIntelligenceAgency = mock(MessageIntelligenceAgency.class);
148         final DeviceManagerImpl deviceManager = new DeviceManagerImpl(mockedDataBroker, mockedMessageIntelligenceAgency,
149                 TEST_VALUE_GLOBAL_NOTIFICATION_QUOTA, false, barrierIntervalNanos, barrierCountLimit);
150
151         deviceManager.setDeviceInitializationPhaseHandler(deviceInitPhaseHandler);
152
153         return deviceManager;
154     }
155
156     public void onDeviceContextLevelUp(final boolean withException) throws Exception {
157         final DeviceManagerImpl deviceManager = prepareDeviceManager(withException);
158         final DeviceState mockedDeviceState = mock(DeviceState.class);
159         when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
160         when(mockedDeviceState.getRole()).thenReturn(OfpRole.BECOMEMASTER);
161
162         if (withException) {
163             doThrow(new IllegalStateException("dummy")).when(mockedDeviceContext).initialSubmitTransaction();
164         }
165
166         deviceManager.onDeviceContextLevelUp(mockedDeviceContext);
167         if (withException) {
168             verify(mockedDeviceContext).close();
169         } else {
170             verify(mockedDeviceContext).initialSubmitTransaction();
171             verify(mockedDeviceContext).onPublished();
172         }
173     }
174
175     @Test
176     public void deviceConnectedTest() throws Exception{
177         final DeviceManagerImpl deviceManager = prepareDeviceManager();
178         injectMockTranslatorLibrary(deviceManager);
179         final ConnectionContext mockConnectionContext = buildMockConnectionContext(OFConstants.OFP_VERSION_1_3);
180
181         deviceManager.deviceConnected(mockConnectionContext);
182
183         final InOrder order = inOrder(mockConnectionContext);
184         order.verify(mockConnectionContext).getFeatures();
185         order.verify(mockConnectionContext).setOutboundQueueProvider(any(OutboundQueueProvider.class));
186         order.verify(mockConnectionContext).setOutboundQueueHandleRegistration(
187                 Mockito.<OutboundQueueHandlerRegistration<OutboundQueueProvider>>any());
188         order.verify(mockConnectionContext).getNodeId();
189         Mockito.verify(deviceInitPhaseHandler).onDeviceContextLevelUp(Matchers.<DeviceContext>any());
190     }
191
192     @Test
193     public void deviceConnectedV10Test() throws Exception{
194         final DeviceManagerImpl deviceManager = prepareDeviceManager();
195         injectMockTranslatorLibrary(deviceManager);
196         final ConnectionContext mockConnectionContext = buildMockConnectionContext(OFConstants.OFP_VERSION_1_0);
197
198         final PhyPortBuilder phyPort = new PhyPortBuilder()
199                 .setPortNo(41L);
200         when(mockFeatures.getPhyPort()).thenReturn(Collections.singletonList(phyPort.build()));
201         final MessageTranslator<Object, Object> mockedTranslator = Mockito.mock(MessageTranslator.class);
202         when(mockedTranslator.translate(Matchers.<Object>any(), Matchers.<DeviceContext>any(), Matchers.any()))
203                 .thenReturn(null);
204         when(translatorLibrary.lookupTranslator(Matchers.<TranslatorKey>any())).thenReturn(mockedTranslator);
205
206         deviceManager.deviceConnected(mockConnectionContext);
207
208         final InOrder order = inOrder(mockConnectionContext);
209         order.verify(mockConnectionContext).getFeatures();
210         order.verify(mockConnectionContext).setOutboundQueueProvider(any(OutboundQueueProvider.class));
211         order.verify(mockConnectionContext).setOutboundQueueHandleRegistration(
212                 Mockito.<OutboundQueueHandlerRegistration<OutboundQueueProvider>>any());
213         order.verify(mockConnectionContext).getNodeId();
214         Mockito.verify(deviceInitPhaseHandler).onDeviceContextLevelUp(Matchers.<DeviceContext>any());
215     }
216
217     protected ConnectionContext buildMockConnectionContext(final short ofpVersion) {
218         when(mockFeatures.getVersion()).thenReturn(ofpVersion);
219         when(outboundQueueProvider.reserveEntry()).thenReturn(43L);
220         Mockito.doAnswer(new Answer<Void>() {
221             @Override
222             public Void answer(final InvocationOnMock invocation) throws Throwable {
223                 final FutureCallback<OfHeader> callBack = (FutureCallback<OfHeader>) invocation.getArguments()[2];
224                 callBack.onSuccess(null);
225                 return null;
226             }
227         })
228                 .when(outboundQueueProvider)
229                 .commitEntry(Matchers.anyLong(), Matchers.<MultipartRequestInput>any(), Matchers.<FutureCallback<OfHeader>>any());
230
231         when(mockedConnectionAdapter.registerOutboundQueueHandler(Matchers.<OutboundQueueHandler>any(), Matchers.anyInt(), Matchers.anyLong()))
232                 .thenAnswer(new Answer<OutboundQueueHandlerRegistration<OutboundQueueHandler>>() {
233                     @Override
234                     public OutboundQueueHandlerRegistration<OutboundQueueHandler> answer(final InvocationOnMock invocation) throws Throwable {
235                         final OutboundQueueHandler handler = (OutboundQueueHandler) invocation.getArguments()[0];
236                         handler.onConnectionQueueChanged(outboundQueueProvider);
237                         return null;
238                     }
239                 });
240
241         when(mockConnectionContext.getOutboundQueueProvider()).thenReturn(outboundQueueProvider);
242         return mockConnectionContext;
243     }
244
245     private void injectMockTranslatorLibrary(final DeviceManagerImpl deviceManager) {
246         deviceManager.setTranslatorLibrary(translatorLibrary);
247     }
248
249     @Test
250     public void testClose() throws Exception {
251         final DeviceContext deviceContext = Mockito.mock(DeviceContext.class);
252         final DeviceManagerImpl deviceManager = prepareDeviceManager();
253         final ConcurrentHashMap<NodeId, DeviceContext> deviceContexts = getContextsCollection(deviceManager);
254         deviceContexts.put(mockedNodeId, deviceContext);
255         Assert.assertEquals(1, deviceContexts.size());
256
257         deviceManager.close();
258
259         Mockito.verify(deviceContext).close();
260     }
261
262     private static ConcurrentHashMap<NodeId, DeviceContext> getContextsCollection(final DeviceManagerImpl deviceManager) throws NoSuchFieldException, IllegalAccessException {
263         // HACK: contexts collection for testing shall be accessed in some more civilized way
264         final Field contextsField = DeviceManagerImpl.class.getDeclaredField("deviceContexts");
265         Assert.assertNotNull(contextsField);
266         contextsField.setAccessible(true);
267         return (ConcurrentHashMap<NodeId, DeviceContext>) contextsField.get(deviceManager);
268     }
269
270 }