e333da2b7610ab6b210e4c158b5e9b2f2cbcf2e7
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / handler / ssh / client / AsyncSshHandlerWriter.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.ChannelPromise;
15 import java.nio.charset.StandardCharsets;
16 import java.util.Deque;
17 import java.util.LinkedList;
18 import java.util.Queue;
19 import org.apache.sshd.common.future.SshFutureListener;
20 import org.apache.sshd.common.io.IoOutputStream;
21 import org.apache.sshd.common.io.IoWriteFuture;
22 import org.apache.sshd.common.io.WritePendingException;
23 import org.apache.sshd.common.util.Buffer;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 /**
28  * Async Ssh writer. Takes messages(byte arrays) and sends them encrypted to remote server.
29  * Also handles pending writes by caching requests until pending state is over.
30  */
31 public final class AsyncSshHandlerWriter implements AutoCloseable {
32
33     private static final Logger LOG = LoggerFactory
34             .getLogger(AsyncSshHandlerWriter.class);
35
36     // public static final int MAX_PENDING_WRITES = 1000;
37     // TODO implement Limiting mechanism for pending writes
38     // But there is a possible issue with limiting:
39     // 1. What to do when queue is full ? Immediate Fail for every request ?
40     // 2. At this level we might be dealing with Chunks of messages(not whole messages)
41     // and unexpected behavior might occur when we send/queue 1 chunk and fail the other chunks
42
43     private volatile IoOutputStream asyncIn;
44
45     // Order has to be preserved for queued writes
46     private final Deque<PendingWriteRequest> pending = new LinkedList<>();
47
48     public AsyncSshHandlerWriter(final IoOutputStream asyncIn) {
49         this.asyncIn = asyncIn;
50     }
51
52     public void write(final ChannelHandlerContext ctx,
53             final Object msg, final ChannelPromise promise) {
54         if (asyncIn == null) {
55             promise.setFailure(new IllegalStateException("Channel closed"));
56             return;
57         }
58         // synchronized block due to deadlock that happens on ssh window resize
59         // writes and pending writes would lock the underlyinch channel session
60         // window resize write would try to write the message on an already locked channelSession
61         // while the pending write was in progress from the write callback
62         synchronized (asyncIn) {
63             // TODO check for isClosed, isClosing might be performed by mina SSH internally and is not required here
64             // If we are closed/closing, set immediate fail
65             if (asyncIn.isClosed() || asyncIn.isClosing()) {
66                 promise.setFailure(new IllegalStateException("Channel closed"));
67             } else {
68                 final ByteBuf byteBufMsg = (ByteBuf) msg;
69                 if (pending.isEmpty() == false) {
70                     queueRequest(ctx, byteBufMsg, promise);
71                     return;
72                 }
73
74                 writeWithPendingDetection(ctx, promise, byteBufMsg, false);
75             }
76         }
77     }
78
79     //sending message with pending
80     //if resending message not succesfull, then attribute wasPending is true
81     private void writeWithPendingDetection(final ChannelHandlerContext ctx, final ChannelPromise promise,
82                                            final ByteBuf byteBufMsg, final boolean wasPending) {
83         try {
84
85             if (LOG.isTraceEnabled()) {
86                 LOG.trace("Writing request on channel: {}, message: {}", ctx.channel(), byteBufToString(byteBufMsg));
87             }
88             asyncIn.write(toBuffer(byteBufMsg)).addListener(new SshFutureListener<IoWriteFuture>() {
89
90                 @Override
91                 public void operationComplete(final IoWriteFuture future) {
92                     // synchronized block due to deadlock that happens on ssh window resize
93                     // writes and pending writes would lock the underlyinch channel session
94                     // window resize write would try to write the message on an already locked channelSession,
95                     // while the pending write was in progress from the write callback
96                     synchronized (asyncIn) {
97                         if (LOG.isTraceEnabled()) {
98                             LOG.trace(
99                                 "Ssh write request finished on channel: {} with result: {}: and ex:{}, message: {}",
100                                 ctx.channel(), future.isWritten(), future.getException(), byteBufToString(byteBufMsg));
101                         }
102
103                         // Notify success or failure
104                         if (future.isWritten()) {
105                             promise.setSuccess();
106                         } else {
107                             LOG.warn("Ssh write request failed on channel: {} for message: {}", ctx.channel(),
108                                     byteBufToString(byteBufMsg), future.getException());
109                             promise.setFailure(future.getException());
110                         }
111
112                         // Not needed anymore, release
113                         byteBufMsg.release();
114
115                         //rescheduling message from queue after successfully sent
116                         if (wasPending) {
117                             byteBufMsg.resetReaderIndex();
118                             pending.remove();
119                         }
120                     }
121
122                     // Check pending queue and schedule next
123                     // At this time we are guaranteed that we are not in pending state anymore
124                     // so the next request should succeed
125                     writePendingIfAny();
126                 }
127             });
128
129         } catch (final WritePendingException e) {
130
131             if (wasPending == false) {
132                 queueRequest(ctx, byteBufMsg, promise);
133             }
134         }
135     }
136
137     private void writePendingIfAny() {
138         synchronized (asyncIn) {
139             if (pending.peek() == null) {
140                 return;
141             }
142
143             final PendingWriteRequest pendingWrite = pending.peek();
144             final ByteBuf msg = pendingWrite.msg;
145             if (LOG.isTraceEnabled()) {
146                 LOG.trace("Writing pending request on channel: {}, message: {}",
147                         pendingWrite.ctx.channel(), byteBufToString(msg));
148             }
149
150             writeWithPendingDetection(pendingWrite.ctx, pendingWrite.promise, msg, true);
151         }
152     }
153
154     public static String byteBufToString(final ByteBuf msg) {
155         final String s = msg.toString(StandardCharsets.UTF_8);
156         msg.resetReaderIndex();
157         return s;
158     }
159
160     private void queueRequest(final ChannelHandlerContext ctx, final ByteBuf msg, final ChannelPromise promise) {
161 //        try {
162         LOG.debug("Write pending on channel: {}, queueing, current queue size: {}", ctx.channel(), pending.size());
163         if (LOG.isTraceEnabled()) {
164             LOG.trace("Queueing request due to pending: {}", byteBufToString(msg));
165         }
166         new PendingWriteRequest(ctx, msg, promise).pend(pending);
167 //        } catch (final Exception ex) {
168 //            LOG.warn("Unable to queue write request on channel: {}. Setting fail for the request: {}",
169 //                    ctx.channel(), ex, byteBufToString(msg));
170 //            msg.release();
171 //            promise.setFailure(ex);
172 //        }
173     }
174
175     @Override
176     public void close() {
177         asyncIn = null;
178     }
179
180     private static Buffer toBuffer(final ByteBuf msg) {
181         // TODO Buffer vs ByteBuf translate, Can we handle that better ?
182         msg.resetReaderIndex();
183         final byte[] temp = new byte[msg.readableBytes()];
184         msg.readBytes(temp, 0, msg.readableBytes());
185         return new Buffer(temp);
186     }
187
188     private static final class PendingWriteRequest {
189         private final ChannelHandlerContext ctx;
190         private final ByteBuf msg;
191         private final ChannelPromise promise;
192
193         PendingWriteRequest(final ChannelHandlerContext ctx, final ByteBuf msg, final ChannelPromise promise) {
194             this.ctx = ctx;
195             // Reset reader index, last write (failed) attempt moved index to the end
196             msg.resetReaderIndex();
197             this.msg = msg;
198             this.promise = promise;
199         }
200
201         public void pend(final Queue<PendingWriteRequest> pending) {
202             // Preconditions.checkState(pending.size() < MAX_PENDING_WRITES,
203             // "Too much pending writes(%s) on channel: %s, remote window is not getting read or is too small",
204             // pending.size(), ctx.channel());
205             Preconditions.checkState(pending.offer(this),
206                 "Cannot pend another request write (pending count: %s) on channel: %s", pending.size(), ctx.channel());
207         }
208     }
209 }