Merge "Bug 2055: Handle shard not initialized resiliently"
[controller.git] / opendaylight / netconf / netconf-ssh / src / test / java / org / opendaylight / controller / netconf / netty / SSHTest.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.controller.netconf.netty;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertTrue;
14
15 import com.google.common.base.Stopwatch;
16 import io.netty.bootstrap.Bootstrap;
17 import io.netty.channel.ChannelInitializer;
18 import io.netty.channel.EventLoopGroup;
19 import io.netty.channel.nio.NioEventLoopGroup;
20 import io.netty.channel.socket.nio.NioSocketChannel;
21 import io.netty.util.HashedWheelTimer;
22 import java.net.InetSocketAddress;
23 import java.nio.file.Files;
24 import java.util.concurrent.ExecutorService;
25 import java.util.concurrent.Executors;
26 import java.util.concurrent.ScheduledExecutorService;
27 import java.util.concurrent.TimeUnit;
28 import org.apache.sshd.server.PasswordAuthenticator;
29 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
30 import org.apache.sshd.server.session.ServerSession;
31 import org.junit.AfterClass;
32 import org.junit.BeforeClass;
33 import org.junit.Test;
34 import org.opendaylight.controller.netconf.netty.EchoClientHandler.State;
35 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
36 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.client.AsyncSshHandler;
37 import org.opendaylight.controller.netconf.ssh.SshProxyServer;
38 import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public class SSHTest {
43     public static final Logger logger = LoggerFactory.getLogger(SSHTest.class);
44     public static final String AHOJ = "ahoj\n";
45
46     private static EventLoopGroup nettyGroup;
47     private static HashedWheelTimer hashedWheelTimer;
48     private static ExecutorService nioExec;
49     private static ScheduledExecutorService minaTimerEx;
50
51     @BeforeClass
52     public static void setUp() throws Exception {
53         hashedWheelTimer = new HashedWheelTimer();
54         nettyGroup = new NioEventLoopGroup();
55         nioExec = Executors.newFixedThreadPool(1);
56         minaTimerEx = Executors.newScheduledThreadPool(1);
57     }
58
59     @AfterClass
60     public static void tearDown() throws Exception {
61         hashedWheelTimer.stop();
62         nettyGroup.shutdownGracefully().await();
63         minaTimerEx.shutdownNow();
64         nioExec.shutdownNow();
65     }
66
67     @Test
68     public void test() throws Exception {
69         new Thread(new EchoServer(), "EchoServer").start();
70
71         final InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 10831);
72         final SshProxyServer sshProxyServer = new SshProxyServer(minaTimerEx, nettyGroup, nioExec);
73         sshProxyServer.bind(addr, NetconfConfigUtil.getNetconfLocalAddress(),
74                 new PasswordAuthenticator() {
75                     @Override
76                     public boolean authenticate(final String username, final String password, final ServerSession session) {
77                         return true;
78                     }
79                 }, new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString()));
80
81         final EchoClientHandler echoClientHandler = connectClient(addr);
82
83         Stopwatch stopwatch = new Stopwatch().start();
84         while(echoClientHandler.isConnected() == false && stopwatch.elapsed(TimeUnit.SECONDS) < 30) {
85             Thread.sleep(500);
86         }
87         assertTrue(echoClientHandler.isConnected());
88         logger.info("connected, writing to client");
89         echoClientHandler.write(AHOJ);
90
91         // check that server sent back the same string
92         stopwatch = stopwatch.reset().start();
93         while (echoClientHandler.read().endsWith(AHOJ) == false && stopwatch.elapsed(TimeUnit.SECONDS) < 30) {
94             Thread.sleep(500);
95         }
96
97         try {
98             final String read = echoClientHandler.read();
99             assertTrue(read + " should end with " + AHOJ, read.endsWith(AHOJ));
100         } finally {
101             logger.info("Closing socket");
102             sshProxyServer.close();
103         }
104     }
105
106     public EchoClientHandler connectClient(final InetSocketAddress address) {
107         final EchoClientHandler echoClientHandler = new EchoClientHandler();
108         final ChannelInitializer<NioSocketChannel> channelInitializer = new ChannelInitializer<NioSocketChannel>() {
109             @Override
110             public void initChannel(final NioSocketChannel ch) throws Exception {
111                 ch.pipeline().addFirst(AsyncSshHandler.createForNetconfSubsystem(new LoginPassword("a", "a")));
112                 ch.pipeline().addLast(echoClientHandler);
113             }
114         };
115         final Bootstrap b = new Bootstrap();
116
117         b.group(nettyGroup)
118                 .channel(NioSocketChannel.class)
119                 .handler(channelInitializer);
120
121         // Start the client.
122         b.connect(address).addListener(echoClientHandler);
123         return echoClientHandler;
124     }
125
126     @Test
127     public void testClientWithoutServer() throws Exception {
128         final InetSocketAddress address = new InetSocketAddress(12345);
129         final EchoClientHandler echoClientHandler = connectClient(address);
130         final Stopwatch stopwatch = new Stopwatch().start();
131         while(echoClientHandler.getState() == State.CONNECTING && stopwatch.elapsed(TimeUnit.SECONDS) < 5) {
132             Thread.sleep(100);
133         }
134         assertFalse(echoClientHandler.isConnected());
135         assertEquals(State.CONNECTION_CLOSED, echoClientHandler.getState());
136     }
137
138 }