-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Nio2Endpoint.java
1727 lines (1548 loc) · 66.8 KB
/
Nio2Endpoint.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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.tomcat.util.net;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.CompletionHandler;
import java.nio.channels.FileChannel;
import java.nio.channels.NetworkChannel;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.collections.SynchronizedStack;
import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
import org.apache.tomcat.util.net.jsse.JSSESupport;
/**
* NIO2 endpoint.
*/
public class Nio2Endpoint extends AbstractJsseEndpoint<Nio2Channel,AsynchronousSocketChannel> {
// -------------------------------------------------------------- Constants
private static final Log log = LogFactory.getLog(Nio2Endpoint.class);
// ----------------------------------------------------------------- Fields
/**
* Server socket "pointer".
*/
private volatile AsynchronousServerSocketChannel serverSock = null;
/**
* Allows detecting if a completion handler completes inline.
*/
private static ThreadLocal<Boolean> inlineCompletion = new ThreadLocal<>();
/**
* Thread group associated with the server socket.
*/
private AsynchronousChannelGroup threadGroup = null;
private volatile boolean allClosed;
/**
* Bytebuffer cache, each channel holds a set of buffers (two, except for SSL holds four)
*/
private SynchronizedStack<Nio2Channel> nioChannels;
public Nio2Endpoint() {
// Override the defaults for NIO2
// Disable maxConnections by default for NIO2 (see BZ58103)
setMaxConnections(-1);
}
// ------------------------------------------------------------- Properties
/**
* Is deferAccept supported?
*/
@Override
public boolean getDeferAccept() {
// Not supported
return false;
}
// --------------------------------------------------------- Public Methods
/**
* Number of keep-alive sockets.
*
* @return Always returns -1.
*/
public int getKeepAliveCount() {
// For this connector, only the overall connection count is relevant
return -1;
}
// ----------------------------------------------- Public Lifecycle Methods
/**
* Initialize the endpoint.
*/
@Override
public void bind() throws Exception {
// Create worker collection
if ( getExecutor() == null ) {
createExecutor();
}
if (getExecutor() instanceof ExecutorService) {
threadGroup = AsynchronousChannelGroup.withThreadPool((ExecutorService) getExecutor());
}
// AsynchronousChannelGroup currently needs exclusive access to its executor service
if (!internalExecutor) {
log.warn(sm.getString("endpoint.nio2.exclusiveExecutor"));
}
serverSock = AsynchronousServerSocketChannel.open(threadGroup);
socketProperties.setProperties(serverSock);
InetSocketAddress addr = (getAddress()!=null?new InetSocketAddress(getAddress(),getPort()):new InetSocketAddress(getPort()));
serverSock.bind(addr,getAcceptCount());
// Initialize thread count defaults for acceptor, poller
if (acceptorThreadCount != 1) {
// NIO2 does not allow any form of IO concurrency
acceptorThreadCount = 1;
}
// Initialize SSL if needed
initialiseSsl();
}
/**
* Start the NIO2 endpoint, creating acceptor.
*/
@Override
public void startInternal() throws Exception {
if (!running) {
allClosed = false;
running = true;
paused = false;
processorCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
socketProperties.getProcessorCache());
nioChannels = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
socketProperties.getBufferPool());
// Create worker collection
if ( getExecutor() == null ) {
createExecutor();
}
initializeConnectionLatch();
startAcceptorThreads();
}
}
/**
* Stop the endpoint. This will cause all processing threads to stop.
*/
@Override
public void stopInternal() {
if (!paused) {
pause();
}
if (running) {
running = false;
// Use the executor to avoid binding the main thread if something bad
// occurs and unbind will also wait for a bit for it to complete
getExecutor().execute(new Runnable() {
@Override
public void run() {
// Then close all active connections if any remain
try {
for (Nio2Channel channel : getHandler().getOpenSockets()) {
closeSocket(channel.getSocket());
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
} finally {
allClosed = true;
}
}
});
nioChannels.clear();
processorCache.clear();
}
}
/**
* Deallocate NIO memory pools, and close server socket.
*/
@Override
public void unbind() throws Exception {
if (running) {
stop();
}
doCloseServerSocket();
destroySsl();
super.unbind();
// Unlike other connectors, the thread pool is tied to the server socket
shutdownExecutor();
if (getHandler() != null) {
getHandler().recycle();
}
}
@Override
protected void doCloseServerSocket() throws IOException {
// Close server socket
if (serverSock != null) {
serverSock.close();
serverSock = null;
}
}
@Override
public void shutdownExecutor() {
if (threadGroup != null && internalExecutor) {
try {
long timeout = getExecutorTerminationTimeoutMillis();
while (timeout > 0 && !allClosed) {
timeout -= 100;
Thread.sleep(100);
}
threadGroup.shutdownNow();
if (timeout > 0) {
threadGroup.awaitTermination(timeout, TimeUnit.MILLISECONDS);
}
} catch (IOException e) {
getLog().warn(sm.getString("endpoint.warn.executorShutdown", getName()), e);
} catch (InterruptedException e) {
// Ignore
}
if (!threadGroup.isTerminated()) {
getLog().warn(sm.getString("endpoint.warn.executorShutdown", getName()));
}
threadGroup = null;
}
// Mostly to cleanup references
super.shutdownExecutor();
}
// ------------------------------------------------------ Protected Methods
/**
* Process the specified connection.
* @param socket The socket channel
* @return <code>true</code> if the socket was correctly configured
* and processing may continue, <code>false</code> if the socket needs to be
* close immediately
*/
@Override
protected boolean setSocketOptions(AsynchronousSocketChannel socket) {
try {
socketProperties.setProperties(socket);
Nio2Channel channel = nioChannels.pop();
if (channel == null) {
SocketBufferHandler bufhandler = new SocketBufferHandler(
socketProperties.getAppReadBufSize(),
socketProperties.getAppWriteBufSize(),
socketProperties.getDirectBuffer());
if (isSSLEnabled()) {
channel = new SecureNio2Channel(bufhandler, this);
} else {
channel = new Nio2Channel(bufhandler);
}
}
Nio2SocketWrapper socketWrapper = new Nio2SocketWrapper(channel, this);
channel.reset(socket, socketWrapper);
socketWrapper.setReadTimeout(getConnectionTimeout());
socketWrapper.setWriteTimeout(getConnectionTimeout());
socketWrapper.setKeepAliveLeft(Nio2Endpoint.this.getMaxKeepAliveRequests());
socketWrapper.setSecure(isSSLEnabled());
// Continue processing on another thread
return processSocket(socketWrapper, SocketEvent.OPEN_READ, true);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error("",t);
}
// Tell to close the socket
return false;
}
@Override
protected void closeSocket(AsynchronousSocketChannel socket) {
countDownConnection();
try {
socket.close();
} catch (IOException ioe) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("endpoint.err.close"), ioe);
}
}
}
@Override
protected NetworkChannel getServerSocket() {
return serverSock;
}
@Override
protected AsynchronousSocketChannel serverSocketAccept() throws Exception {
return serverSock.accept().get();
}
@Override
protected Log getLog() {
return log;
}
@Override
protected SocketProcessorBase<Nio2Channel> createSocketProcessor(
SocketWrapperBase<Nio2Channel> socketWrapper, SocketEvent event) {
return new SocketProcessor(socketWrapper, event);
}
private void closeSocket(SocketWrapperBase<Nio2Channel> socket) {
if (log.isDebugEnabled()) {
log.debug("Calling [" + this + "].closeSocket([" + socket + "],[" + socket.getSocket() + "])",
new Exception());
}
if (socket == null) {
return;
}
try {
getHandler().release(socket);
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
if (log.isDebugEnabled()) log.error("",e);
}
Nio2SocketWrapper nio2Socket = (Nio2SocketWrapper) socket;
try {
synchronized (socket.getSocket()) {
if (!nio2Socket.closed) {
nio2Socket.closed = true;
countDownConnection();
}
if (socket.getSocket().isOpen()) {
socket.getSocket().close(true);
}
}
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
if (log.isDebugEnabled()) log.error("",e);
}
try {
if (nio2Socket.getSendfileData() != null
&& nio2Socket.getSendfileData().fchannel != null
&& nio2Socket.getSendfileData().fchannel.isOpen()) {
nio2Socket.getSendfileData().fchannel.close();
}
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
if (log.isDebugEnabled()) log.error("",e);
}
}
public static class Nio2SocketWrapper extends SocketWrapperBase<Nio2Channel> {
private static final ThreadLocal<AtomicInteger> nestedWriteCompletionCount =
new ThreadLocal<AtomicInteger>() {
@Override
protected AtomicInteger initialValue() {
return new AtomicInteger(0);
}
};
private SendfileData sendfileData = null;
private final CompletionHandler<Integer, SocketWrapperBase<Nio2Channel>> readCompletionHandler;
private final Semaphore readPending = new Semaphore(1);
private boolean readInterest = false; // Guarded by readCompletionHandler
private final CompletionHandler<Integer, ByteBuffer> writeCompletionHandler;
private final CompletionHandler<Long, ByteBuffer[]> gatheringWriteCompletionHandler;
private final Semaphore writePending = new Semaphore(1);
private boolean writeInterest = false; // Guarded by writeCompletionHandler
private boolean writeNotify = false;
private volatile boolean closed = false;
private CompletionHandler<Integer, SocketWrapperBase<Nio2Channel>> awaitBytesHandler
= new CompletionHandler<Integer, SocketWrapperBase<Nio2Channel>>() {
@Override
public void completed(Integer nBytes, SocketWrapperBase<Nio2Channel> attachment) {
if (nBytes.intValue() < 0) {
failed(new ClosedChannelException(), attachment);
return;
}
getEndpoint().processSocket(attachment, SocketEvent.OPEN_READ, Nio2Endpoint.isInline());
}
@Override
public void failed(Throwable exc, SocketWrapperBase<Nio2Channel> attachment) {
getEndpoint().processSocket(attachment, SocketEvent.DISCONNECT, true);
}
};
private CompletionHandler<Integer, SendfileData> sendfileHandler
= new CompletionHandler<Integer, SendfileData>() {
@Override
public void completed(Integer nWrite, SendfileData attachment) {
if (nWrite.intValue() < 0) {
failed(new EOFException(), attachment);
return;
}
attachment.pos += nWrite.intValue();
ByteBuffer buffer = getSocket().getBufHandler().getWriteBuffer();
if (!buffer.hasRemaining()) {
if (attachment.length <= 0) {
// All data has now been written
setSendfileData(null);
try {
attachment.fchannel.close();
} catch (IOException e) {
// Ignore
}
if (isInline()) {
attachment.doneInline = true;
} else {
switch (attachment.keepAliveState) {
case NONE: {
getEndpoint().processSocket(Nio2SocketWrapper.this,
SocketEvent.DISCONNECT, false);
break;
}
case PIPELINED: {
getEndpoint().processSocket(Nio2SocketWrapper.this,
SocketEvent.OPEN_READ, true);
break;
}
case OPEN: {
awaitBytes();
break;
}
}
}
return;
} else {
getSocket().getBufHandler().configureWriteBufferForWrite();
int nRead = -1;
try {
nRead = attachment.fchannel.read(buffer);
} catch (IOException e) {
failed(e, attachment);
return;
}
if (nRead > 0) {
getSocket().getBufHandler().configureWriteBufferForRead();
if (attachment.length < buffer.remaining()) {
buffer.limit(buffer.limit() - buffer.remaining() + (int) attachment.length);
}
attachment.length -= nRead;
} else {
failed(new EOFException(), attachment);
return;
}
}
}
getSocket().write(buffer, toNio2Timeout(getWriteTimeout()), TimeUnit.MILLISECONDS, attachment, this);
}
@Override
public void failed(Throwable exc, SendfileData attachment) {
try {
attachment.fchannel.close();
} catch (IOException e) {
// Ignore
}
if (!isInline()) {
getEndpoint().processSocket(Nio2SocketWrapper.this, SocketEvent.ERROR, false);
} else {
attachment.doneInline = true;
attachment.error = true;
}
}
};
public Nio2SocketWrapper(Nio2Channel channel, final Nio2Endpoint endpoint) {
super(channel, endpoint);
socketBufferHandler = channel.getBufHandler();
this.readCompletionHandler = new CompletionHandler<Integer, SocketWrapperBase<Nio2Channel>>() {
@Override
public void completed(Integer nBytes, SocketWrapperBase<Nio2Channel> attachment) {
boolean notify = false;
if (log.isDebugEnabled()) {
log.debug("Socket: [" + attachment + "], Interest: [" + readInterest + "]");
}
synchronized (readCompletionHandler) {
if (nBytes.intValue() < 0) {
failed(new EOFException(), attachment);
} else {
if (readInterest && !Nio2Endpoint.isInline()) {
readInterest = false;
notify = true;
} else {
// Release here since there will be no
// notify/dispatch to do the release.
readPending.release();
}
}
}
if (notify) {
getEndpoint().processSocket(attachment, SocketEvent.OPEN_READ, false);
}
}
@Override
public void failed(Throwable exc, SocketWrapperBase<Nio2Channel> attachment) {
IOException ioe;
if (exc instanceof IOException) {
ioe = (IOException) exc;
} else {
ioe = new IOException(exc);
}
setError(ioe);
if (exc instanceof AsynchronousCloseException) {
// Release here since there will be no
// notify/dispatch to do the release.
readPending.release();
// If already closed, don't call onError and close again
return;
}
getEndpoint().processSocket(attachment, SocketEvent.ERROR, true);
}
};
this.writeCompletionHandler = new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer nBytes, ByteBuffer attachment) {
writeNotify = false;
synchronized (writeCompletionHandler) {
if (nBytes.intValue() < 0) {
failed(new EOFException(sm.getString("iob.failedwrite")), attachment);
} else if (!nonBlockingWriteBuffer.isEmpty()) {
nestedWriteCompletionCount.get().incrementAndGet();
// Continue writing data using a gathering write
ByteBuffer[] array = nonBlockingWriteBuffer.toArray(attachment);
getSocket().write(array, 0, array.length,
toNio2Timeout(getWriteTimeout()), TimeUnit.MILLISECONDS,
array, gatheringWriteCompletionHandler);
nestedWriteCompletionCount.get().decrementAndGet();
} else if (attachment.hasRemaining()) {
// Regular write
nestedWriteCompletionCount.get().incrementAndGet();
getSocket().write(attachment, toNio2Timeout(getWriteTimeout()),
TimeUnit.MILLISECONDS, attachment, writeCompletionHandler);
nestedWriteCompletionCount.get().decrementAndGet();
} else {
// All data has been written
if (writeInterest) {
writeInterest = false;
writeNotify = true;
}
writePending.release();
}
}
if (writeNotify && nestedWriteCompletionCount.get().get() == 0) {
endpoint.processSocket(Nio2SocketWrapper.this, SocketEvent.OPEN_WRITE, Nio2Endpoint.isInline());
}
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
IOException ioe;
if (exc instanceof IOException) {
ioe = (IOException) exc;
} else {
ioe = new IOException(exc);
}
setError(ioe);
writePending.release();
endpoint.processSocket(Nio2SocketWrapper.this, SocketEvent.ERROR, true);
}
};
gatheringWriteCompletionHandler = new CompletionHandler<Long, ByteBuffer[]>() {
@Override
public void completed(Long nBytes, ByteBuffer[] attachment) {
writeNotify = false;
synchronized (writeCompletionHandler) {
if (nBytes.longValue() < 0) {
failed(new EOFException(sm.getString("iob.failedwrite")), attachment);
} else if (!nonBlockingWriteBuffer.isEmpty() || arrayHasData(attachment)) {
// Continue writing data using a gathering write
nestedWriteCompletionCount.get().incrementAndGet();
ByteBuffer[] array = nonBlockingWriteBuffer.toArray(attachment);
getSocket().write(array, 0, array.length,
toNio2Timeout(getWriteTimeout()), TimeUnit.MILLISECONDS,
array, gatheringWriteCompletionHandler);
nestedWriteCompletionCount.get().decrementAndGet();
} else {
// All data has been written
if (writeInterest) {
writeInterest = false;
writeNotify = true;
}
writePending.release();
}
}
if (writeNotify && nestedWriteCompletionCount.get().get() == 0) {
endpoint.processSocket(Nio2SocketWrapper.this, SocketEvent.OPEN_WRITE, Nio2Endpoint.isInline());
}
}
@Override
public void failed(Throwable exc, ByteBuffer[] attachment) {
IOException ioe;
if (exc instanceof IOException) {
ioe = (IOException) exc;
} else {
ioe = new IOException(exc);
}
setError(ioe);
writePending.release();
endpoint.processSocket(Nio2SocketWrapper.this, SocketEvent.ERROR, true);
}
};
}
private static boolean arrayHasData(ByteBuffer[] byteBuffers) {
for (ByteBuffer byteBuffer : byteBuffers) {
if (byteBuffer.hasRemaining()) {
return true;
}
}
return false;
}
public void setSendfileData(SendfileData sf) { this.sendfileData = sf; }
public SendfileData getSendfileData() { return this.sendfileData; }
@Override
public boolean isReadyForRead() throws IOException {
synchronized (readCompletionHandler) {
if (!readPending.tryAcquire()) {
readInterest = true;
return false;
}
if (!socketBufferHandler.isReadBufferEmpty()) {
readPending.release();
return true;
}
int nRead = fillReadBuffer(false);
boolean isReady = nRead > 0;
if (!isReady) {
readInterest = true;
}
return isReady;
}
}
@Override
public int read(boolean block, byte[] b, int off, int len) throws IOException {
checkError();
if (log.isDebugEnabled()) {
log.debug("Socket: [" + this + "], block: [" + block + "], length: [" + len + "]");
}
if (socketBufferHandler == null) {
throw new IOException(sm.getString("socket.closed"));
}
if (block) {
try {
readPending.acquire();
} catch (InterruptedException e) {
throw new IOException(e);
}
} else {
if (!readPending.tryAcquire()) {
if (log.isDebugEnabled()) {
log.debug("Socket: [" + this + "], Read in progress. Returning [0]");
}
return 0;
}
}
int nRead = populateReadBuffer(b, off, len);
if (nRead > 0) {
// This may be sufficient to complete the request and we
// don't want to trigger another read since if there is no
// more data to read and this request takes a while to
// process the read will timeout triggering an error.
readPending.release();
return nRead;
}
synchronized (readCompletionHandler) {
// Fill the read buffer as best we can.
nRead = fillReadBuffer(block);
// Fill as much of the remaining byte array as possible with the
// data that was just read
if (nRead > 0) {
socketBufferHandler.configureReadBufferForRead();
nRead = Math.min(nRead, len);
socketBufferHandler.getReadBuffer().get(b, off, nRead);
} else if (nRead == 0 && !block) {
readInterest = true;
}
if (log.isDebugEnabled()) {
log.debug("Socket: [" + this + "], Read: [" + nRead + "]");
}
return nRead;
}
}
@Override
public int read(boolean block, ByteBuffer to) throws IOException {
checkError();
if (socketBufferHandler == null) {
throw new IOException(sm.getString("socket.closed"));
}
if (block) {
try {
readPending.acquire();
} catch (InterruptedException e) {
throw new IOException(e);
}
} else {
if (!readPending.tryAcquire()) {
if (log.isDebugEnabled()) {
log.debug("Socket: [" + this + "], Read in progress. Returning [0]");
}
return 0;
}
}
int nRead = populateReadBuffer(to);
if (nRead > 0) {
// This may be sufficient to complete the request and we
// don't want to trigger another read since if there is no
// more data to read and this request takes a while to
// process the read will timeout triggering an error.
readPending.release();
return nRead;
}
synchronized (readCompletionHandler) {
// The socket read buffer capacity is socket.appReadBufSize
int limit = socketBufferHandler.getReadBuffer().capacity();
if (block && to.remaining() >= limit) {
to.limit(to.position() + limit);
nRead = fillReadBuffer(block, to);
if (log.isDebugEnabled()) {
log.debug("Socket: [" + this + "], Read direct from socket: [" + nRead + "]");
}
} else {
// Fill the read buffer as best we can.
nRead = fillReadBuffer(block);
if (log.isDebugEnabled()) {
log.debug("Socket: [" + this + "], Read into buffer: [" + nRead + "]");
}
// Fill as much of the remaining byte array as possible with the
// data that was just read
if (nRead > 0) {
nRead = populateReadBuffer(to);
} else if (nRead == 0 && !block) {
readInterest = true;
}
}
return nRead;
}
}
@Override
public void close() throws IOException {
getSocket().close();
}
@Override
public boolean isClosed() {
return closed || !getSocket().isOpen();
}
@Override
public boolean isWritePending() {
synchronized (writeCompletionHandler) {
return writePending.availablePermits() == 0;
}
}
@Override
public boolean hasAsyncIO() {
return true;
}
/**
* Internal state tracker for scatter/gather operations.
*/
private static class OperationState<A> {
private final boolean read;
private final ByteBuffer[] buffers;
private final int offset;
private final int length;
private final A attachment;
private final long timeout;
private final TimeUnit unit;
private final BlockingMode block;
private final CompletionCheck check;
private final CompletionHandler<Long, ? super A> handler;
private final Semaphore semaphore;
private OperationState(boolean read, ByteBuffer[] buffers, int offset, int length,
BlockingMode block, long timeout, TimeUnit unit, A attachment,
CompletionCheck check, CompletionHandler<Long, ? super A> handler,
Semaphore semaphore) {
this.read = read;
this.buffers = buffers;
this.offset = offset;
this.length = length;
this.block = block;
this.timeout = timeout;
this.unit = unit;
this.attachment = attachment;
this.check = check;
this.handler = handler;
this.semaphore = semaphore;
}
private volatile long nBytes = 0;
private volatile CompletionState state = CompletionState.PENDING;
}
@Override
public <A> CompletionState read(ByteBuffer[] dsts, int offset, int length,
BlockingMode block, long timeout, TimeUnit unit, A attachment,
CompletionCheck check, CompletionHandler<Long, ? super A> handler) {
IOException ioe = getError();
if (ioe != null) {
handler.failed(ioe, attachment);
return CompletionState.ERROR;
}
if (timeout == -1) {
timeout = toNio2Timeout(getReadTimeout());
}
if (block != BlockingMode.NON_BLOCK) {
try {
if (!readPending.tryAcquire(timeout, unit)) {
handler.failed(new SocketTimeoutException(), attachment);
return CompletionState.ERROR;
}
} catch (InterruptedException e) {
handler.failed(e, attachment);
return CompletionState.ERROR;
}
} else {
if (!readPending.tryAcquire()) {
return CompletionState.NOT_DONE;
}
}
OperationState<A> state = new OperationState<>(true, dsts, offset, length, block,
timeout, unit, attachment, check, handler, readPending);
VectoredIOCompletionHandler<A> completion = new VectoredIOCompletionHandler<>();
Nio2Endpoint.startInline();
long nBytes = 0;
if (!socketBufferHandler.isReadBufferEmpty()) {
// There is still data inside the main read buffer, use it to fill out the destination buffers
synchronized (readCompletionHandler) {
// Note: It is not necessary to put this code in the completion handler
socketBufferHandler.configureReadBufferForRead();
for (int i = 0; i < length && !socketBufferHandler.isReadBufferEmpty(); i++) {
nBytes += transfer(socketBufferHandler.getReadBuffer(), dsts[offset + i]);
}
}
if (nBytes > 0) {
completion.completed(Long.valueOf(nBytes), state);
}
}
if (nBytes == 0) {
getSocket().read(dsts, offset, length, timeout, unit, state, completion);
}
Nio2Endpoint.endInline();
if (block == BlockingMode.BLOCK) {
synchronized (state) {
if (state.state == CompletionState.PENDING) {
try {
state.wait(unit.toMillis(timeout));
if (state.state == CompletionState.PENDING) {
return CompletionState.ERROR;
}
} catch (InterruptedException e) {
handler.failed(new SocketTimeoutException(), attachment);
return CompletionState.ERROR;
}
}
}
}
return state.state;
}
@Override
public <A> CompletionState write(ByteBuffer[] srcs, int offset, int length,
BlockingMode block, long timeout, TimeUnit unit, A attachment,
CompletionCheck check, CompletionHandler<Long, ? super A> handler) {
IOException ioe = getError();
if (ioe != null) {
handler.failed(ioe, attachment);
return CompletionState.ERROR;
}
if (timeout == -1) {
timeout = toNio2Timeout(getWriteTimeout());
}
if (block != BlockingMode.NON_BLOCK) {
try {
if (!writePending.tryAcquire(timeout, unit)) {
handler.failed(new SocketTimeoutException(), attachment);
return CompletionState.ERROR;
}
} catch (InterruptedException e) {
handler.failed(e, attachment);
return CompletionState.ERROR;
}
} else {
if (!writePending.tryAcquire()) {
return CompletionState.NOT_DONE;
}
}
if (!socketBufferHandler.isWriteBufferEmpty()) {
// First flush the main buffer as needed
try {
doWrite(true);
} catch (IOException e) {
handler.failed(e, attachment);
return CompletionState.ERROR;
}
}
OperationState<A> state = new OperationState<>(false, srcs, offset, length, block,
timeout, unit, attachment, check, handler, writePending);
VectoredIOCompletionHandler<A> completion = new VectoredIOCompletionHandler<>();
Nio2Endpoint.startInline();
// It should be less necessary to check the buffer state as it is easy to flush before
getSocket().write(srcs, offset, length, timeout, unit, state, completion);
Nio2Endpoint.endInline();
if (block == BlockingMode.BLOCK) {
synchronized (state) {
if (state.state == CompletionState.PENDING) {
try {
state.wait(unit.toMillis(timeout));
if (state.state == CompletionState.PENDING) {
return CompletionState.ERROR;
}
} catch (InterruptedException e) {
handler.failed(new SocketTimeoutException(), attachment);