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