Merge "Fix failing reconnect test."
[controller.git] / opendaylight / netconf / netconf-netty-util / src / main / java / org / opendaylight / controller / netconf / nettyutil / handler / ssh / client / AsyncSshHandler.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.nettyutil.handler.ssh.client;
10
11 import com.google.common.base.Preconditions;
12 import io.netty.channel.ChannelHandlerContext;
13 import io.netty.channel.ChannelOutboundHandlerAdapter;
14 import io.netty.channel.ChannelPromise;
15 import java.io.IOException;
16 import java.net.SocketAddress;
17 import org.apache.sshd.ClientChannel;
18 import org.apache.sshd.ClientSession;
19 import org.apache.sshd.SshClient;
20 import org.apache.sshd.client.future.AuthFuture;
21 import org.apache.sshd.client.future.ConnectFuture;
22 import org.apache.sshd.client.future.OpenFuture;
23 import org.apache.sshd.common.future.CloseFuture;
24 import org.apache.sshd.common.future.SshFutureListener;
25 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 /**
30  * Netty SSH handler class. Acts as interface between Netty and SSH library.
31  */
32 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
33
34     private static final Logger logger = LoggerFactory.getLogger(AsyncSshHandler.class);
35     public static final String SUBSYSTEM = "netconf";
36
37     public static final SshClient DEFAULT_CLIENT = SshClient.setUpDefaultClient();
38
39     public static final int SSH_DEFAULT_NIO_WORKERS = 8;
40
41     static {
42         // TODO make configurable, or somehow reuse netty threadpool
43         DEFAULT_CLIENT.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
44         DEFAULT_CLIENT.start();
45     }
46
47     private final AuthenticationHandler authenticationHandler;
48     private final SshClient sshClient;
49
50     private AsyncSshHanderReader sshReadAsyncListener;
51     private AsyncSshHandlerWriter sshWriteAsyncHandler;
52
53     private ClientChannel channel;
54     private ClientSession session;
55     private ChannelPromise connectPromise;
56
57
58     public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) throws IOException {
59         return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
60     }
61
62     /**
63      *
64      * @param authenticationHandler
65      * @param sshClient started SshClient
66      * @throws IOException
67      */
68     public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient) throws IOException {
69         this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
70         this.sshClient = Preconditions.checkNotNull(sshClient);
71         // Start just in case
72         sshClient.start();
73     }
74
75     private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) {
76         logger.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
77
78         final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
79         sshConnectionFuture.addListener(new SshFutureListener<ConnectFuture>() {
80             @Override
81             public void operationComplete(final ConnectFuture future) {
82                 if (future.isConnected()) {
83                     handleSshSessionCreated(future, ctx);
84                 } else {
85                     handleSshSetupFailure(ctx, future.getException());
86                 }
87             }
88         });
89     }
90
91     private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
92         try {
93             logger.trace("SSH session created on channel: {}", ctx.channel());
94
95             session = future.getSession();
96             final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
97             authenticateFuture.addListener(new SshFutureListener<AuthFuture>() {
98                 @Override
99                 public void operationComplete(final AuthFuture future) {
100                     if (future.isSuccess()) {
101                         handleSshAuthenticated(session, ctx);
102                     } else {
103                         handleSshSetupFailure(ctx, future.getException());
104                     }
105                 }
106             });
107         } catch (final IOException e) {
108             handleSshSetupFailure(ctx, e);
109         }
110     }
111
112     private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) {
113         try {
114             logger.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), session.getServerVersion());
115
116             channel = session.createSubsystemChannel(SUBSYSTEM);
117             channel.setStreaming(ClientChannel.Streaming.Async);
118             channel.open().addListener(new SshFutureListener<OpenFuture>() {
119                 @Override
120                 public void operationComplete(final OpenFuture future) {
121                     if(future.isOpened()) {
122                         handleSshChanelOpened(ctx);
123                     } else {
124                         handleSshSetupFailure(ctx, future.getException());
125                     }
126                 }
127             });
128
129
130         } catch (final IOException e) {
131             handleSshSetupFailure(ctx, e);
132         }
133     }
134
135     private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
136         logger.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
137
138         connectPromise.setSuccess();
139         connectPromise = null;
140
141         sshReadAsyncListener = new AsyncSshHanderReader(this, ctx, channel.getAsyncOut());
142         // if readAsyncListener receives immediate close, it will close this handler and closing this handler sets channel variable to null
143         if(channel != null) {
144             sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
145             ctx.fireChannelActive();
146         }
147     }
148
149     private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable e) {
150         logger.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), e);
151         connectPromise.setFailure(e);
152         connectPromise = null;
153         throw new IllegalStateException("Unable to setup SSH connection on channel: " + ctx.channel(), e);
154     }
155
156     @Override
157     public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
158         sshWriteAsyncHandler.write(ctx, msg, promise);
159     }
160
161     @Override
162     public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
163         this.connectPromise = promise;
164         startSsh(ctx, remoteAddress);
165     }
166
167     @Override
168     public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
169         disconnect(ctx, promise);
170     }
171
172     @Override
173     public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
174         if(sshReadAsyncListener != null) {
175             sshReadAsyncListener.close();
176         }
177
178         if(sshWriteAsyncHandler != null) {
179             sshWriteAsyncHandler.close();
180         }
181
182         if(session!= null && !session.isClosed() && !session.isClosing()) {
183             session.close(false).addListener(new SshFutureListener<CloseFuture>() {
184                 @Override
185                 public void operationComplete(final CloseFuture future) {
186                     if (future.isClosed() == false) {
187                         session.close(true);
188                     }
189                     session = null;
190                 }
191             });
192         }
193
194         channel = null;
195         promise.setSuccess();
196
197         logger.debug("SSH session closed on channel: {}", ctx.channel());
198         ctx.fireChannelInactive();
199     }
200
201 }