Merge "Bug 1029: Remove dead code: p2site"
[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.ssh.SshProxyServerConfigurationBuilder;
39 import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public class SSHTest {
44     public static final Logger logger = 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();
64         minaTimerEx.shutdownNow();
65         nioExec.shutdownNow();
66     }
67
68     @Test
69     public void test() throws Exception {
70         new Thread(new EchoServer(), "EchoServer").start();
71
72         final InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 10831);
73         final SshProxyServer sshProxyServer = new SshProxyServer(minaTimerEx, nettyGroup, nioExec);
74         sshProxyServer.bind(
75                 new SshProxyServerConfigurationBuilder().setBindingAddress(addr).setLocalAddress(NetconfConfigUtil.getNetconfLocalAddress()).setAuthenticator(new PasswordAuthenticator() {
76                     @Override
77                     public boolean authenticate(final String username, final String password, final ServerSession session) {
78                         return true;
79                     }
80                 }).setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString())).setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration());
81
82         final EchoClientHandler echoClientHandler = connectClient(addr);
83
84         Stopwatch stopwatch = new Stopwatch().start();
85         while(echoClientHandler.isConnected() == false && stopwatch.elapsed(TimeUnit.SECONDS) < 30) {
86             Thread.sleep(500);
87         }
88         assertTrue(echoClientHandler.isConnected());
89         logger.info("connected, writing to client");
90         echoClientHandler.write(AHOJ);
91
92         // check that server sent back the same string
93         stopwatch = stopwatch.reset().start();
94         while (echoClientHandler.read().endsWith(AHOJ) == false && stopwatch.elapsed(TimeUnit.SECONDS) < 30) {
95             Thread.sleep(500);
96         }
97
98         try {
99             final String read = echoClientHandler.read();
100             assertTrue(read + " should end with " + AHOJ, read.endsWith(AHOJ));
101         } finally {
102             logger.info("Closing socket");
103             sshProxyServer.close();
104         }
105     }
106
107     public EchoClientHandler connectClient(final InetSocketAddress address) {
108         final EchoClientHandler echoClientHandler = new EchoClientHandler();
109         final ChannelInitializer<NioSocketChannel> channelInitializer = new ChannelInitializer<NioSocketChannel>() {
110             @Override
111             public void initChannel(final NioSocketChannel ch) throws Exception {
112                 ch.pipeline().addFirst(AsyncSshHandler.createForNetconfSubsystem(new LoginPassword("a", "a")));
113                 ch.pipeline().addLast(echoClientHandler);
114             }
115         };
116         final Bootstrap b = new Bootstrap();
117
118         b.group(nettyGroup)
119                 .channel(NioSocketChannel.class)
120                 .handler(channelInitializer);
121
122         // Start the client.
123         b.connect(address).addListener(echoClientHandler);
124         return echoClientHandler;
125     }
126
127     @Test
128     public void testClientWithoutServer() throws Exception {
129         final InetSocketAddress address = new InetSocketAddress(12345);
130         final EchoClientHandler echoClientHandler = connectClient(address);
131         final Stopwatch stopwatch = new Stopwatch().start();
132         while(echoClientHandler.getState() == State.CONNECTING && stopwatch.elapsed(TimeUnit.SECONDS) < 5) {
133             Thread.sleep(100);
134         }
135         assertFalse(echoClientHandler.isConnected());
136         assertEquals(State.CONNECTION_CLOSED, echoClientHandler.getState());
137     }
138
139 }