-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
NioEndpoint.java
1858 lines (1537 loc) · 60.7 KB
/
NioEndpoint.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
/*
* Copyright 2005-2006 The Apache Software Foundation
*
* 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 org.apache.tomcat.util.net;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import java.util.concurrent.Executor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.jni.Error;
import org.apache.tomcat.jni.Library;
import org.apache.tomcat.jni.Poll;
import org.apache.tomcat.jni.SSL;
import org.apache.tomcat.jni.Status;
import org.apache.tomcat.util.res.StringManager;
/**
* NIO tailored thread pool, providing the following services:
* <ul>
* <li>Socket acceptor thread</li>
* <li>Socket poller thread</li>
* <li>Sendfile thread</li>
* <li>Worker threads pool</li>
* </ul>
*
* When switching to Java 5, there's an opportunity to use the virtual
* machine's thread pool.
*
* @author Mladen Turk
* @author Remy Maucherat
* @author Filip Hanik
*/
public class NioEndpoint {
// -------------------------------------------------------------- Constants
protected static Log log = LogFactory.getLog(NioEndpoint.class);
protected static StringManager sm =
StringManager.getManager("org.apache.tomcat.util.net.res");
/**
* The Request attribute key for the cipher suite.
*/
public static final String CIPHER_SUITE_KEY = "javax.servlet.request.cipher_suite";
/**
* The Request attribute key for the key size.
*/
public static final String KEY_SIZE_KEY = "javax.servlet.request.key_size";
/**
* The Request attribute key for the client certificate chain.
*/
public static final String CERTIFICATE_KEY = "javax.servlet.request.X509Certificate";
/**
* The Request attribute key for the session id.
* This one is a Tomcat extension to the Servlet spec.
*/
public static final String SESSION_ID_KEY = "javax.servlet.request.ssl_session";
// ----------------------------------------------------------------- Fields
/**
* Available workers.
*/
protected WorkerStack workers = null;
/**
* Running state of the endpoint.
*/
protected volatile boolean running = false;
/**
* Will be set to true whenever the endpoint is paused.
*/
protected volatile boolean paused = false;
/**
* Track the initialization state of the endpoint.
*/
protected boolean initialized = false;
/**
* Current worker threads busy count.
*/
protected int curThreadsBusy = 0;
/**
* Current worker threads count.
*/
protected int curThreads = 0;
/**
* Sequence number used to generate thread names.
*/
protected int sequence = 0;
/**
* Root APR memory pool.
*/
protected long rootPool = 0;
/**
* Server socket "pointer".
*/
protected ServerSocketChannel serverSock = null;
/**
* APR memory pool for the server socket.
*/
protected long serverSockPool = 0;
/**
* SSL context.
*/
protected long sslContext = 0;
// ------------------------------------------------------------- Properties
/**
* External Executor based thread pool.
*/
protected Executor executor = null;
public void setExecutor(Executor executor) { this.executor = executor; }
public Executor getExecutor() { return executor; }
/**
* Maximum amount of worker threads.
*/
protected int maxThreads = 40;
public void setMaxThreads(int maxThreads) { this.maxThreads = maxThreads; }
public int getMaxThreads() { return maxThreads; }
/**
* Priority of the acceptor and poller threads.
*/
protected int threadPriority = Thread.NORM_PRIORITY;
public void setThreadPriority(int threadPriority) { this.threadPriority = threadPriority; }
public int getThreadPriority() { return threadPriority; }
/**
* Size of the socket poller.
*/
protected int pollerSize = 8 * 1024;
public void setPollerSize(int pollerSize) { this.pollerSize = pollerSize; }
public int getPollerSize() { return pollerSize; }
/**
* Size of the sendfile (= concurrent files which can be served).
*/
protected int sendfileSize = 1 * 1024;
public void setSendfileSize(int sendfileSize) { this.sendfileSize = sendfileSize; }
public int getSendfileSize() { return sendfileSize; }
/**
* Server socket port.
*/
protected int port;
public int getPort() { return port; }
public void setPort(int port ) { this.port=port; }
/**
* Address for the server socket.
*/
protected InetAddress address;
public InetAddress getAddress() { return address; }
public void setAddress(InetAddress address) { this.address = address; }
/**
* Handling of accepted sockets.
*/
protected Handler handler = null;
public void setHandler(Handler handler ) { this.handler = handler; }
public Handler getHandler() { return handler; }
/**
* Allows the server developer to specify the backlog that
* should be used for server sockets. By default, this value
* is 100.
*/
protected int backlog = 100;
public void setBacklog(int backlog) { if (backlog > 0) this.backlog = backlog; }
public int getBacklog() { return backlog; }
/**
* Socket TCP no delay.
*/
protected boolean tcpNoDelay = false;
public boolean getTcpNoDelay() { return tcpNoDelay; }
public void setTcpNoDelay(boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; }
/**
* Socket linger.
*/
protected int soLinger = 100;
public int getSoLinger() { return soLinger; }
public void setSoLinger(int soLinger) { this.soLinger = soLinger; }
/**
* Socket timeout.
*/
protected int soTimeout = -1;
public int getSoTimeout() { return soTimeout; }
public void setSoTimeout(int soTimeout) { this.soTimeout = soTimeout; }
/**
* Timeout on first request read before going to the poller, in ms.
*/
protected int firstReadTimeout = 60000;
public int getFirstReadTimeout() { return firstReadTimeout; }
public void setFirstReadTimeout(int firstReadTimeout) { this.firstReadTimeout = firstReadTimeout; }
/**
* Poll interval, in microseconds. The smaller the value, the more CPU the poller
* will use, but the more responsive to activity it will be.
*/
protected int pollTime = 2000;
public int getPollTime() { return pollTime; }
public void setPollTime(int pollTime) { if (pollTime > 0) { this.pollTime = pollTime; } }
/**
* The default is true - the created threads will be
* in daemon mode. If set to false, the control thread
* will not be daemon - and will keep the process alive.
*/
protected boolean daemon = true;
public void setDaemon(boolean b) { daemon = b; }
public boolean getDaemon() { return daemon; }
/**
* Name of the thread pool, which will be used for naming child threads.
*/
protected String name = "TP";
public void setName(String name) { this.name = name; }
public String getName() { return name; }
/**
* Use endfile for sending static files.
*/
protected boolean useSendfile = Library.APR_HAS_SENDFILE;
public void setUseSendfile(boolean useSendfile) { this.useSendfile = useSendfile; }
public boolean getUseSendfile() { return useSendfile; }
/**
* Allow comet request handling.
*/
protected boolean useComet = true;
public void setUseComet(boolean useComet) { this.useComet = useComet; }
public boolean getUseComet() { return useComet; }
/**
* Acceptor thread count.
*/
protected int acceptorThreadCount = 0;
public void setAcceptorThreadCount(int acceptorThreadCount) { this.acceptorThreadCount = acceptorThreadCount; }
public int getAcceptorThreadCount() { return acceptorThreadCount; }
/**
* Sendfile thread count.
*/
protected int sendfileThreadCount = 0;
public void setSendfileThreadCount(int sendfileThreadCount) { this.sendfileThreadCount = sendfileThreadCount; }
public int getSendfileThreadCount() { return sendfileThreadCount; }
/**
* Poller thread count.
*/
protected int pollerThreadCount = 0;
public void setPollerThreadCount(int pollerThreadCount) { this.pollerThreadCount = pollerThreadCount; }
public int getPollerThreadCount() { return pollerThreadCount; }
protected long selectorTimeout = 5000;
public void setSelectorTimeout(long timeout){ this.selectorTimeout = timeout;}
public long getSelectorTimeout(){ return this.selectorTimeout; }
/**
* The socket poller.
*/
protected Poller[] pollers = null;
protected int pollerRoundRobin = 0;
public Poller getPoller() {
pollerRoundRobin = (pollerRoundRobin + 1) % pollers.length;
Poller poller = pollers[pollerRoundRobin];
poller.comet = false;
return poller;
}
/**
* The socket poller used for Comet support.
*/
public Poller getCometPoller() {
Poller poller = getPoller();
poller.comet = true;
return poller;
}
/**
* The static file sender.
*/
protected Sendfile[] sendfiles = null;
protected int sendfileRoundRobin = 0;
public Sendfile getSendfile() {
sendfileRoundRobin = (sendfileRoundRobin + 1) % sendfiles.length;
return sendfiles[sendfileRoundRobin];
}
/**
* Dummy maxSpareThreads property.
*/
public int getMaxSpareThreads() { return 0; }
/**
* Dummy minSpareThreads property.
*/
public int getMinSpareThreads() { return 0; }
/**
* SSL engine.
*/
protected String SSLEngine = "off";
public String getSSLEngine() { return SSLEngine; }
public void setSSLEngine(String SSLEngine) { this.SSLEngine = SSLEngine; }
/**
* SSL protocols.
*/
protected String SSLProtocol = "all";
public String getSSLProtocol() { return SSLProtocol; }
public void setSSLProtocol(String SSLProtocol) { this.SSLProtocol = SSLProtocol; }
/**
* SSL password (if a cert is encrypted, and no password has been provided, a callback
* will ask for a password).
*/
protected String SSLPassword = null;
public String getSSLPassword() { return SSLPassword; }
public void setSSLPassword(String SSLPassword) { this.SSLPassword = SSLPassword; }
/**
* SSL cipher suite.
*/
protected String SSLCipherSuite = "ALL";
public String getSSLCipherSuite() { return SSLCipherSuite; }
public void setSSLCipherSuite(String SSLCipherSuite) { this.SSLCipherSuite = SSLCipherSuite; }
/**
* SSL certificate file.
*/
protected String SSLCertificateFile = null;
public String getSSLCertificateFile() { return SSLCertificateFile; }
public void setSSLCertificateFile(String SSLCertificateFile) { this.SSLCertificateFile = SSLCertificateFile; }
/**
* SSL certificate key file.
*/
protected String SSLCertificateKeyFile = null;
public String getSSLCertificateKeyFile() { return SSLCertificateKeyFile; }
public void setSSLCertificateKeyFile(String SSLCertificateKeyFile) { this.SSLCertificateKeyFile = SSLCertificateKeyFile; }
/**
* SSL certificate chain file.
*/
protected String SSLCertificateChainFile = null;
public String getSSLCertificateChainFile() { return SSLCertificateChainFile; }
public void setSSLCertificateChainFile(String SSLCertificateChainFile) { this.SSLCertificateChainFile = SSLCertificateChainFile; }
/**
* SSL CA certificate path.
*/
protected String SSLCACertificatePath = null;
public String getSSLCACertificatePath() { return SSLCACertificatePath; }
public void setSSLCACertificatePath(String SSLCACertificatePath) { this.SSLCACertificatePath = SSLCACertificatePath; }
/**
* SSL CA certificate file.
*/
protected String SSLCACertificateFile = null;
public String getSSLCACertificateFile() { return SSLCACertificateFile; }
public void setSSLCACertificateFile(String SSLCACertificateFile) { this.SSLCACertificateFile = SSLCACertificateFile; }
/**
* SSL CA revocation path.
*/
protected String SSLCARevocationPath = null;
public String getSSLCARevocationPath() { return SSLCARevocationPath; }
public void setSSLCARevocationPath(String SSLCARevocationPath) { this.SSLCARevocationPath = SSLCARevocationPath; }
/**
* SSL CA revocation file.
*/
protected String SSLCARevocationFile = null;
public String getSSLCARevocationFile() { return SSLCARevocationFile; }
public void setSSLCARevocationFile(String SSLCARevocationFile) { this.SSLCARevocationFile = SSLCARevocationFile; }
/**
* SSL verify client.
*/
protected String SSLVerifyClient = "none";
public String getSSLVerifyClient() { return SSLVerifyClient; }
public void setSSLVerifyClient(String SSLVerifyClient) { this.SSLVerifyClient = SSLVerifyClient; }
/**
* SSL verify depth.
*/
protected int SSLVerifyDepth = 10;
public int getSSLVerifyDepth() { return SSLVerifyDepth; }
public void setSSLVerifyDepth(int SSLVerifyDepth) { this.SSLVerifyDepth = SSLVerifyDepth; }
// --------------------------------------------------------- Public Methods
/**
* Number of keepalive sockets.
*/
public int getKeepAliveCount() {
if (pollers == null) {
return 0;
} else {
int keepAliveCount = 0;
for (int i = 0; i < pollers.length; i++) {
keepAliveCount += pollers[i].getKeepAliveCount();
}
return keepAliveCount;
}
}
/**
* Number of sendfile sockets.
*/
public int getSendfileCount() {
if (sendfiles == null) {
return 0;
} else {
int sendfileCount = 0;
for (int i = 0; i < sendfiles.length; i++) {
sendfileCount += sendfiles[i].getSendfileCount();
}
return sendfileCount;
}
}
/**
* Return the amount of threads that are managed by the pool.
*
* @return the amount of threads that are managed by the pool
*/
public int getCurrentThreadCount() {
return curThreads;
}
/**
* Return the amount of threads currently busy.
*
* @return the amount of threads currently busy
*/
public int getCurrentThreadsBusy() {
return curThreadsBusy;
}
/**
* Return the state of the endpoint.
*
* @return true if the endpoint is running, false otherwise
*/
public boolean isRunning() {
return running;
}
/**
* Return the state of the endpoint.
*
* @return true if the endpoint is paused, false otherwise
*/
public boolean isPaused() {
return paused;
}
// ----------------------------------------------- Public Lifecycle Methods
/**
* Initialize the endpoint.
*/
public void init()
throws Exception {
if (initialized)
return;
serverSock = ServerSocketChannel.open();
InetSocketAddress addr = (address!=null?new InetSocketAddress(address,port):new InetSocketAddress(port));
serverSock.socket().bind(addr,100); //todo, set backlog value
serverSock.configureBlocking(true); //mimic APR behavior
// Sendfile usage on systems which don't support it cause major problems
if (useSendfile) {
log.warn(sm.getString("endpoint.sendfile.nosupport"));
useSendfile = false;
}
// Initialize thread count defaults for acceptor, poller and sendfile
if (acceptorThreadCount == 0) {
// FIXME: Doesn't seem to work that well with multiple accept threads
acceptorThreadCount = 1;
}
if (pollerThreadCount != 1) {
// limit to one poller, no need for others
pollerThreadCount = 1;
}
if (sendfileThreadCount != 0) {
sendfileThreadCount = 0;
}
// Initialize SSL if needed
if (!"off".equalsIgnoreCase(SSLEngine)) {
// Initialize SSL
// FIXME: one per VM call ?
if ("on".equalsIgnoreCase(SSLEngine)) {
SSL.initialize(null);
} else {
SSL.initialize(SSLEngine);
}
// SSL protocol
int value = SSL.SSL_PROTOCOL_ALL;
if ("SSLv2".equalsIgnoreCase(SSLProtocol)) {
value = SSL.SSL_PROTOCOL_SSLV2;
} else if ("SSLv3".equalsIgnoreCase(SSLProtocol)) {
value = SSL.SSL_PROTOCOL_SSLV3;
} else if ("TLSv1".equalsIgnoreCase(SSLProtocol)) {
value = SSL.SSL_PROTOCOL_TLSV1;
} else if ("SSLv2+SSLv3".equalsIgnoreCase(SSLProtocol)) {
value = SSL.SSL_PROTOCOL_SSLV2 | SSL.SSL_PROTOCOL_SSLV3;
}
// // Create SSL Context
// sslContext = SSLContext.make(rootPool, value, SSL.SSL_MODE_SERVER);
// // List the ciphers that the client is permitted to negotiate
// SSLContext.setCipherSuite(sslContext, SSLCipherSuite);
// // Load Server key and certificate
// SSLContext.setCertificate(sslContext, SSLCertificateFile, SSLCertificateKeyFile, SSLPassword, SSL.SSL_AIDX_RSA);
// // Set certificate chain file
// SSLContext.setCertificateChainFile(sslContext, SSLCertificateChainFile, false);
// // Support Client Certificates
// SSLContext.setCACertificate(sslContext, SSLCACertificateFile, SSLCACertificatePath);
// // Set revocation
// SSLContext.setCARevocation(sslContext, SSLCARevocationFile, SSLCARevocationPath);
// // Client certificate verification
// value = SSL.SSL_CVERIFY_NONE;
// if ("optional".equalsIgnoreCase(SSLVerifyClient)) {
// value = SSL.SSL_CVERIFY_OPTIONAL;
// } else if ("require".equalsIgnoreCase(SSLVerifyClient)) {
// value = SSL.SSL_CVERIFY_REQUIRE;
// } else if ("optionalNoCA".equalsIgnoreCase(SSLVerifyClient)) {
// value = SSL.SSL_CVERIFY_OPTIONAL_NO_CA;
// }
// SSLContext.setVerify(sslContext, value, SSLVerifyDepth);
// For now, sendfile is not supported with SSL
useSendfile = false;
}
initialized = true;
}
/**
* Start the APR endpoint, creating acceptor, poller and sendfile threads.
*/
public void start()
throws Exception {
// Initialize socket if not done before
if (!initialized) {
init();
}
if (!running) {
running = true;
paused = false;
// Create worker collection
if (executor == null) {
workers = new WorkerStack(maxThreads);
}
// Start acceptor threads
for (int i = 0; i < acceptorThreadCount; i++) {
Thread acceptorThread = new Thread(new Acceptor(), getName() + "-Acceptor-" + i);
acceptorThread.setPriority(threadPriority);
acceptorThread.setDaemon(daemon);
acceptorThread.start();
}
// Start poller threads
pollers = new Poller[pollerThreadCount];
for (int i = 0; i < pollerThreadCount; i++) {
pollers[i] = new Poller(false);
pollers[i].init();
Thread pollerThread = new Thread(pollers[i], getName() + "-Poller-" + i);
pollerThread.setPriority(threadPriority);
pollerThread.setDaemon(true);
pollerThread.start();
}
// Start sendfile threads
if (useSendfile) {
sendfiles = new Sendfile[sendfileThreadCount];
for (int i = 0; i < sendfileThreadCount; i++) {
sendfiles[i] = new Sendfile();
sendfiles[i].init();
Thread sendfileThread = new Thread(sendfiles[i], getName() + "-Sendfile-" + i);
sendfileThread.setPriority(threadPriority);
sendfileThread.setDaemon(true);
sendfileThread.start();
}
}
}
}
/**
* Pause the endpoint, which will make it stop accepting new sockets.
*/
public void pause() {
if (running && !paused) {
paused = true;
unlockAccept();
}
}
/**
* Resume the endpoint, which will make it start accepting new sockets
* again.
*/
public void resume() {
if (running) {
paused = false;
}
}
/**
* Stop the endpoint. This will cause all processing threads to stop.
*/
public void stop() {
if (running) {
running = false;
unlockAccept();
for (int i = 0; i < pollers.length; i++) {
pollers[i].destroy();
}
pollers = null;
if (useSendfile) {
for (int i = 0; i < sendfiles.length; i++) {
sendfiles[i].destroy();
}
sendfiles = null;
}
}
}
/**
* Deallocate APR memory pools, and close server socket.
*/
public void destroy() throws Exception {
if (running) {
stop();
}
// Close server socket
serverSock.socket().close();
serverSock.close();
serverSock = null;
sslContext = 0;
initialized = false;
}
// ------------------------------------------------------ Protected Methods
/**
* Get a sequence number used for thread naming.
*/
protected int getSequence() {
return sequence++;
}
/**
* Unlock the server socket accept using a bugus connection.
*/
protected void unlockAccept() {
java.net.Socket s = null;
try {
// Need to create a connection to unlock the accept();
if (address == null) {
s = new java.net.Socket("127.0.0.1", port);
} else {
s = new java.net.Socket(address, port);
// setting soLinger to a small value will help shutdown the
// connection quicker
s.setSoLinger(true, 0);
}
} catch(Exception e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("endpoint.debug.unlock", "" + port), e);
}
} finally {
if (s != null) {
try {
s.close();
} catch (Exception e) {
// Ignore
}
}
}
}
/**
* Process the specified connection.
*/
protected boolean setSocketOptions(SocketChannel socket) {
// Process the connection
int step = 1;
try {
//disable blocking, APR style, we are gonna be polling it
socket.configureBlocking(false);
// 1: Set socket options: timeout, linger, etc
if (soLinger >= 0)
socket.socket().setSoLinger(true,soLinger);
if (tcpNoDelay)
socket.socket().setTcpNoDelay(true);
if (soTimeout > 0)
socket.socket().setSoTimeout(soTimeout);
// 2: SSL handshake
step = 2;
if (sslContext != 0) {
// SSLSocket.attach(sslContext, socket);
// if (SSLSocket.handshake(socket) != 0) {
// if (log.isDebugEnabled()) {
// log.debug(sm.getString("endpoint.err.handshake") + ": " + SSL.getLastError());
// }
// return false;
// }
}
getPoller().register(socket);
} catch (Throwable t) {
if (log.isDebugEnabled()) {
if (step == 2) {
log.debug(sm.getString("endpoint.err.handshake"), t);
} else {
log.debug(sm.getString("endpoint.err.unexpected"), t);
}
}
// Tell to close the socket
return false;
}
return true;
}
/**
* Create (or allocate) and return an available processor for use in
* processing a specific HTTP request, if possible. If the maximum
* allowed processors have already been created and are in use, return
* <code>null</code> instead.
*/
protected Worker createWorkerThread() {
synchronized (workers) {
if (workers.size() > 0) {
curThreadsBusy++;
return (workers.pop());
}
if ((maxThreads > 0) && (curThreads < maxThreads)) {
curThreadsBusy++;
return (newWorkerThread());
} else {
if (maxThreads < 0) {
curThreadsBusy++;
return (newWorkerThread());
} else {
return (null);
}
}
}
}
/**
* Create and return a new processor suitable for processing HTTP
* requests and returning the corresponding responses.
*/
protected Worker newWorkerThread() {
Worker workerThread = new Worker();
workerThread.start();
return (workerThread);
}
/**
* Return a new worker thread, and block while to worker is available.
*/
protected Worker getWorkerThread() {
// Allocate a new worker thread
Worker workerThread = createWorkerThread();
while (workerThread == null) {
try {
synchronized (workers) {
workers.wait();
}
} catch (InterruptedException e) {
// Ignore
}
workerThread = createWorkerThread();
}
return workerThread;
}
/**
* Recycle the specified Processor so that it can be used again.
*
* @param workerThread The processor to be recycled
*/
protected void recycleWorkerThread(Worker workerThread) {
synchronized (workers) {
workers.push(workerThread);
curThreadsBusy--;
workers.notify();
}
}
/**
* Allocate a new poller of the specified size.
*/
protected long allocatePoller(int size, long pool, int timeout) {
try {
return Poll.create(size, pool, 0, timeout * 1000);
} catch (Error e) {
if (Status.APR_STATUS_IS_EINVAL(e.getError())) {
log.info(sm.getString("endpoint.poll.limitedpollsize", "" + size));
return 0;
} else {
log.error(sm.getString("endpoint.poll.initfail"), e);
return -1;
}
}
}
/**
* Process given socket.
*/
protected boolean processSocket(SocketChannel socket) {
try {
if (executor == null) {
getWorkerThread().assign(socket);
} else {
executor.execute(new SocketProcessor(socket));
}
} catch (Throwable t) {
// This means we got an OOM or similar creating a thread, or that
// the pool and its queue are full
log.error(sm.getString("endpoint.process.fail"), t);
return false;
}
return true;
}
/**
* Process given socket for an event.
*/
protected boolean processSocket(SocketChannel socket, boolean error) {
try {
if (executor == null) {
getWorkerThread().assign(socket, error);
} else {
executor.execute(new SocketEventProcessor(socket, error));
}
} catch (Throwable t) {
// This means we got an OOM or similar creating a thread, or that
// the pool and its queue are full
log.error(sm.getString("endpoint.process.fail"), t);
return false;
}
return true;
}
// --------------------------------------------------- Acceptor Inner Class
/**
* Server socket acceptor thread.
*/
protected class Acceptor implements Runnable {
/**
* The background thread that listens for incoming TCP/IP connections and
* hands them off to an appropriate processor.
*/