BUG-2560 Canonical write to remote netconf devices
[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.channel.ChannelHandlerContext;
14 import io.netty.channel.ChannelOutboundHandlerAdapter;
15 import io.netty.channel.ChannelPromise;
16 import java.io.IOException;
17 import java.net.SocketAddress;
18 import org.apache.sshd.ClientChannel;
19 import org.apache.sshd.ClientSession;
20 import org.apache.sshd.SshClient;
21 import org.apache.sshd.client.future.AuthFuture;
22 import org.apache.sshd.client.future.ConnectFuture;
23 import org.apache.sshd.client.future.OpenFuture;
24 import org.apache.sshd.common.future.CloseFuture;
25 import org.apache.sshd.common.future.SshFutureListener;
26 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 /**
31  * Netty SSH handler class. Acts as interface between Netty and SSH library.
32  */
33 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
34
35     private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
36     public static final String SUBSYSTEM = "netconf";
37
38     public static final SshClient DEFAULT_CLIENT = SshClient.setUpDefaultClient();
39
40     public static final int SSH_DEFAULT_NIO_WORKERS = 8;
41
42     static {
43         // TODO make configurable, or somehow reuse netty threadpool
44         DEFAULT_CLIENT.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
45         DEFAULT_CLIENT.start();
46     }
47
48     private final AuthenticationHandler authenticationHandler;
49     private final SshClient sshClient;
50
51     private AsyncSshHandlerReader sshReadAsyncListener;
52     private AsyncSshHandlerWriter sshWriteAsyncHandler;
53
54     private ClientChannel channel;
55     private ClientSession session;
56     private ChannelPromise connectPromise;
57
58
59     public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) throws IOException {
60         return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
61     }
62
63     /**
64      *
65      * @param authenticationHandler
66      * @param sshClient started SshClient
67      * @throws IOException
68      */
69     public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient) throws IOException {
70         this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
71         this.sshClient = Preconditions.checkNotNull(sshClient);
72         // Start just in case
73         sshClient.start();
74     }
75
76     private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) {
77         LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
78
79         final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
80         sshConnectionFuture.addListener(new SshFutureListener<ConnectFuture>() {
81             @Override
82             public void operationComplete(final ConnectFuture future) {
83                 if (future.isConnected()) {
84                     handleSshSessionCreated(future, ctx);
85                 } else {
86                     handleSshSetupFailure(ctx, future.getException());
87                 }
88             }
89         });
90     }
91
92     private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
93         try {
94             LOG.trace("SSH session created on channel: {}", ctx.channel());
95
96             session = future.getSession();
97             final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
98             authenticateFuture.addListener(new SshFutureListener<AuthFuture>() {
99                 @Override
100                 public void operationComplete(final AuthFuture future) {
101                     if (future.isSuccess()) {
102                         handleSshAuthenticated(session, ctx);
103                     } else {
104                         // Exception does not have to be set in the future, add simple exception in such case
105                         final Throwable exception = future.getException() == null ?
106                                 new IllegalStateException("Authentication failed") :
107                                 future.getException();
108                         handleSshSetupFailure(ctx, exception);
109                     }
110                 }
111             });
112         } catch (final IOException e) {
113             handleSshSetupFailure(ctx, e);
114         }
115     }
116
117     private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) {
118         try {
119             LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), session.getServerVersion());
120
121             channel = session.createSubsystemChannel(SUBSYSTEM);
122             channel.setStreaming(ClientChannel.Streaming.Async);
123             channel.open().addListener(new SshFutureListener<OpenFuture>() {
124                 @Override
125                 public void operationComplete(final OpenFuture future) {
126                     if(future.isOpened()) {
127                         handleSshChanelOpened(ctx);
128                     } else {
129                         handleSshSetupFailure(ctx, future.getException());
130                     }
131                 }
132             });
133
134
135         } catch (final IOException e) {
136             handleSshSetupFailure(ctx, e);
137         }
138     }
139
140     private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
141         LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
142
143         connectPromise.setSuccess();
144
145         // TODO we should also read from error stream and at least log from that
146
147         sshReadAsyncListener = new AsyncSshHandlerReader(new AutoCloseable() {
148             @Override
149             public void close() throws Exception {
150                 AsyncSshHandler.this.disconnect(ctx, ctx.newPromise());
151             }
152         }, new AsyncSshHandlerReader.ReadMsgHandler() {
153             @Override
154             public void onMessageRead(final ByteBuf msg) {
155                 ctx.fireChannelRead(msg);
156             }
157         }, channel.toString(), channel.getAsyncOut());
158
159         // if readAsyncListener receives immediate close, it will close this handler and closing this handler sets channel variable to null
160         if(channel != null) {
161             sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
162             ctx.fireChannelActive();
163         }
164     }
165
166     private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable e) {
167         LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), e);
168         disconnect(ctx, ctx.newPromise());
169
170         // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
171         if(!connectPromise.isDone()) {
172             connectPromise.setFailure(e);
173         }
174     }
175
176     @Override
177     public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
178         sshWriteAsyncHandler.write(ctx, msg, promise);
179     }
180
181     @Override
182     public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
183         LOG.debug("XXX session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
184         this.connectPromise = promise;
185         startSsh(ctx, remoteAddress);
186     }
187
188     @Override
189     public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
190         disconnect(ctx, promise);
191     }
192
193     @Override
194     public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
195         LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}", ctx.channel(), connectPromise);
196
197         // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
198         if(connectPromise.isSuccess()) {
199             ctx.fireChannelInactive();
200         }
201
202         if(sshWriteAsyncHandler != null) {
203             sshWriteAsyncHandler.close();
204         }
205
206         if(sshReadAsyncListener != null) {
207             sshReadAsyncListener.close();
208         }
209
210         if(session!= null && !session.isClosed() && !session.isClosing()) {
211             session.close(false).addListener(new SshFutureListener<CloseFuture>() {
212                 @Override
213                 public void operationComplete(final CloseFuture future) {
214                     if (future.isClosed() == false) {
215                         session.close(true);
216                     }
217                     session = null;
218                 }
219             });
220         }
221
222         // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs to cleanup its resources
223         // e.g. Socket that it tries to open in its constructor (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
224         // TODO better solution would be to implement custom ChannelFactory + Channel that will use mina SSH lib internally: port this to custom channel implementation
225         try {
226             // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
227             super.disconnect(ctx, ctx.newPromise());
228         } catch (final Exception e) {
229             LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
230         }
231
232         channel = null;
233         promise.setSuccess();
234         LOG.debug("SSH session closed on channel: {}", ctx.channel());
235     }
236
237 }