Fixed deadlock between AsyncSshHandlerReader and AsyncSshHandler
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / 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.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 io.netty.util.concurrent.Future;
16 import io.netty.util.concurrent.GenericFutureListener;
17 import java.io.IOException;
18 import java.net.SocketAddress;
19 import java.util.concurrent.atomic.AtomicBoolean;
20 import org.apache.sshd.client.SshClient;
21 import org.apache.sshd.client.channel.ClientChannel;
22 import org.apache.sshd.client.future.AuthFuture;
23 import org.apache.sshd.client.future.ConnectFuture;
24 import org.apache.sshd.client.session.ClientSession;
25 import org.opendaylight.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     private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
34
35     public static final String SUBSYSTEM = "netconf";
36
37     public static final int SSH_DEFAULT_NIO_WORKERS = 8;
38     // Disable default timeouts from mina sshd
39     private static final long DEFAULT_TIMEOUT = -1L;
40
41     public static final SshClient DEFAULT_CLIENT;
42
43     static {
44         final SshClient c = SshClient.setUpDefaultClient();
45         c.getProperties().put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
46         c.getProperties().put(SshClient.IDLE_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
47
48         // TODO make configurable, or somehow reuse netty threadpool
49         c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
50         c.start();
51         DEFAULT_CLIENT = c;
52     }
53
54     private final AuthenticationHandler authenticationHandler;
55     private final SshClient sshClient;
56     private final AtomicBoolean isDisconnected = new AtomicBoolean();
57     private Future<?> negotiationFuture;
58
59     private AsyncSshHandlerReader sshReadAsyncListener;
60     private AsyncSshHandlerWriter sshWriteAsyncHandler;
61
62     private ClientChannel channel;
63     private ClientSession session;
64     private ChannelPromise connectPromise;
65     private GenericFutureListener negotiationFutureListener;
66
67     public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient,
68             final Future<?> negotiationFuture) {
69         this(authenticationHandler, sshClient);
70         this.negotiationFuture = negotiationFuture;
71     }
72
73     /**
74      * Constructor of {@code AsyncSshHandler}.
75      *
76      * @param authenticationHandler authentication handler
77      * @param sshClient             started SshClient
78      */
79     public AsyncSshHandler(final AuthenticationHandler authenticationHandler,
80                            final SshClient sshClient) {
81         this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
82         this.sshClient = Preconditions.checkNotNull(sshClient);
83     }
84
85     public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) {
86         return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
87     }
88
89     /**
90      * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful
91      * netconf negotiation.
92      *
93      * @param authenticationHandler authentication handler
94      * @param negotiationFuture     negotiation future
95      * @return                      {@code AsyncSshHandler}
96      */
97     public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
98             final Future<?> negotiationFuture) {
99         return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT, negotiationFuture);
100     }
101
102     private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) throws IOException {
103         LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
104
105         final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
106         sshConnectionFuture.addListener(future -> {
107             if (future.isConnected()) {
108                 handleSshSessionCreated(future, ctx);
109             } else {
110                 handleSshSetupFailure(ctx, future.getException());
111             }
112         });
113     }
114
115     private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
116         try {
117             LOG.trace("SSH session created on channel: {}", ctx.channel());
118
119             session = future.getSession();
120             final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
121             final ClientSession localSession = session;
122             authenticateFuture.addListener(future1 -> {
123                 if (future1.isSuccess()) {
124                     handleSshAuthenticated(localSession, ctx);
125                 } else {
126                     // Exception does not have to be set in the future, add simple exception in such case
127                     final Throwable exception = future1.getException() == null
128                             ? new IllegalStateException("Authentication failed") : future1.getException();
129                     handleSshSetupFailure(ctx, exception);
130                 }
131             });
132         } catch (final IOException e) {
133             handleSshSetupFailure(ctx, e);
134         }
135     }
136
137     private synchronized void handleSshAuthenticated(final ClientSession newSession, final ChannelHandlerContext ctx) {
138         try {
139             LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
140                     newSession.getServerVersion());
141
142             channel = newSession.createSubsystemChannel(SUBSYSTEM);
143             channel.setStreaming(ClientChannel.Streaming.Async);
144             channel.open().addListener(future -> {
145                 if (future.isOpened()) {
146                     handleSshChanelOpened(ctx);
147                 } else {
148                     handleSshSetupFailure(ctx, future.getException());
149                 }
150             });
151
152
153         } catch (final IOException e) {
154             handleSshSetupFailure(ctx, e);
155         }
156     }
157
158     private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
159         LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
160
161         if (negotiationFuture == null) {
162             connectPromise.setSuccess();
163         }
164
165         // TODO we should also read from error stream and at least log from that
166
167         ClientChannel localChannel = channel;
168         sshReadAsyncListener = new AsyncSshHandlerReader(() -> AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()),
169             ctx::fireChannelRead, localChannel.toString(), localChannel.getAsyncOut());
170
171         // if readAsyncListener receives immediate close,
172         // it will close this handler and closing this handler sets channel variable to null
173         if (channel != null) {
174             sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
175             ctx.fireChannelActive();
176         }
177     }
178
179     private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable error) {
180         LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), error);
181
182         // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
183         if (!connectPromise.isDone()) {
184             connectPromise.setFailure(error);
185         }
186
187         disconnect(ctx, ctx.newPromise());
188     }
189
190     @Override
191     public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
192         sshWriteAsyncHandler.write(ctx, msg, promise);
193     }
194
195     @Override
196     public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
197                                      final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
198         LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
199         this.connectPromise = promise;
200
201         if (negotiationFuture != null) {
202             negotiationFutureListener = future -> {
203                 if (future.isSuccess()) {
204                     promise.setSuccess();
205                 }
206             };
207             //complete connection promise with netconf negotiation future
208             negotiationFuture.addListener(negotiationFutureListener);
209         }
210         startSsh(ctx, remoteAddress);
211     }
212
213     @Override
214     public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
215         disconnect(ctx, promise);
216     }
217
218     @Override
219     public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
220         if (isDisconnected.compareAndSet(false, true)) {
221             safelyDisconnect(ctx, promise);
222         }
223     }
224
225     @SuppressWarnings("checkstyle:IllegalCatch")
226     private synchronized void safelyDisconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
227         LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}",
228                 ctx.channel(), connectPromise);
229
230         // If we have already succeeded and the session was dropped after,
231         // we need to fire inactive to notify reconnect logic
232         if (connectPromise.isSuccess()) {
233             ctx.fireChannelInactive();
234         }
235
236         if (sshWriteAsyncHandler != null) {
237             sshWriteAsyncHandler.close();
238         }
239
240         if (sshReadAsyncListener != null) {
241             sshReadAsyncListener.close();
242         }
243
244         //If connection promise is not already set, it means negotiation failed
245         //we must set connection promise to failure
246         if (!connectPromise.isDone()) {
247             connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
248         }
249
250         //Remove listener from negotiation future, we don't want notifications
251         //from negotiation anymore
252         if (negotiationFuture != null) {
253             negotiationFuture.removeListener(negotiationFutureListener);
254         }
255
256         if (session != null && !session.isClosed() && !session.isClosing()) {
257             session.close(false).addListener(future -> {
258                 synchronized (this) {
259                     if (!future.isClosed()) {
260                         session.close(true);
261                     }
262                     session = null;
263                 }
264             });
265         }
266
267         // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs
268         // to cleanup its resources e.g. Socket that it tries to open in its constructor
269         // (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
270         // TODO better solution would be to implement custom ChannelFactory + Channel
271         // that will use mina SSH lib internally: port this to custom channel implementation
272         try {
273             // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
274             super.disconnect(ctx, ctx.newPromise());
275         } catch (final Exception e) {
276             LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
277         }
278
279         channel = null;
280         promise.setSuccess();
281         LOG.debug("SSH session closed on channel: {}", ctx.channel());
282     }
283 }