BUG-1568 Ssh Handler for netconf client Mina implementation
[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.buffer.ByteBuf;
13 import io.netty.buffer.Unpooled;
14 import io.netty.channel.ChannelHandlerContext;
15 import io.netty.channel.ChannelOutboundHandlerAdapter;
16 import io.netty.channel.ChannelPromise;
17 import java.io.IOException;
18 import java.net.SocketAddress;
19 import org.apache.sshd.ClientChannel;
20 import org.apache.sshd.ClientSession;
21 import org.apache.sshd.SshClient;
22 import org.apache.sshd.client.future.AuthFuture;
23 import org.apache.sshd.client.future.ConnectFuture;
24 import org.apache.sshd.client.future.OpenFuture;
25 import org.apache.sshd.common.future.CloseFuture;
26 import org.apache.sshd.common.future.SshFutureListener;
27 import org.apache.sshd.common.io.IoInputStream;
28 import org.apache.sshd.common.io.IoReadFuture;
29 import org.apache.sshd.common.util.Buffer;
30 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 /**
35  * Netty SSH handler class. Acts as interface between Netty and SSH library.
36  */
37 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
38
39     private static final Logger logger = LoggerFactory.getLogger(AsyncSshHandler.class);
40     public static final String SUBSYSTEM = "netconf";
41
42     public static final SshClient DEFAULT_CLIENT = SshClient.setUpDefaultClient();
43
44     public static final int SSH_DEFAULT_NIO_WORKERS = 8;
45
46     static {
47         // TODO make configurable, or somehow reuse netty threadpool
48         DEFAULT_CLIENT.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
49         DEFAULT_CLIENT.start();
50     }
51
52     private final AuthenticationHandler authenticationHandler;
53     private final SshClient sshClient;
54
55     private SshReadAsyncListener sshReadAsyncListener;
56     private ClientChannel channel;
57     private ClientSession session;
58     private ChannelPromise connectPromise;
59
60     public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) throws IOException {
61         return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
62     }
63
64     /**
65      *
66      * @param authenticationHandler
67      * @param sshClient started SshClient
68      * @throws IOException
69      */
70     public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient) throws IOException {
71         this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
72         this.sshClient = Preconditions.checkNotNull(sshClient);
73         // Start just in case
74         sshClient.start();
75     }
76
77     private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) {
78         logger.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
79
80         final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
81         sshConnectionFuture.addListener(new SshFutureListener<ConnectFuture>() {
82             @Override
83             public void operationComplete(final ConnectFuture future) {
84                 if (future.isConnected()) {
85                     handleSshSessionCreated(future, ctx);
86                 } else {
87                     handleSshSetupFailure(ctx, future.getException());
88                 }
89             }
90         });
91     }
92
93     private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
94         try {
95             logger.trace("SSH session created on channel: {}", ctx.channel());
96
97             session = future.getSession();
98             final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
99             authenticateFuture.addListener(new SshFutureListener<AuthFuture>() {
100                 @Override
101                 public void operationComplete(final AuthFuture future) {
102                     if (future.isSuccess()) {
103                         handleSshAuthenticated(session, ctx);
104                     } else {
105                         handleSshSetupFailure(ctx, future.getException());
106                     }
107                 }
108             });
109         } catch (final IOException e) {
110             handleSshSetupFailure(ctx, e);
111         }
112     }
113
114     private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) {
115         try {
116             logger.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), session.getServerVersion());
117
118             channel = session.createSubsystemChannel(SUBSYSTEM);
119             channel.setStreaming(ClientChannel.Streaming.Async);
120             channel.open().addListener(new SshFutureListener<OpenFuture>() {
121                 @Override
122                 public void operationComplete(final OpenFuture future) {
123                     if(future.isOpened()) {
124                         handleSshChanelOpened(ctx);
125                     } else {
126                         handleSshSetupFailure(ctx, future.getException());
127                     }
128                 }
129             });
130
131
132         } catch (final IOException e) {
133             handleSshSetupFailure(ctx, e);
134         }
135     }
136
137     private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
138         logger.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
139
140         connectPromise.setSuccess();
141         connectPromise = null;
142         ctx.fireChannelActive();
143
144         final IoInputStream asyncOut = channel.getAsyncOut();
145         sshReadAsyncListener = new SshReadAsyncListener(ctx, asyncOut);
146     }
147
148     private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable e) {
149         logger.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), e);
150         connectPromise.setFailure(e);
151         connectPromise = null;
152         throw new IllegalStateException("Unable to setup SSH connection on channel: " + ctx.channel(), e);
153     }
154
155     @Override
156     public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
157         try {
158             if(channel.getAsyncIn().isClosed() || channel.getAsyncIn().isClosing()) {
159                 handleSshSessionClosed(ctx);
160             } else {
161                 channel.getAsyncIn().write(toBuffer(msg));
162                 ((ByteBuf) msg).release();
163             }
164         } catch (final Exception e) {
165             logger.warn("Exception while writing to SSH remote on channel {}", ctx.channel(), e);
166             throw new IllegalStateException("Exception while writing to SSH remote on channel " + ctx.channel(),e);
167         }
168     }
169
170     private static void handleSshSessionClosed(final ChannelHandlerContext ctx) {
171         logger.debug("SSH session closed on channel: {}", ctx.channel());
172         ctx.fireChannelInactive();
173     }
174
175     private Buffer toBuffer(final Object msg) {
176         // TODO Buffer vs ByteBuf translate, Can we handle that better ?
177         Preconditions.checkState(msg instanceof ByteBuf);
178         final ByteBuf byteBuf = (ByteBuf) msg;
179         final byte[] temp = new byte[byteBuf.readableBytes()];
180         byteBuf.readBytes(temp, 0, byteBuf.readableBytes());
181         return new Buffer(temp);
182     }
183
184     @Override
185     public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
186         this.connectPromise = promise;
187         startSsh(ctx, remoteAddress);
188     }
189
190     @Override
191     public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
192         disconnect(ctx, promise);
193     }
194
195     @Override
196     public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
197         if(sshReadAsyncListener != null) {
198             sshReadAsyncListener.close();
199         }
200
201         session.close(false).addListener(new SshFutureListener<CloseFuture>() {
202             @Override
203             public void operationComplete(final CloseFuture future) {
204                 if(future.isClosed() == false) {
205                     session.close(true);
206                 }
207                 session = null;
208             }
209         });
210
211         channel = null;
212     }
213
214     /**
215      * Listener over async input stream from SSH session.
216      * This listeners schedules reads in a loop until the session is closed or read fails.
217      */
218     private static class SshReadAsyncListener implements SshFutureListener<IoReadFuture>, AutoCloseable {
219         private static final int BUFFER_SIZE = 8192;
220
221         private final ChannelHandlerContext ctx;
222
223         private IoInputStream asyncOut;
224         private Buffer buf;
225         private IoReadFuture currentReadFuture;
226
227         public SshReadAsyncListener(final ChannelHandlerContext ctx, final IoInputStream asyncOut) {
228             this.ctx = ctx;
229             this.asyncOut = asyncOut;
230             buf = new Buffer(BUFFER_SIZE);
231             asyncOut.read(buf).addListener(this);
232         }
233
234         @Override
235         public synchronized void operationComplete(final IoReadFuture future) {
236             if(future.getException() != null) {
237
238                 if(asyncOut.isClosed() || asyncOut.isClosing()) {
239                     // We are closing
240                     handleSshSessionClosed(ctx);
241                 } else {
242                     logger.warn("Exception while reading from SSH remote on channel {}", ctx.channel(), future.getException());
243                     throw new IllegalStateException("Exception while reading from SSH remote on channel " + ctx.channel(), future.getException());
244                 }
245             }
246
247             if (future.getRead() > 0) {
248                 ctx.fireChannelRead(Unpooled.wrappedBuffer(buf.array(), 0, future.getRead()));
249
250                 // Schedule next read
251                 buf = new Buffer(BUFFER_SIZE);
252                 currentReadFuture = asyncOut.read(buf);
253                 currentReadFuture.addListener(this);
254             }
255         }
256
257         @Override
258         public synchronized void close() throws Exception {
259             // Remove self as listener on close to prevent reading from closed input
260             if(currentReadFuture != null) {
261                 currentReadFuture.removeListener(this);
262             }
263
264             asyncOut = null;
265         }
266     }
267 }