96e5a975f92497f1f609566651e6771753a6d9b2
[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 com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
12
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.channel.ChannelOutboundHandlerAdapter;
15 import io.netty.channel.ChannelPromise;
16 import io.netty.util.concurrent.Future;
17 import io.netty.util.concurrent.GenericFutureListener;
18 import java.io.IOException;
19 import java.net.SocketAddress;
20 import java.util.concurrent.TimeUnit;
21 import java.util.concurrent.atomic.AtomicBoolean;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
24 import org.opendaylight.netconf.shaded.sshd.client.SshClient;
25 import org.opendaylight.netconf.shaded.sshd.client.channel.ClientChannel;
26 import org.opendaylight.netconf.shaded.sshd.client.future.AuthFuture;
27 import org.opendaylight.netconf.shaded.sshd.client.future.ConnectFuture;
28 import org.opendaylight.netconf.shaded.sshd.client.session.ClientSession;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33  * Netty SSH handler class. Acts as interface between Netty and SSH library.
34  */
35 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
36     private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
37
38     public static final String SUBSYSTEM = "netconf";
39
40     public static final int SSH_DEFAULT_NIO_WORKERS = 8;
41     // Disable default timeouts from mina sshd
42     private static final long DEFAULT_TIMEOUT = -1L;
43
44     public static final NetconfSshClient DEFAULT_CLIENT;
45
46     static {
47         final NetconfSshClient c = new NetconfClientBuilder().build();
48         c.getProperties().put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
49         c.getProperties().put(SshClient.IDLE_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
50
51         // TODO make configurable, or somehow reuse netty threadpool
52         c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
53         c.start();
54         DEFAULT_CLIENT = c;
55     }
56
57     private final AtomicBoolean isDisconnected = new AtomicBoolean();
58     private final AuthenticationHandler authenticationHandler;
59     private final Future<?> negotiationFuture;
60     private final NetconfSshClient sshClient;
61
62     private AsyncSshHandlerWriter sshWriteAsyncHandler;
63
64     private NettyAwareChannelSubsystem channel;
65     private ClientSession session;
66     private ChannelPromise connectPromise;
67     private GenericFutureListener negotiationFutureListener;
68
69     public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final NetconfSshClient 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 NetconfSshClient 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, final @Nullable NetconfSshClient 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             verify(session instanceof NettyAwareClientSession, "Unexpected session %s", session);
124
125             final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
126             final NettyAwareClientSession localSession = (NettyAwareClientSession) session;
127             authenticateFuture.addListener(future1 -> {
128                 if (future1.isSuccess()) {
129                     handleSshAuthenticated(localSession, ctx);
130                 } else {
131                     handleSshSetupFailure(ctx, new AuthenticationFailedException("Authentication failed",
132                         future1.getException()));
133                 }
134             });
135         } catch (final IOException e) {
136             handleSshSetupFailure(ctx, e);
137         }
138     }
139
140     private synchronized void handleSshAuthenticated(final NettyAwareClientSession newSession,
141             final ChannelHandlerContext ctx) {
142         try {
143             LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
144                     newSession.getServerVersion());
145
146             channel = newSession.createSubsystemChannel(SUBSYSTEM, ctx);
147             channel.setStreaming(ClientChannel.Streaming.Async);
148             channel.open().addListener(future -> {
149                 if (future.isOpened()) {
150                     handleSshChanelOpened(ctx);
151                 } else {
152                     handleSshSetupFailure(ctx, future.getException());
153                 }
154             });
155
156
157         } catch (final IOException e) {
158             handleSshSetupFailure(ctx, e);
159         }
160     }
161
162     private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
163         LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
164
165         if (negotiationFuture == null) {
166             connectPromise.setSuccess();
167         }
168
169         sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
170         ctx.fireChannelActive();
171         channel.onClose(() -> disconnect(ctx, ctx.newPromise()));
172     }
173
174     private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable error) {
175         LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), error);
176
177         // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
178         if (!connectPromise.isDone()) {
179             connectPromise.setFailure(error);
180         }
181
182         disconnect(ctx, ctx.newPromise());
183     }
184
185     @Override
186     public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
187         sshWriteAsyncHandler.write(ctx, msg, promise);
188     }
189
190     @Override
191     public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
192                                      final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
193         LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
194         this.connectPromise = promise;
195
196         if (negotiationFuture != null) {
197             negotiationFutureListener = future -> {
198                 if (future.isSuccess()) {
199                     promise.setSuccess();
200                 }
201             };
202             //complete connection promise with netconf negotiation future
203             negotiationFuture.addListener(negotiationFutureListener);
204         }
205         startSsh(ctx, remoteAddress);
206     }
207
208     @Override
209     public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
210         disconnect(ctx, promise);
211     }
212
213     @Override
214     public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
215         if (isDisconnected.compareAndSet(false, true)) {
216             safelyDisconnect(ctx, promise);
217         }
218     }
219
220     @SuppressWarnings("checkstyle:IllegalCatch")
221     private synchronized void safelyDisconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
222         LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}",
223                 ctx.channel(), connectPromise);
224
225         // If we have already succeeded and the session was dropped after,
226         // we need to fire inactive to notify reconnect logic
227         if (connectPromise.isSuccess()) {
228             ctx.fireChannelInactive();
229         }
230
231         if (sshWriteAsyncHandler != null) {
232             sshWriteAsyncHandler.close();
233         }
234
235         //If connection promise is not already set, it means negotiation failed
236         //we must set connection promise to failure
237         if (!connectPromise.isDone()) {
238             connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
239         }
240
241         //Remove listener from negotiation future, we don't want notifications
242         //from negotiation anymore
243         if (negotiationFuture != null) {
244             negotiationFuture.removeListener(negotiationFutureListener);
245         }
246
247         if (session != null && !session.isClosed() && !session.isClosing()) {
248             session.close(false).addListener(future -> {
249                 synchronized (this) {
250                     if (!future.isClosed()) {
251                         session.close(true);
252                     }
253                     session = null;
254                 }
255             });
256         }
257
258         // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs
259         // to cleanup its resources e.g. Socket that it tries to open in its constructor
260         // (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
261         // TODO better solution would be to implement custom ChannelFactory + Channel
262         // that will use mina SSH lib internally: port this to custom channel implementation
263         try {
264             // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
265             super.disconnect(ctx, ctx.newPromise());
266         } catch (final Exception e) {
267             LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
268         }
269
270         if (channel != null) {
271             //TODO: see if calling just close() is sufficient
272             //channel.close(false);
273             channel.close();
274             channel = null;
275         }
276         promise.setSuccess();
277         LOG.debug("SSH session closed on channel: {}", ctx.channel());
278     }
279 }