This repository has been archived by the owner on Oct 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 312
/
AbstractClientChannel.java
609 lines (524 loc) · 19.2 KB
/
AbstractClientChannel.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
/*
* Copyright (C) 2012-2016 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.nifty.client;
import com.facebook.nifty.core.TChannelBufferInputTransport;
import com.facebook.nifty.duplex.TDuplexProtocolFactory;
import io.airlift.log.Logger;
import io.airlift.units.Duration;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TMessage;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioSocketChannel;
import org.jboss.netty.handler.timeout.ReadTimeoutException;
import org.jboss.netty.handler.timeout.WriteTimeoutException;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.Timer;
import org.jboss.netty.util.TimerTask;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@NotThreadSafe
public abstract class AbstractClientChannel extends SimpleChannelHandler implements
NiftyClientChannel {
private static final Logger LOGGER = Logger.get(AbstractClientChannel.class);
private final Channel nettyChannel;
private Duration sendTimeout = null;
// Timeout until the whole request must be received.
private Duration receiveTimeout = null;
// Timeout for not receiving any data from the server
private Duration readTimeout = null;
private final Map<Integer, Request> requestMap = new HashMap<>();
private volatile TException channelError;
private final Timer timer;
private final TDuplexProtocolFactory protocolFactory;
protected AbstractClientChannel(Channel nettyChannel, Timer timer, TDuplexProtocolFactory protocolFactory) {
this.nettyChannel = nettyChannel;
this.timer = timer;
this.protocolFactory = protocolFactory;
}
@Override
public Channel getNettyChannel() {
return nettyChannel;
}
@Override
public TDuplexProtocolFactory getProtocolFactory()
{
return protocolFactory;
}
protected abstract ChannelBuffer extractResponse(Object message) throws TTransportException;
protected int extractSequenceId(ChannelBuffer messageBuffer)
throws TTransportException
{
try {
messageBuffer.markReaderIndex();
TTransport inputTransport = new TChannelBufferInputTransport(messageBuffer);
TProtocol inputProtocol = getProtocolFactory().getInputProtocolFactory().getProtocol(inputTransport);
TMessage message = inputProtocol.readMessageBegin();
messageBuffer.resetReaderIndex();
return message.seqid;
} catch (Throwable t) {
throw new TTransportException("Could not find sequenceId in Thrift message", t);
}
}
protected abstract ChannelFuture writeRequest(ChannelBuffer request);
public void close()
{
getNettyChannel().close();
}
@Override
public void setSendTimeout(@Nullable Duration sendTimeout)
{
this.sendTimeout = sendTimeout;
}
@Override
public Duration getSendTimeout()
{
return sendTimeout;
}
@Override
public void setReceiveTimeout(@Nullable Duration receiveTimeout)
{
this.receiveTimeout = receiveTimeout;
}
@Override
public Duration getReceiveTimeout()
{
return receiveTimeout;
}
@Override
public void setReadTimeout(@Nullable Duration readTimeout)
{
this.readTimeout = readTimeout;
}
@Override
public Duration getReadTimeout()
{
return this.readTimeout;
}
@Override
public boolean hasError()
{
return channelError != null;
}
@Override
public TException getError()
{
return channelError;
}
@Override
public void executeInIoThread(Runnable runnable)
{
NioSocketChannel nioSocketChannel = (NioSocketChannel) getNettyChannel();
nioSocketChannel.getWorker().executeInIoThread(runnable, true);
}
@Override
public void sendAsynchronousRequest(final ChannelBuffer message,
final boolean oneway,
final Listener listener)
throws TException
{
final int sequenceId = extractSequenceId(message);
// Ensure channel listeners are always called on the channel's I/O thread
executeInIoThread(new Runnable()
{
@Override
public void run()
{
try {
final Request request = makeRequest(sequenceId, listener);
if (!nettyChannel.isConnected()) {
fireChannelErrorCallback(listener, new TTransportException(TTransportException.NOT_OPEN, "Channel closed"));
return;
}
if (hasError()) {
fireChannelErrorCallback(
listener,
new TTransportException(TTransportException.UNKNOWN, "Channel is in a bad state due to failing a previous request"));
return;
}
ChannelFuture sendFuture = writeRequest(message);
queueSendTimeout(request);
sendFuture.addListener(new ChannelFutureListener()
{
@Override
public void operationComplete(ChannelFuture future) throws Exception
{
messageSent(future, request, oneway);
}
});
}
catch (Throwable t) {
// onError calls all registered listeners in the requestMap, but this request
// may not be registered yet. So we try to remove it (to make sure we don't call
// the callback twice) and then manually make the callback for this request
// listener.
requestMap.remove(sequenceId);
fireChannelErrorCallback(listener, t);
onError(t);
}
}
});
}
private void messageSent(ChannelFuture future, Request request, boolean oneway)
{
try {
if (future.isSuccess()) {
cancelRequestTimeouts(request);
fireRequestSentCallback(request.getListener());
if (oneway) {
retireRequest(request);
} else {
queueReceiveAndReadTimeout(request);
}
} else {
TTransportException transportException =
new TTransportException("Sending request failed",
future.getCause());
onError(transportException);
}
}
catch (Throwable t) {
onError(t);
}
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
{
try {
ChannelBuffer response = extractResponse(e.getMessage());
if (response != null) {
int sequenceId = extractSequenceId(response);
onResponseReceived(sequenceId, response);
}
else {
ctx.sendUpstream(e);
}
}
catch (Throwable t) {
onError(t);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent event)
throws Exception
{
Throwable t = event.getCause();
onError(t);
}
private Request makeRequest(int sequenceId, Listener listener)
{
Request request = new Request(listener);
requestMap.put(sequenceId, request);
return request;
}
private void retireRequest(Request request)
{
cancelRequestTimeouts(request);
}
private void cancelRequestTimeouts(Request request)
{
Timeout sendTimeout = request.getSendTimeout();
if (sendTimeout != null && !sendTimeout.isCancelled()) {
sendTimeout.cancel();
}
Timeout receiveTimeout = request.getReceiveTimeout();
if (receiveTimeout != null && !receiveTimeout.isCancelled()) {
receiveTimeout.cancel();
}
Timeout readTimeout = request.getReadTimeout();
if (readTimeout != null && !readTimeout.isCancelled()) {
readTimeout.cancel();
}
}
private void cancelAllTimeouts()
{
for (Request request : requestMap.values()) {
cancelRequestTimeouts(request);
}
}
private void onResponseReceived(int sequenceId, ChannelBuffer response)
{
Request request = requestMap.remove(sequenceId);
if (request == null) {
onError(new TTransportException("Bad sequence id in response: " + sequenceId));
} else {
retireRequest(request);
fireResponseReceivedCallback(request.getListener(), response);
}
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception
{
if (!requestMap.isEmpty()) {
onError(new TTransportException("Client was disconnected by server"));
}
}
protected void onError(Throwable t)
{
TException wrappedException = wrapException(t);
if (channelError == null) {
channelError = wrappedException;
}
cancelAllTimeouts();
Collection<Request> requests = new ArrayList<>();
requests.addAll(requestMap.values());
requestMap.clear();
for (Request request : requests) {
fireChannelErrorCallback(request.getListener(), wrappedException);
}
Channel channel = getNettyChannel();
if (nettyChannel.isOpen())
{
channel.close();
}
}
protected TException wrapException(Throwable t)
{
if (t instanceof TException) {
return (TException) t;
} else {
return new TTransportException(t);
}
}
private void fireRequestSentCallback(Listener listener)
{
try {
listener.onRequestSent();
}
catch (Throwable t) {
LOGGER.warn(t, "Request sent listener callback triggered an exception");
}
}
private void fireResponseReceivedCallback(Listener listener, ChannelBuffer response)
{
try {
listener.onResponseReceived(response);
}
catch (Throwable t) {
LOGGER.warn(t, "Response received listener callback triggered an exception");
}
}
private void fireChannelErrorCallback(Listener listener, TException exception)
{
try {
listener.onChannelError(exception);
}
catch (Throwable t) {
LOGGER.warn(t, "Channel error listener callback triggered an exception");
}
}
private void fireChannelErrorCallback(Listener listener, Throwable throwable)
{
fireChannelErrorCallback(listener, wrapException(throwable));
}
private void onSendTimeoutFired(Request request)
{
cancelAllTimeouts();
WriteTimeoutException timeoutException = new WriteTimeoutException("Timed out waiting " + getSendTimeout() + " to send data to server");
fireChannelErrorCallback(request.getListener(), new TTransportException(TTransportException.TIMED_OUT, timeoutException));
}
private void onReceiveTimeoutFired(Request request)
{
cancelAllTimeouts();
ReadTimeoutException timeoutException = new ReadTimeoutException("Timed out waiting " + getReceiveTimeout() + " to receive response");
fireChannelErrorCallback(request.getListener(), new TTransportException(TTransportException.TIMED_OUT, timeoutException));
}
private void onReadTimeoutFired(Request request)
{
cancelAllTimeouts();
ReadTimeoutException timeoutException = new ReadTimeoutException("Timed out waiting " + getReadTimeout() + " to read data from server");
fireChannelErrorCallback(request.getListener(), new TTransportException(TTransportException.TIMED_OUT, timeoutException));
}
private void queueSendTimeout(final Request request) throws TTransportException
{
if (this.sendTimeout != null) {
long sendTimeoutMs = this.sendTimeout.toMillis();
if (sendTimeoutMs > 0) {
TimerTask sendTimeoutTask = new IoThreadBoundTimerTask(this, new TimerTask() {
@Override
public void run(Timeout timeout) {
onSendTimeoutFired(request);
}
});
Timeout sendTimeout;
try {
sendTimeout = timer.newTimeout(sendTimeoutTask, sendTimeoutMs, TimeUnit.MILLISECONDS);
}
catch (IllegalStateException e) {
throw new TTransportException("Unable to schedule send timeout", e);
}
request.setSendTimeout(sendTimeout);
}
}
}
private void queueReceiveAndReadTimeout(final Request request) throws TTransportException
{
if (this.receiveTimeout != null) {
long receiveTimeoutMs = this.receiveTimeout.toMillis();
if (receiveTimeoutMs > 0) {
TimerTask receiveTimeoutTask = new IoThreadBoundTimerTask(this, new TimerTask() {
@Override
public void run(Timeout timeout) {
onReceiveTimeoutFired(request);
}
});
Timeout timeout;
try {
timeout = timer.newTimeout(receiveTimeoutTask, receiveTimeoutMs, TimeUnit.MILLISECONDS);
}
catch (IllegalStateException e) {
throw new TTransportException("Unable to schedule request timeout", e);
}
request.setReceiveTimeout(timeout);
}
}
if (this.readTimeout != null) {
long readTimeoutNanos = this.readTimeout.roundTo(TimeUnit.NANOSECONDS);
if (readTimeoutNanos > 0) {
TimerTask readTimeoutTask = new IoThreadBoundTimerTask(this, new ReadTimeoutTask(readTimeoutNanos, request));
Timeout timeout;
try {
timeout = timer.newTimeout(readTimeoutTask, readTimeoutNanos, TimeUnit.NANOSECONDS);
}
catch (IllegalStateException e) {
throw new TTransportException("Unable to schedule read timeout", e);
}
request.setReadTimeout(timeout);
}
}
}
/**
* Used to create TimerTasks that will fire
*/
private static class IoThreadBoundTimerTask implements TimerTask {
private final NiftyClientChannel channel;
private final TimerTask timerTask;
public IoThreadBoundTimerTask(NiftyClientChannel channel, TimerTask timerTask)
{
this.channel = channel;
this.timerTask = timerTask;
}
@Override
public void run(final Timeout timeout)
throws Exception
{
channel.executeInIoThread(new Runnable()
{
@Override
public void run()
{
try {
timerTask.run(timeout);
} catch (Exception e) {
Channels.fireExceptionCaught(channel.getNettyChannel(), e);
}
}
});
}
}
/**
* Bundles the details of a client request that has started, but for which a response hasn't
* yet been received (or in the one-way case, the send operation hasn't completed yet).
*/
private static class Request
{
private final Listener listener;
private Timeout sendTimeout;
private Timeout receiveTimeout;
private volatile Timeout readTimeout;
public Request(Listener listener)
{
this.listener = listener;
}
public Listener getListener()
{
return listener;
}
public Timeout getReceiveTimeout()
{
return receiveTimeout;
}
public void setReceiveTimeout(Timeout receiveTimeout)
{
this.receiveTimeout = receiveTimeout;
}
public Timeout getReadTimeout()
{
return readTimeout;
}
public void setReadTimeout(Timeout readTimeout)
{
this.readTimeout = readTimeout;
}
public Timeout getSendTimeout()
{
return sendTimeout;
}
public void setSendTimeout(Timeout sendTimeout)
{
this.sendTimeout = sendTimeout;
}
}
private final class ReadTimeoutTask implements TimerTask
{
private final TimeoutHandler timeoutHandler;
private final long timeoutNanos;
private final Request request;
ReadTimeoutTask(long timeoutNanos, Request request)
{
this.timeoutHandler = TimeoutHandler.findTimeoutHandler(getNettyChannel().getPipeline());
this.timeoutNanos = timeoutNanos;
this.request = request;
}
public void run(Timeout timeout) throws Exception
{
if (timeoutHandler == null) {
return;
}
if (timeout.isCancelled()) {
return;
}
if (!getNettyChannel().isOpen()) {
return;
}
long currentTimeNanos = System.nanoTime();
long timePassed = currentTimeNanos - timeoutHandler.getLastMessageReceivedNanos();
long nextDelayNanos = timeoutNanos - timePassed;
if (nextDelayNanos <= 0) {
onReadTimeoutFired(request);
}
else {
request.setReadTimeout(timer.newTimeout(this, nextDelayNanos, TimeUnit.NANOSECONDS));
}
}
}
}