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