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