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