2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.netconf.nettyutil.handler.ssh.client;
11 import com.google.common.base.Preconditions;
12 import io.netty.buffer.ByteBuf;
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.channel.ChannelPromise;
15 import java.io.IOException;
16 import java.nio.charset.StandardCharsets;
17 import java.util.Deque;
18 import java.util.LinkedList;
19 import java.util.Queue;
20 import org.apache.sshd.common.io.IoOutputStream;
21 import org.apache.sshd.common.io.WritePendingException;
22 import org.apache.sshd.common.util.buffer.Buffer;
23 import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
24 import org.checkerframework.checker.lock.qual.GuardedBy;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
29 * Async Ssh writer. Takes messages(byte arrays) and sends them encrypted to remote server.
30 * Also handles pending writes by caching requests until pending state is over.
32 public final class AsyncSshHandlerWriter implements AutoCloseable {
34 private static final Logger LOG = LoggerFactory
35 .getLogger(AsyncSshHandlerWriter.class);
37 // public static final int MAX_PENDING_WRITES = 1000;
38 // TODO implement Limiting mechanism for pending writes
39 // But there is a possible issue with limiting:
40 // 1. What to do when queue is full ? Immediate Fail for every request ?
41 // 2. At this level we might be dealing with Chunks of messages(not whole messages)
42 // and unexpected behavior might occur when we send/queue 1 chunk and fail the other chunks
44 private final Object asyncInLock = new Object();
45 private volatile IoOutputStream asyncIn;
47 // Order has to be preserved for queued writes
48 private final Deque<PendingWriteRequest> pending = new LinkedList<>();
50 public AsyncSshHandlerWriter(final IoOutputStream asyncIn) {
51 this.asyncIn = asyncIn;
54 @GuardedBy("asyncInLock")
55 private boolean isWriteExecuted = false;
57 public void write(final ChannelHandlerContext ctx,
58 final Object msg, final ChannelPromise promise) {
59 if (asyncIn == null) {
60 promise.setFailure(new IllegalStateException("Channel closed"));
63 // synchronized block due to deadlock that happens on ssh window resize
64 // writes and pending writes would lock the underlyinch channel session
65 // window resize write would try to write the message on an already locked channelSession
66 // while the pending write was in progress from the write callback
67 synchronized (asyncInLock) {
68 // TODO check for isClosed, isClosing might be performed by mina SSH internally and is not required here
69 // If we are closed/closing, set immediate fail
70 if (asyncIn.isClosed() || asyncIn.isClosing()) {
71 promise.setFailure(new IllegalStateException("Channel closed"));
73 final ByteBuf byteBufMsg = (ByteBuf) msg;
74 if (isWriteExecuted) {
75 queueRequest(ctx, byteBufMsg, promise);
79 writeWithPendingDetection(ctx, promise, byteBufMsg, false);
84 //sending message with pending
85 //if resending message not succesfull, then attribute wasPending is true
86 private void writeWithPendingDetection(final ChannelHandlerContext ctx, final ChannelPromise promise,
87 final ByteBuf byteBufMsg, final boolean wasPending) {
90 if (LOG.isTraceEnabled()) {
91 LOG.trace("Writing request on channel: {}, message: {}", ctx.channel(), byteBufToString(byteBufMsg));
94 isWriteExecuted = true;
96 asyncIn.writePacket(toBuffer(byteBufMsg)).addListener(future -> {
97 // synchronized block due to deadlock that happens on ssh window resize
98 // writes and pending writes would lock the underlyinch channel session
99 // window resize write would try to write the message on an already locked channelSession,
100 // while the pending write was in progress from the write callback
101 synchronized (asyncInLock) {
102 if (LOG.isTraceEnabled()) {
104 "Ssh write request finished on channel: {} with result: {}: and ex:{}, message: {}",
105 ctx.channel(), future.isWritten(), future.getException(), byteBufToString(byteBufMsg));
108 // Notify success or failure
109 if (future.isWritten()) {
110 promise.setSuccess();
112 LOG.warn("Ssh write request failed on channel: {} for message: {}", ctx.channel(),
113 byteBufToString(byteBufMsg), future.getException());
114 promise.setFailure(future.getException());
117 //rescheduling message from queue after successfully sent
119 byteBufMsg.resetReaderIndex();
123 // Not needed anymore, release
124 byteBufMsg.release();
127 // Check pending queue and schedule next
128 // At this time we are guaranteed that we are not in pending state anymore
129 // so the next request should succeed
133 } catch (final IOException | WritePendingException e) {
135 queueRequest(ctx, byteBufMsg, promise);
140 private void writePendingIfAny() {
141 synchronized (asyncInLock) {
142 if (pending.peek() == null) {
143 isWriteExecuted = false;
147 final PendingWriteRequest pendingWrite = pending.peek();
148 final ByteBuf msg = pendingWrite.msg;
149 if (LOG.isTraceEnabled()) {
150 LOG.trace("Writing pending request on channel: {}, message: {}",
151 pendingWrite.ctx.channel(), byteBufToString(msg));
154 writeWithPendingDetection(pendingWrite.ctx, pendingWrite.promise, msg, true);
158 public static String byteBufToString(final ByteBuf msg) {
159 final String s = msg.toString(StandardCharsets.UTF_8);
160 msg.resetReaderIndex();
164 private void queueRequest(final ChannelHandlerContext ctx, final ByteBuf msg, final ChannelPromise promise) {
166 LOG.debug("Write pending on channel: {}, queueing, current queue size: {}", ctx.channel(), pending.size());
167 if (LOG.isTraceEnabled()) {
168 LOG.trace("Queueing request due to pending: {}", byteBufToString(msg));
170 new PendingWriteRequest(ctx, msg, promise).pend(pending);
171 // } catch (final Exception ex) {
172 // LOG.warn("Unable to queue write request on channel: {}. Setting fail for the request: {}",
173 // ctx.channel(), ex, byteBufToString(msg));
175 // promise.setFailure(ex);
180 public void close() {
184 private static Buffer toBuffer(final ByteBuf msg) {
185 // TODO Buffer vs ByteBuf translate, Can we handle that better ?
186 msg.resetReaderIndex();
187 final byte[] temp = new byte[msg.readableBytes()];
188 msg.readBytes(temp, 0, msg.readableBytes());
189 return new ByteArrayBuffer(temp);
192 private static final class PendingWriteRequest {
193 private final ChannelHandlerContext ctx;
194 private final ByteBuf msg;
195 private final ChannelPromise promise;
197 PendingWriteRequest(final ChannelHandlerContext ctx, final ByteBuf msg, final ChannelPromise promise) {
199 // Reset reader index, last write (failed) attempt moved index to the end
200 msg.resetReaderIndex();
202 this.promise = promise;
205 public void pend(final Queue<PendingWriteRequest> pending) {
206 // Preconditions.checkState(pending.size() < MAX_PENDING_WRITES,
207 // "Too much pending writes(%s) on channel: %s, remote window is not getting read or is too small",
208 // pending.size(), ctx.channel());
209 Preconditions.checkState(pending.offer(this),
210 "Cannot pend another request write (pending count: %s) on channel: %s", pending.size(), ctx.channel());