Bump upstreams
[openflowplugin.git] / openflowjava / openflow-protocol-it / src / test / java / org / opendaylight / openflowjava / protocol / it / integration / IntegrationTest.java
1 /*
2  * Copyright (c) 2013 Pantheon Technologies s.r.o. 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 package org.opendaylight.openflowjava.protocol.it.integration;
9
10 import static org.mockito.ArgumentMatchers.any;
11 import static org.mockito.Mockito.doAnswer;
12 import static org.mockito.Mockito.doReturn;
13 import static org.mockito.Mockito.mock;
14
15 import java.net.InetAddress;
16 import java.util.ArrayList;
17 import java.util.Deque;
18 import java.util.List;
19 import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.ExecutorService;
21 import java.util.concurrent.TimeUnit;
22 import java.util.concurrent.TimeoutException;
23 import org.junit.After;
24 import org.junit.Test;
25 import org.junit.runner.RunWith;
26 import org.mockito.ArgumentMatchers;
27 import org.mockito.Mock;
28 import org.mockito.junit.MockitoJUnitRunner;
29 import org.opendaylight.infrautils.diagstatus.DiagStatusService;
30 import org.opendaylight.infrautils.diagstatus.ServiceRegistration;
31 import org.opendaylight.openflowjava.protocol.api.connection.TlsConfiguration;
32 import org.opendaylight.openflowjava.protocol.api.connection.TlsConfigurationImpl;
33 import org.opendaylight.openflowjava.protocol.impl.clients.ClientEvent;
34 import org.opendaylight.openflowjava.protocol.impl.clients.ListeningSimpleClient;
35 import org.opendaylight.openflowjava.protocol.impl.clients.OFClient;
36 import org.opendaylight.openflowjava.protocol.impl.clients.ScenarioFactory;
37 import org.opendaylight.openflowjava.protocol.impl.clients.ScenarioHandler;
38 import org.opendaylight.openflowjava.protocol.impl.clients.SendEvent;
39 import org.opendaylight.openflowjava.protocol.impl.clients.SimpleClient;
40 import org.opendaylight.openflowjava.protocol.impl.clients.SleepEvent;
41 import org.opendaylight.openflowjava.protocol.impl.clients.UdpSimpleClient;
42 import org.opendaylight.openflowjava.protocol.impl.clients.WaitForMessageEvent;
43 import org.opendaylight.openflowjava.protocol.impl.core.SwitchConnectionProviderImpl;
44 import org.opendaylight.openflowjava.protocol.impl.core.TcpHandler;
45 import org.opendaylight.openflowjava.protocol.impl.core.UdpHandler;
46 import org.opendaylight.openflowjava.protocol.impl.core.connection.ConnectionConfigurationImpl;
47 import org.opendaylight.openflowjava.util.ByteBufUtils;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.KeystoreType;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.PathType;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.TransportProtocol;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 /**
55  * End-to-end integration test.
56  *
57  * @author michal.polkorab
58  * @author timotej.kubas
59  */
60 @RunWith(MockitoJUnitRunner.class)
61 public class IntegrationTest {
62
63     private static final Logger LOGGER = LoggerFactory
64             .getLogger(IntegrationTest.class);
65
66     private static int port;
67     private TlsConfiguration tlsConfiguration;
68     private static final int CHANNEL_OUTBOUND_QUEUE_SIZE = 1024;
69     private static final int SWITCH_IDLE_TIMEOUT = 2000;
70     private static final long CONNECTION_TIMEOUT = 2000;
71     private InetAddress startupAddress;
72     private MockPlugin mockPlugin;
73     private SwitchConnectionProviderImpl switchConnectionProvider;
74     private ConnectionConfigurationImpl connConfig;
75     @Mock
76     private ExecutorService executorService;
77
78     private Thread thread;
79
80     private enum ClientType {
81         SIMPLE,
82         LISTENING
83     }
84
85     public void setUp(final TransportProtocol protocol) throws Exception {
86         LOGGER.debug("\n starting test -------------------------------");
87         doAnswer(invocation -> {
88             invocation.getArgument(0, Runnable.class).run();
89             return null;
90         }).when(executorService).execute(ArgumentMatchers.any());
91
92         final String currentDir = System.getProperty("user.dir");
93         LOGGER.debug("Current dir using System: {}", currentDir);
94         startupAddress = InetAddress.getLocalHost();
95         tlsConfiguration = null;
96         if (protocol.equals(TransportProtocol.TLS)) {
97             tlsConfiguration = new TlsConfigurationImpl(KeystoreType.JKS,
98                     "/selfSignedSwitch", PathType.CLASSPATH, KeystoreType.JKS,
99                     "/selfSignedController", PathType.CLASSPATH,
100                     List.of());
101         }
102         connConfig = new ConnectionConfigurationImpl(startupAddress, 0, tlsConfiguration,
103                 SWITCH_IDLE_TIMEOUT, true, false, CHANNEL_OUTBOUND_QUEUE_SIZE);
104         connConfig.setTransferProtocol(protocol);
105         mockPlugin = new MockPlugin(executorService);
106
107         final var diagStatusService = mock(DiagStatusService.class);
108         doReturn(mock(ServiceRegistration.class)).when(diagStatusService).register(any());
109
110         switchConnectionProvider = new SwitchConnectionProviderImpl(diagStatusService, connConfig);
111         switchConnectionProvider.setSwitchConnectionHandler(mockPlugin);
112         switchConnectionProvider.startup().get(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
113         if (protocol.equals(TransportProtocol.TCP) || protocol.equals(TransportProtocol.TLS)) {
114             final TcpHandler tcpHandler = (TcpHandler) switchConnectionProvider.getServerFacade();
115             port = tcpHandler.getPort();
116         } else {
117             final UdpHandler udpHandler = (UdpHandler) switchConnectionProvider.getServerFacade();
118             port = udpHandler.getPort();
119         }
120     }
121
122     @After
123     public void tearDown() {
124         switchConnectionProvider.close();
125         LOGGER.debug("\n ending test -------------------------------");
126     }
127
128     /**
129      * Library integration and communication test with handshake.
130      */
131     @Test
132     public void testHandshake() throws Exception {
133         setUp(TransportProtocol.TCP);
134         final int amountOfCLients = 1;
135         final Deque<ClientEvent> scenario = ScenarioFactory.createHandshakeScenario();
136         final ScenarioHandler handler = new ScenarioHandler(scenario);
137         final List<OFClient> clients = createAndStartClient(amountOfCLients, handler,
138                 TransportProtocol.TCP, ClientType.SIMPLE);
139         final OFClient firstClient = clients.get(0);
140         firstClient.getScenarioDone().get();
141         Thread.sleep(1000);
142
143         LOGGER.debug("testHandshake() Finished") ;
144     }
145
146     /**
147      * Library integration and secured communication test with handshake.
148      */
149     @Test
150     public void testTlsHandshake() throws Exception {
151         setUp(TransportProtocol.TLS);
152         final int amountOfCLients = 1;
153         final Deque<ClientEvent> scenario = ScenarioFactory.createHandshakeScenario();
154         final ScenarioHandler handler = new ScenarioHandler(scenario);
155         final List<OFClient> clients = createAndStartClient(amountOfCLients, handler,
156                 TransportProtocol.TLS, ClientType.SIMPLE);
157         final OFClient firstClient = clients.get(0);
158         firstClient.getScenarioDone().get();
159         Thread.sleep(1000);
160
161         LOGGER.debug("testTlsHandshake() Finished") ;
162     }
163
164     /**
165      * Library integration and communication test with handshake + echo exchange.
166      */
167     @Test
168     public void testHandshakeAndEcho() throws Exception {
169         setUp(TransportProtocol.TCP);
170         final int amountOfCLients = 1;
171         final Deque<ClientEvent> scenario = ScenarioFactory.createHandshakeScenario();
172         scenario.addFirst(new SleepEvent(1000));
173         scenario.addFirst(new SendEvent(ByteBufUtils.hexStringToBytes("04 02 00 08 00 00 00 04")));
174         scenario.addFirst(new SleepEvent(1000));
175         scenario.addFirst(new WaitForMessageEvent(ByteBufUtils.hexStringToBytes("04 03 00 08 00 00 00 04")));
176         final ScenarioHandler handler = new ScenarioHandler(scenario);
177         final List<OFClient> clients = createAndStartClient(amountOfCLients, handler,
178                 TransportProtocol.TCP, ClientType.SIMPLE);
179         final OFClient firstClient = clients.get(0);
180         firstClient.getScenarioDone().get();
181
182         LOGGER.debug("testHandshakeAndEcho() Finished") ;
183     }
184
185     /**
186      * Library integration and secured communication test with handshake + echo exchange.
187      */
188     @Test
189     public void testTlsHandshakeAndEcho() throws Exception {
190         setUp(TransportProtocol.TLS);
191         final int amountOfCLients = 1;
192         final Deque<ClientEvent> scenario = ScenarioFactory.createHandshakeScenario();
193         scenario.addFirst(new SleepEvent(1000));
194         scenario.addFirst(new SendEvent(ByteBufUtils.hexStringToBytes("04 02 00 08 00 00 00 04")));
195         scenario.addFirst(new SleepEvent(1000));
196         scenario.addFirst(new WaitForMessageEvent(ByteBufUtils.hexStringToBytes("04 03 00 08 00 00 00 04")));
197         final ScenarioHandler handler = new ScenarioHandler(scenario);
198         final List<OFClient> clients = createAndStartClient(amountOfCLients, handler,
199                 TransportProtocol.TLS, ClientType.SIMPLE);
200         final OFClient firstClient = clients.get(0);
201         firstClient.getScenarioDone().get();
202
203         LOGGER.debug("testTlsHandshakeAndEcho() Finished") ;
204     }
205
206     /**
207      * Library udp integration and communication test with handshake + echo exchange.
208      */
209     @Test
210     public void testUdpHandshakeAndEcho() throws Exception {
211         setUp(TransportProtocol.UDP);
212         final int amountOfCLients = 1;
213         final Deque<ClientEvent> scenario = ScenarioFactory.createHandshakeScenario();
214         scenario.addFirst(new SleepEvent(1000));
215         scenario.addFirst(new SendEvent(ByteBufUtils.hexStringToBytes("04 02 00 08 00 00 00 04")));
216         scenario.addFirst(new SleepEvent(1000));
217         scenario.addFirst(new WaitForMessageEvent(ByteBufUtils.hexStringToBytes("04 03 00 08 00 00 00 04")));
218         final ScenarioHandler handler = new ScenarioHandler(scenario);
219         final List<OFClient> clients = createAndStartClient(amountOfCLients, handler,
220                 TransportProtocol.UDP, ClientType.SIMPLE);
221         final OFClient firstClient = clients.get(0);
222         firstClient.getScenarioDone().get();
223
224         LOGGER.debug("testUdpHandshakeAndEcho() Finished") ;
225     }
226
227     /**
228      * Library integration and communication test (with virtual machine).
229      */
230     //@Test
231     public void testCommunicationWithVM() throws Exception {
232         mockPlugin.getFinishedFuture().get();
233     }
234
235     /**
236      * Creates and start a client.
237      *
238      * @param amountOfCLients number of clients
239      * @param protocol true if encrypted connection should be used
240      * @return new clients up and running
241      * @throws ExecutionException if some client could not start
242      */
243     private List<OFClient> createAndStartClient(final int amountOfCLients, final ScenarioHandler scenarioHandler,
244             final TransportProtocol protocol, final ClientType clientType)
245                     throws ExecutionException, InterruptedException, TimeoutException {
246         final List<OFClient> clientsHorde = new ArrayList<>();
247         for (int i = 0; i < amountOfCLients; i++) {
248             LOGGER.debug("startup address in createclient: {}", startupAddress.getHostAddress());
249             OFClient sc = null;
250             if (clientType == ClientType.SIMPLE) {
251                 if (protocol.equals(TransportProtocol.TCP)) {
252                     sc = new SimpleClient(startupAddress.getHostAddress(), port);
253                     sc.setSecuredClient(false);
254                 } else if (protocol.equals(TransportProtocol.TLS)) {
255                     sc = new SimpleClient(startupAddress.getHostAddress(), port);
256                     sc.setSecuredClient(true);
257                 } else {
258                     sc = new UdpSimpleClient(startupAddress.getHostAddress(), port);
259                 }
260             } else if (clientType == ClientType.LISTENING) {
261                 sc = new ListeningSimpleClient(0);
262                 sc.setScenarioHandler(scenarioHandler);
263                 sc.setSecuredClient(false);
264             } else {
265                 LOGGER.error("Unknown type of client.");
266                 throw new IllegalStateException("Unknown type of client.");
267             }
268
269             sc.setScenarioHandler(scenarioHandler);
270             clientsHorde.add(sc);
271             //sc.run();
272             thread = new Thread(sc);
273             thread.start();
274         }
275         for (final OFClient sc : clientsHorde) {
276             sc.getIsOnlineFuture().get(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
277         }
278         return clientsHorde;
279     }
280
281     @Test
282     public void testInitiateConnection() throws Exception {
283         setUp(TransportProtocol.TCP);
284
285         final Deque<ClientEvent> scenario = ScenarioFactory.createHandshakeScenario();
286         final ScenarioHandler handler = new ScenarioHandler(scenario);
287         final List<OFClient> clients = createAndStartClient(1, handler, TransportProtocol.TCP, ClientType.LISTENING);
288         final OFClient ofClient = clients.get(0);
289         ofClient.getIsOnlineFuture().get(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
290         final int listeningClientPort = ((ListeningSimpleClient) ofClient).getPort();
291         mockPlugin.initiateConnection(switchConnectionProvider, "localhost", listeningClientPort);
292         ofClient.getScenarioDone().get();
293         LOGGER.debug("testInitiateConnection() Finished") ;
294     }
295 }