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