5e1056c964981b9bfd8d4b2eb6a0f0fccc508e70
[bgpcep.git] / pcep / impl / src / test / java / org / opendaylight / protocol / pcep / impl / PCEPDispatcherImplTest.java
1 /*
2  * Copyright (c) 2014 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.protocol.pcep.impl;
10
11 import static java.util.Objects.requireNonNull;
12 import static org.junit.Assert.assertEquals;
13 import static org.mockito.Matchers.any;
14 import static org.mockito.Mockito.doReturn;
15 import static org.opendaylight.protocol.util.CheckUtil.waitFutureSuccess;
16
17 import io.netty.bootstrap.Bootstrap;
18 import io.netty.channel.ChannelFuture;
19 import io.netty.channel.ChannelInitializer;
20 import io.netty.channel.ChannelOption;
21 import io.netty.channel.EventLoopGroup;
22 import io.netty.channel.epoll.Epoll;
23 import io.netty.channel.epoll.EpollEventLoopGroup;
24 import io.netty.channel.nio.NioEventLoopGroup;
25 import io.netty.channel.socket.SocketChannel;
26 import io.netty.channel.socket.nio.NioSocketChannel;
27 import io.netty.util.concurrent.EventExecutor;
28 import io.netty.util.concurrent.Future;
29 import io.netty.util.concurrent.GlobalEventExecutor;
30 import java.net.InetSocketAddress;
31 import java.nio.channels.Channel;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.concurrent.ExecutionException;
35 import org.junit.After;
36 import org.junit.Assert;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.mockito.Mock;
40 import org.mockito.Mockito;
41 import org.mockito.MockitoAnnotations;
42 import org.opendaylight.protocol.concepts.KeyMapping;
43 import org.opendaylight.protocol.pcep.PCEPCapability;
44 import org.opendaylight.protocol.pcep.PCEPDispatcherDependencies;
45 import org.opendaylight.protocol.pcep.PCEPSessionListenerFactory;
46 import org.opendaylight.protocol.pcep.PCEPSessionNegotiatorFactory;
47 import org.opendaylight.protocol.pcep.PCEPSessionProposalFactory;
48 import org.opendaylight.protocol.pcep.spi.MessageRegistry;
49 import org.opendaylight.protocol.pcep.spi.pojo.ServiceLoaderPCEPExtensionProviderContext;
50 import org.opendaylight.protocol.util.InetSocketAddressUtil;
51
52 public class PCEPDispatcherImplTest {
53     private static final short DEAD_TIMER = 120;
54     private static final short KEEP_ALIVE = 30;
55     private static final int RETRY_TIMER = 0;
56     private static final int CONNECT_TIMEOUT = 500;
57
58     private PCEPDispatcherImpl dispatcher;
59     private PCEPDispatcherImpl disp2Spy;
60
61     @Mock
62     private Channel mockChannel;
63     @Mock
64     private PCEPDispatcherDependencies dispatcherDependencies;
65     @Mock
66     private PCEPSessionListenerFactory listenerFactory;
67
68     private PCCMock pccMock;
69
70     @Before
71     public void setUp() {
72         MockitoAnnotations.initMocks(this);
73         final List<PCEPCapability> capList = new ArrayList<>();
74         final PCEPSessionProposalFactory sessionProposal = new BasePCEPSessionProposalFactory(DEAD_TIMER, KEEP_ALIVE,
75                 capList);
76         final EventLoopGroup eventLoopGroup;
77         if (Epoll.isAvailable()) {
78             eventLoopGroup = new EpollEventLoopGroup();
79         } else {
80             eventLoopGroup = new NioEventLoopGroup();
81         }
82         final MessageRegistry msgReg = ServiceLoaderPCEPExtensionProviderContext.getSingletonInstance()
83                 .getMessageHandlerRegistry();
84         this.dispatcher = new PCEPDispatcherImpl(msgReg,
85                 new DefaultPCEPSessionNegotiatorFactory(sessionProposal, 0),
86                 eventLoopGroup, eventLoopGroup);
87
88         doReturn(KeyMapping.getKeyMapping()).when(this.dispatcherDependencies).getKeys();
89         doReturn(null).when(this.dispatcherDependencies).getPeerProposal();
90
91         doReturn("mockChannel").when(this.mockChannel).toString();
92         final PCEPDispatcherImpl dispatcher2 = new PCEPDispatcherImpl(msgReg,
93                 new DefaultPCEPSessionNegotiatorFactory(sessionProposal, 0),
94                 eventLoopGroup, eventLoopGroup);
95         this.disp2Spy = Mockito.spy(dispatcher2);
96
97         this.pccMock = new PCCMock(new DefaultPCEPSessionNegotiatorFactory(sessionProposal, 0),
98                 new PCEPHandlerFactory(msgReg));
99     }
100
101     @Test
102     public void testCreateClientServer() throws InterruptedException, ExecutionException {
103         final int port = InetSocketAddressUtil.getRandomPort();
104         final InetSocketAddress serverAddr = new InetSocketAddress("0.0.0.0", port);
105         final InetSocketAddress clientAddr1 = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
106         final InetSocketAddress clientAddr2 = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
107
108         doReturn(serverAddr).when(this.dispatcherDependencies).getAddress();
109         doReturn(this.listenerFactory).when(this.dispatcherDependencies).getListenerFactory();
110         doReturn(new SimpleSessionListener()).when(this.listenerFactory).getSessionListener();
111         final ChannelFuture futureChannel = this.dispatcher.createServer(this.dispatcherDependencies);
112         waitFutureSuccess(futureChannel);
113         final PCEPSessionImpl session1 = this.pccMock.createClient(clientAddr1,
114                 RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
115
116         final PCEPSessionImpl session2 = this.pccMock.createClient(clientAddr2,
117                 RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
118
119         Assert.assertTrue(futureChannel.channel().isActive());
120         assertEquals(clientAddr1.getAddress().getHostAddress(), session1.getPeerPref().getIpAddress());
121         assertEquals(DEAD_TIMER, session1.getDeadTimerValue().shortValue());
122         assertEquals(KEEP_ALIVE, session1.getKeepAliveTimerValue().shortValue());
123
124         assertEquals(clientAddr2.getAddress().getHostAddress(), session2.getPeerPref().getIpAddress());
125         assertEquals(DEAD_TIMER, session2.getDeadTimerValue().shortValue());
126         assertEquals(KEEP_ALIVE, session2.getKeepAliveTimerValue().shortValue());
127
128         session1.close();
129         session2.close();
130         Assert.assertTrue(futureChannel.channel().isActive());
131     }
132
133     @Test
134     public void testCreateDuplicateClient() throws InterruptedException, ExecutionException {
135         final int port = InetSocketAddressUtil.getRandomPort();
136         final InetSocketAddress serverAddr = new InetSocketAddress("0.0.0.0", port);
137         final InetSocketAddress clientAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
138
139         doReturn(serverAddr).when(this.dispatcherDependencies).getAddress();
140         doReturn(this.listenerFactory).when(this.dispatcherDependencies).getListenerFactory();
141         doReturn(new SimpleSessionListener()).when(this.listenerFactory).getSessionListener();
142
143         waitFutureSuccess(this.dispatcher.createServer(this.dispatcherDependencies));
144         final Future<PCEPSessionImpl> futureClient = this.pccMock.createClient(clientAddr, RETRY_TIMER, CONNECT_TIMEOUT,
145                 SimpleSessionListener::new);
146         waitFutureSuccess(futureClient);
147         final PCEPSessionImpl session1 = futureClient.get();
148
149         try {
150             this.pccMock.createClient(clientAddr, RETRY_TIMER, CONNECT_TIMEOUT,
151                     SimpleSessionListener::new).get();
152             Assert.fail();
153         } catch (final ExecutionException e) {
154             Assert.assertTrue(e.getMessage().contains("A conflicting session for address"));
155         } finally {
156             session1.close();
157         }
158     }
159
160     @Test
161     public void testReconectClient() throws InterruptedException, ExecutionException {
162         final int port = InetSocketAddressUtil.getRandomPort();
163         final InetSocketAddress clientAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
164
165         doReturn(new InetSocketAddress("0.0.0.0", port)).when(this.dispatcherDependencies).getAddress();
166         doReturn(this.listenerFactory).when(this.dispatcherDependencies).getListenerFactory();
167         doReturn(new SimpleSessionListener()).when(this.listenerFactory).getSessionListener();
168         waitFutureSuccess(this.dispatcher.createServer(this.dispatcherDependencies));
169         final PCEPSessionImpl session1 = this.pccMock.createClient(clientAddr,
170                 RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
171
172         assertEquals(clientAddr.getAddress(), session1.getRemoteAddress());
173         assertEquals(DEAD_TIMER, session1.getDeadTimerValue().shortValue());
174         assertEquals(KEEP_ALIVE, session1.getKeepAliveTimerValue().shortValue());
175         waitFutureSuccess(session1.closeChannel());
176
177         final PCEPSessionImpl session2 = this.pccMock.createClient(clientAddr,
178                 RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
179
180         assertEquals(clientAddr.getAddress(), session1.getRemoteAddress());
181         assertEquals(DEAD_TIMER, session2.getDeadTimerValue().shortValue());
182         assertEquals(KEEP_ALIVE, session2.getKeepAliveTimerValue().shortValue());
183
184         session2.close();
185     }
186
187     @Test
188     public void testCustomizeBootstrap() {
189         final int port = InetSocketAddressUtil.getRandomPort();
190         final InetSocketAddress clientAddr1 = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
191         final InetSocketAddress clientAddr2 = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
192         final KeyMapping keys = KeyMapping.getKeyMapping(clientAddr1.getAddress(), "CLIENT1_ADDRESS");
193         keys.put(clientAddr2.getAddress(), "CLIENT2_ADDRESS".getBytes());
194
195         doReturn(new InetSocketAddress("0.0.0.0", port)).when(this.dispatcherDependencies).getAddress();
196         doReturn(this.listenerFactory).when(this.dispatcherDependencies).getListenerFactory();
197         doReturn(new SimpleSessionListener()).when(this.listenerFactory).getSessionListener();
198
199         final ChannelFuture futureChannel = this.disp2Spy.createServer(this.dispatcherDependencies);
200         waitFutureSuccess(futureChannel);
201         Mockito.verify(this.disp2Spy).createServerBootstrap(any(PCEPDispatcherImpl.ChannelPipelineInitializer.class));
202     }
203
204     @After
205     public void tearDown() {
206         this.dispatcher.close();
207         this.disp2Spy.close();
208     }
209
210     private static class PCCMock {
211         private final PCEPSessionNegotiatorFactory<PCEPSessionImpl> negotiatorFactory;
212         private final PCEPHandlerFactory factory;
213         private final EventExecutor executor;
214         private final EventLoopGroup workerGroup;
215
216         PCCMock(final PCEPSessionNegotiatorFactory<PCEPSessionImpl> negotiatorFactory,
217                 final PCEPHandlerFactory factory) {
218             this.workerGroup = new NioEventLoopGroup();
219             this.negotiatorFactory = requireNonNull(negotiatorFactory);
220             this.factory = requireNonNull(factory);
221             this.executor = requireNonNull(GlobalEventExecutor.INSTANCE);
222         }
223
224         Future<PCEPSessionImpl> createClient(final InetSocketAddress address, final int retryTimer,
225                 final int connectTimeout, final PCEPSessionListenerFactory listenerFactory) {
226             return createClient(address, retryTimer, connectTimeout, (ch, promise) -> {
227                 ch.pipeline().addLast(this.factory.getDecoders());
228                 ch.pipeline().addLast("negotiator", this.negotiatorFactory.getSessionNegotiator(
229                         () -> listenerFactory,
230                         ch,
231                         promise));
232                 ch.pipeline().addLast(this.factory.getEncoders());
233             });
234         }
235
236         Future<PCEPSessionImpl> createClient(final InetSocketAddress address, final int retryTimer,
237                 final int connectTimeout, final PCEPDispatcherImpl.ChannelPipelineInitializer initializer) {
238             final Bootstrap b = new Bootstrap();
239             final PCEPProtocolSessionPromise<PCEPSessionImpl> p = new PCEPProtocolSessionPromise<>(this.executor,
240                     address, retryTimer, connectTimeout, b);
241             b.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE).handler(new ChannelInitializer<SocketChannel>() {
242                 @Override
243                 protected void initChannel(final SocketChannel ch) {
244                     initializer.initializeChannel(ch, p);
245                 }
246             });
247
248             setWorkerGroup(b);
249             setChannelFactory(b);
250             p.connect();
251             return p;
252         }
253
254         private static void setChannelFactory(final Bootstrap b) {
255             try {
256                 b.channel(NioSocketChannel.class);
257             } catch (final IllegalStateException ignored) {
258             }
259         }
260
261         private void setWorkerGroup(final Bootstrap b) {
262             if (b.config().group() == null) {
263                 b.group(this.workerGroup);
264             }
265         }
266     }
267
268 }