b905f7ad2145a126a07396af2f2065ecb840014a
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / handler / ssh / client / AsyncSshHandlerReader.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 io.netty.buffer.ByteBuf;
12 import io.netty.buffer.Unpooled;
13 import org.apache.sshd.common.future.SshFutureListener;
14 import org.apache.sshd.common.io.IoInputStream;
15 import org.apache.sshd.common.io.IoReadFuture;
16 import org.apache.sshd.common.util.buffer.Buffer;
17 import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 /**
22  * Listener on async input stream from SSH session.
23  * This listeners schedules reads in a loop until the session is closed or read fails.
24  */
25 public final class AsyncSshHandlerReader implements SshFutureListener<IoReadFuture>, AutoCloseable {
26
27     private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandlerReader.class);
28
29     private static final int BUFFER_SIZE = 2048;
30
31     private final AutoCloseable connectionClosedCallback;
32     private final ReadMsgHandler readHandler;
33
34     private final String channelId;
35     private IoInputStream asyncOut;
36     private Buffer buf;
37     private IoReadFuture currentReadFuture;
38
39     public AsyncSshHandlerReader(final AutoCloseable connectionClosedCallback, final ReadMsgHandler readHandler,
40                                  final String channelId, final IoInputStream asyncOut) {
41         this.connectionClosedCallback = connectionClosedCallback;
42         this.readHandler = readHandler;
43         this.channelId = channelId;
44         this.asyncOut = asyncOut;
45         buf = new ByteArrayBuffer(BUFFER_SIZE);
46         asyncOut.read(buf).addListener(this);
47     }
48
49     @Override
50     public synchronized void operationComplete(final IoReadFuture future) {
51         if (future.getException() != null) {
52
53             //if asyncout is already set to null by close method, do nothing
54             if (asyncOut == null) {
55                 return;
56             }
57
58             if (asyncOut.isClosed() || asyncOut.isClosing()) {
59                 // Ssh dropped
60                 LOG.debug("Ssh session dropped on channel: {}", channelId, future.getException());
61             } else {
62                 LOG.warn("Exception while reading from SSH remote on channel {}", channelId, future.getException());
63             }
64             invokeDisconnect();
65             return;
66         }
67
68         if (future.getRead() > 0) {
69             final ByteBuf msg = Unpooled.wrappedBuffer(buf.array(), 0, future.getRead());
70             if (LOG.isTraceEnabled()) {
71                 LOG.trace("Reading message on channel: {}, message: {}",
72                         channelId, AsyncSshHandlerWriter.byteBufToString(msg));
73             }
74             readHandler.onMessageRead(msg);
75
76             // Schedule next read
77             buf = new ByteArrayBuffer(BUFFER_SIZE);
78             currentReadFuture = asyncOut.read(buf);
79             currentReadFuture.addListener(this);
80         }
81     }
82
83     @SuppressWarnings("checkstyle:IllegalCatch")
84     private void invokeDisconnect() {
85         try {
86             connectionClosedCallback.close();
87         } catch (final Exception e) {
88             // This should not happen
89             throw new IllegalStateException(e);
90         }
91     }
92
93     @Override
94     public synchronized void close() {
95         // Remove self as listener on close to prevent reading from closed input
96         if (currentReadFuture != null) {
97             currentReadFuture.removeListener(this);
98             currentReadFuture = null;
99         }
100
101         asyncOut = null;
102     }
103
104     public interface ReadMsgHandler {
105
106         void onMessageRead(ByteBuf msg);
107     }
108 }