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