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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
|
/*
* 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.IOException;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.juli.logging.Log;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.collections.SynchronizedStack;
import org.apache.tomcat.util.modeler.Registry;
import org.apache.tomcat.util.net.Acceptor.AcceptorState;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.util.threads.LimitLatch;
import org.apache.tomcat.util.threads.ResizableExecutor;
import org.apache.tomcat.util.threads.TaskQueue;
import org.apache.tomcat.util.threads.TaskThreadFactory;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
/**
* @param <S> The type used by the socket wrapper associated with this endpoint.
* May be the same as U.
* @param <U> The type of the underlying socket used by this endpoint. May be
* the same as S.
*
* @author Mladen Turk
* @author Remy Maucherat
*/
public abstract class AbstractEndpoint<S,U> {
// -------------------------------------------------------------- Constants
protected static final StringManager sm = StringManager.getManager(AbstractEndpoint.class);
public static interface Handler<S> {
/**
* Different types of socket states to react upon.
*/
public enum SocketState {
// TODO Add a new state to the AsyncStateMachine and remove
// ASYNC_END (if possible)
OPEN, CLOSED, LONG, ASYNC_END, SENDFILE, UPGRADING, UPGRADED, ASYNC_IO, SUSPENDED
}
/**
* Process the provided socket with the given current status.
*
* @param socket The socket to process
* @param status The current socket status
*
* @return The state of the socket after processing
*/
public SocketState process(SocketWrapperBase<S> socket,
SocketEvent status);
/**
* Obtain the GlobalRequestProcessor associated with the handler.
*
* @return the GlobalRequestProcessor
*/
public Object getGlobal();
/**
* Obtain the currently open sockets.
*
* @return The sockets for which the handler is tracking a currently
* open connection
* @deprecated Unused, will be removed in Tomcat 10, replaced
* by AbstractEndpoint.getConnections
*/
@Deprecated
public Set<S> getOpenSockets();
/**
* Release any resources associated with the given SocketWrapper.
*
* @param socketWrapper The socketWrapper to release resources for
*/
public void release(SocketWrapperBase<S> socketWrapper);
/**
* Inform the handler that the endpoint has stopped accepting any new
* connections. Typically, the endpoint will be stopped shortly
* afterwards but it is possible that the endpoint will be resumed so
* the handler should not assume that a stop will follow.
*/
public void pause();
/**
* Recycle resources associated with the handler.
*/
public void recycle();
}
protected enum BindState {
UNBOUND(false, false),
BOUND_ON_INIT(true, true),
BOUND_ON_START(true, true),
SOCKET_CLOSED_ON_STOP(false, true);
private final boolean bound;
private final boolean wasBound;
private BindState(boolean bound, boolean wasBound) {
this.bound = bound;
this.wasBound = wasBound;
}
public boolean isBound() {
return bound;
}
public boolean wasBound() {
return wasBound;
}
}
public static long toTimeout(long timeout) {
// Many calls can't do infinite timeout so use Long.MAX_VALUE if timeout is <= 0
return (timeout > 0) ? timeout : Long.MAX_VALUE;
}
// ----------------------------------------------------------------- Fields
/**
* 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;
/**
* Are we using an internal executor
*/
protected volatile boolean internalExecutor = true;
/**
* counter for nr of connections handled by an endpoint
*/
private volatile LimitLatch connectionLimitLatch = null;
/**
* Socket properties
*/
protected final SocketProperties socketProperties = new SocketProperties();
public SocketProperties getSocketProperties() {
return socketProperties;
}
/**
* Thread used to accept new connections and pass them to worker threads.
*/
protected Acceptor<U> acceptor;
/**
* Cache for SocketProcessor objects
*/
protected SynchronizedStack<SocketProcessorBase<S>> processorCache;
private ObjectName oname = null;
/**
* Map holding all current connections keyed with the sockets.
*/
protected Map<U, SocketWrapperBase<S>> connections = new ConcurrentHashMap<>();
/**
* Get a set with the current open connections.
* @return A set with the open socket wrappers
*/
public Set<SocketWrapperBase<S>> getConnections() {
return new HashSet<>(connections.values());
}
// ----------------------------------------------------------------- Properties
private String defaultSSLHostConfigName = SSLHostConfig.DEFAULT_SSL_HOST_NAME;
/**
* @return The host name for the default SSL configuration for this endpoint
* - always in lower case.
*/
public String getDefaultSSLHostConfigName() {
return defaultSSLHostConfigName;
}
public void setDefaultSSLHostConfigName(String defaultSSLHostConfigName) {
this.defaultSSLHostConfigName = defaultSSLHostConfigName.toLowerCase(Locale.ENGLISH);
}
protected ConcurrentMap<String,SSLHostConfig> sslHostConfigs = new ConcurrentHashMap<>();
/**
* Add the given SSL Host configuration.
*
* @param sslHostConfig The configuration to add
*
* @throws IllegalArgumentException If the host name is not valid or if a
* configuration has already been provided
* for that host
*/
public void addSslHostConfig(SSLHostConfig sslHostConfig) throws IllegalArgumentException {
addSslHostConfig(sslHostConfig, false);
}
/**
* Add the given SSL Host configuration, optionally replacing the existing
* configuration for the given host.
*
* @param sslHostConfig The configuration to add
* @param replace If {@code true} replacement of an existing
* configuration is permitted, otherwise any such
* attempted replacement will trigger an exception
*
* @throws IllegalArgumentException If the host name is not valid or if a
* configuration has already been provided
* for that host and replacement is not
* allowed
*/
public void addSslHostConfig(SSLHostConfig sslHostConfig, boolean replace) throws IllegalArgumentException {
String key = sslHostConfig.getHostName();
if (key == null || key.length() == 0) {
throw new IllegalArgumentException(sm.getString("endpoint.noSslHostName"));
}
if (bindState != BindState.UNBOUND && bindState != BindState.SOCKET_CLOSED_ON_STOP &&
isSSLEnabled()) {
try {
createSSLContext(sslHostConfig);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
if (replace) {
SSLHostConfig previous = sslHostConfigs.put(key, sslHostConfig);
if (previous != null) {
unregisterJmx(sslHostConfig);
}
registerJmx(sslHostConfig);
// Do not release any SSLContexts associated with a replaced
// SSLHostConfig. They may still be in used by existing connections
// and releasing them would break the connection at best. Let GC
// handle the clean up.
} else {
SSLHostConfig duplicate = sslHostConfigs.putIfAbsent(key, sslHostConfig);
if (duplicate != null) {
releaseSSLContext(sslHostConfig);
throw new IllegalArgumentException(sm.getString("endpoint.duplicateSslHostName", key));
}
registerJmx(sslHostConfig);
}
}
/**
* Removes the SSL host configuration for the given host name, if such a
* configuration exists.
*
* @param hostName The host name associated with the SSL host configuration
* to remove
*
* @return The SSL host configuration that was removed, if any
*/
public SSLHostConfig removeSslHostConfig(String hostName) {
if (hostName == null) {
return null;
}
// Host names are case insensitive but stored/processed in lower case
// internally because they are used as keys in a ConcurrentMap where
// keys are compared in a case sensitive manner.
String hostNameLower = hostName.toLowerCase(Locale.ENGLISH);
if (hostNameLower.equals(getDefaultSSLHostConfigName())) {
throw new IllegalArgumentException(
sm.getString("endpoint.removeDefaultSslHostConfig", hostName));
}
SSLHostConfig sslHostConfig = sslHostConfigs.remove(hostNameLower);
unregisterJmx(sslHostConfig);
return sslHostConfig;
}
/**
* Re-read the configuration files for the SSL host and replace the existing
* SSL configuration with the updated settings. Note this replacement will
* happen even if the settings remain unchanged.
*
* @param hostName The SSL host for which the configuration should be
* reloaded. This must match a current SSL host
*/
public void reloadSslHostConfig(String hostName) {
// Host names are case insensitive but stored/processed in lower case
// internally because they are used as keys in a ConcurrentMap where
// keys are compared in a case sensitive manner.
// This method can be called via various paths so convert the supplied
// host name to lower case here to ensure the conversion occurs whatever
// the call path.
SSLHostConfig sslHostConfig = sslHostConfigs.get(hostName.toLowerCase(Locale.ENGLISH));
if (sslHostConfig == null) {
throw new IllegalArgumentException(
sm.getString("endpoint.unknownSslHostName", hostName));
}
addSslHostConfig(sslHostConfig, true);
}
/**
* Re-read the configuration files for all SSL hosts and replace the
* existing SSL configuration with the updated settings. Note this
* replacement will happen even if the settings remain unchanged.
*/
public void reloadSslHostConfigs() {
for (String hostName : sslHostConfigs.keySet()) {
reloadSslHostConfig(hostName);
}
}
public SSLHostConfig[] findSslHostConfigs() {
return sslHostConfigs.values().toArray(new SSLHostConfig[0]);
}
/**
* Create the SSLContext for the given SSLHostConfig.
*
* @param sslHostConfig The SSLHostConfig for which the SSLContext should be
* created
* @throws Exception If the SSLContext cannot be created for the given
* SSLHostConfig
*/
protected abstract void createSSLContext(SSLHostConfig sslHostConfig) throws Exception;
protected void destroySsl() throws Exception {
if (isSSLEnabled()) {
for (SSLHostConfig sslHostConfig : sslHostConfigs.values()) {
releaseSSLContext(sslHostConfig);
}
}
}
/**
* Release the SSLContext, if any, associated with the SSLHostConfig.
*
* @param sslHostConfig The SSLHostConfig for which the SSLContext should be
* released
*/
protected void releaseSSLContext(SSLHostConfig sslHostConfig) {
for (SSLHostConfigCertificate certificate : sslHostConfig.getCertificates(true)) {
if (certificate.getSslContext() != null) {
SSLContext sslContext = certificate.getSslContext();
if (sslContext != null) {
sslContext.destroy();
}
}
}
}
/**
* Look up the SSLHostConfig for the given host name. Lookup order is:
* <ol>
* <li>exact match</li>
* <li>wild card match</li>
* <li>default SSLHostConfig</li>
* </ol>
*
* @param sniHostName Host name - must be in lower case
*
* @return The SSLHostConfig for the given host name.
*/
protected SSLHostConfig getSSLHostConfig(String sniHostName) {
SSLHostConfig result = null;
if (sniHostName != null) {
// First choice - direct match
result = sslHostConfigs.get(sniHostName);
if (result != null) {
return result;
}
// Second choice, wildcard match
int indexOfDot = sniHostName.indexOf('.');
if (indexOfDot > -1) {
result = sslHostConfigs.get("*" + sniHostName.substring(indexOfDot));
}
}
// Fall-back. Use the default
if (result == null) {
result = sslHostConfigs.get(getDefaultSSLHostConfigName());
}
if (result == null) {
// Should never happen.
throw new IllegalStateException();
}
return result;
}
/**
* Has the user requested that send file be used where possible?
*/
private boolean useSendfile = true;
public boolean getUseSendfile() {
return useSendfile;
}
public void setUseSendfile(boolean useSendfile) {
this.useSendfile = useSendfile;
}
/**
* Time to wait for the internal executor (if used) to terminate when the
* endpoint is stopped in milliseconds. Defaults to 5000 (5 seconds).
*/
private long executorTerminationTimeoutMillis = 5000;
public long getExecutorTerminationTimeoutMillis() {
return executorTerminationTimeoutMillis;
}
public void setExecutorTerminationTimeoutMillis(
long executorTerminationTimeoutMillis) {
this.executorTerminationTimeoutMillis = executorTerminationTimeoutMillis;
}
/**
* Unused.
*
* @deprecated This attribute is hard-coded to {@code 1} and is no longer
* configurable. It will be removed in Tomcat 10.1.
*/
@Deprecated
protected int acceptorThreadCount = 1;
/**
* Unused.
*
* @param acceptorThreadCount Ignored
*
* @deprecated This attribute is hard-coded to {@code 1} and is no longer
* configurable. This setter will be removed in Tomcat 10.
*/
@Deprecated
public void setAcceptorThreadCount(int acceptorThreadCount) {
// NO-OP;
}
/**
* Unused.
*
* @return Always returns {@code 1}
*
* @deprecated This attribute is hard-coded to {@code 1} and is no longer
* configurable. This getter will be removed in Tomcat 10.
*/
@Deprecated
public int getAcceptorThreadCount() {
return 1;
}
/**
* Priority of the acceptor threads.
*/
protected int acceptorThreadPriority = Thread.NORM_PRIORITY;
public void setAcceptorThreadPriority(int acceptorThreadPriority) {
this.acceptorThreadPriority = acceptorThreadPriority;
}
public int getAcceptorThreadPriority() { return acceptorThreadPriority; }
private int maxConnections = 8*1024;
public void setMaxConnections(int maxCon) {
this.maxConnections = maxCon;
LimitLatch latch = this.connectionLimitLatch;
if (latch != null) {
// Update the latch that enforces this
if (maxCon == -1) {
releaseConnectionLatch();
} else {
latch.setLimit(maxCon);
}
} else if (maxCon > 0) {
initializeConnectionLatch();
}
}
public int getMaxConnections() { return this.maxConnections; }
/**
* Return the current count of connections handled by this endpoint, if the
* connections are counted (which happens when the maximum count of
* connections is limited), or <code>-1</code> if they are not. This
* property is added here so that this value can be inspected through JMX.
* It is visible on "ThreadPool" MBean.
*
* <p>The count is incremented by the Acceptor before it tries to accept a
* new connection. Until the limit is reached and thus the count cannot be
* incremented, this value is more by 1 (the count of acceptors) than the
* actual count of connections that are being served.
*
* @return The count
*/
public long getConnectionCount() {
LimitLatch latch = connectionLimitLatch;
if (latch != null) {
return latch.getCount();
}
return -1;
}
/**
* External Executor based thread pool.
*/
private Executor executor = null;
public void setExecutor(Executor executor) {
this.executor = executor;
this.internalExecutor = (executor == null);
}
public Executor getExecutor() { return executor; }
/**
* External Executor based thread pool for utility tasks.
*/
private ScheduledExecutorService utilityExecutor = null;
public void setUtilityExecutor(ScheduledExecutorService utilityExecutor) {
this.utilityExecutor = utilityExecutor;
}
public ScheduledExecutorService getUtilityExecutor() {
if (utilityExecutor == null) {
getLog().warn(sm.getString("endpoint.warn.noUtilityExecutor"));
utilityExecutor = new ScheduledThreadPoolExecutor(1);
}
return utilityExecutor;
}
/**
* Server socket port.
*/
private int port = -1;
public int getPort() { return port; }
public void setPort(int port ) { this.port=port; }
private int portOffset = 0;
public int getPortOffset() { return portOffset; }
public void setPortOffset(int portOffset ) {
if (portOffset < 0) {
throw new IllegalArgumentException(
sm.getString("endpoint.portOffset.invalid", Integer.valueOf(portOffset)));
}
this.portOffset = portOffset;
}
public int getPortWithOffset() {
// Zero is a special case and negative values are invalid
int port = getPort();
if (port > 0) {
return port + getPortOffset();
}
return port;
}
public final int getLocalPort() {
try {
InetSocketAddress localAddress = getLocalAddress();
if (localAddress == null) {
return -1;
}
return localAddress.getPort();
} catch (IOException ioe) {
return -1;
}
}
/**
* Address for the server socket.
*/
private InetAddress address;
public InetAddress getAddress() { return address; }
public void setAddress(InetAddress address) { this.address = address; }
/**
* Obtain the network address the server socket is bound to. This primarily
* exists to enable the correct address to be used when unlocking the server
* socket since it removes the guess-work involved if no address is
* specifically set.
*
* @return The network address that the server socket is listening on or
* null if the server socket is not currently bound.
*
* @throws IOException If there is a problem determining the currently bound
* socket
*/
protected abstract InetSocketAddress getLocalAddress() throws IOException;
/**
* Allows the server developer to specify the acceptCount (backlog) that
* should be used for server sockets. By default, this value
* is 100.
*/
private int acceptCount = 100;
public void setAcceptCount(int acceptCount) { if (acceptCount > 0) {
this.acceptCount = acceptCount;
} }
public int getAcceptCount() { return acceptCount; }
/**
* Controls when the Endpoint binds the port. <code>true</code>, the default
* binds the port on {@link #init()} and unbinds it on {@link #destroy()}.
* If set to <code>false</code> the port is bound on {@link #start()} and
* unbound on {@link #stop()}.
*/
private boolean bindOnInit = true;
public boolean getBindOnInit() { return bindOnInit; }
public void setBindOnInit(boolean b) { this.bindOnInit = b; }
private volatile BindState bindState = BindState.UNBOUND;
protected BindState getBindState() {
return bindState;
}
/**
* Keepalive timeout, if not set the soTimeout is used.
*/
private Integer keepAliveTimeout = null;
public int getKeepAliveTimeout() {
if (keepAliveTimeout == null) {
return getConnectionTimeout();
} else {
return keepAliveTimeout.intValue();
}
}
public void setKeepAliveTimeout(int keepAliveTimeout) {
this.keepAliveTimeout = Integer.valueOf(keepAliveTimeout);
}
/**
* Socket TCP no delay.
*
* @return The current TCP no delay setting for sockets created by this
* endpoint
*/
public boolean getTcpNoDelay() { return socketProperties.getTcpNoDelay();}
public void setTcpNoDelay(boolean tcpNoDelay) { socketProperties.setTcpNoDelay(tcpNoDelay); }
/**
* Socket linger.
*
* @return The current socket linger time for sockets created by this
* endpoint
*/
public int getConnectionLinger() { return socketProperties.getSoLingerTime(); }
public void setConnectionLinger(int connectionLinger) {
socketProperties.setSoLingerTime(connectionLinger);
socketProperties.setSoLingerOn(connectionLinger>=0);
}
/**
* Socket timeout.
*
* @return The current socket timeout for sockets created by this endpoint
*/
public int getConnectionTimeout() { return socketProperties.getSoTimeout(); }
public void setConnectionTimeout(int soTimeout) { socketProperties.setSoTimeout(soTimeout); }
/**
* SSL engine.
*/
private boolean SSLEnabled = false;
public boolean isSSLEnabled() { return SSLEnabled; }
public void setSSLEnabled(boolean SSLEnabled) { this.SSLEnabled = SSLEnabled; }
/**
* Identifies if the endpoint supports ALPN. Note that a return value of
* <code>true</code> implies that {@link #isSSLEnabled()} will also return
* <code>true</code>.
*
* @return <code>true</code> if the endpoint supports ALPN in its current
* configuration, otherwise <code>false</code>.
*/
public abstract boolean isAlpnSupported();
private int minSpareThreads = 10;
public void setMinSpareThreads(int minSpareThreads) {
this.minSpareThreads = minSpareThreads;
Executor executor = this.executor;
if (internalExecutor && executor instanceof ThreadPoolExecutor) {
// The internal executor should always be an instance of
// org.apache.tomcat.util.threads.ThreadPoolExecutor but it may be
// null if the endpoint is not running.
// This check also avoids various threading issues.
((ThreadPoolExecutor) executor).setCorePoolSize(minSpareThreads);
}
}
public int getMinSpareThreads() {
return Math.min(getMinSpareThreadsInternal(), getMaxThreads());
}
private int getMinSpareThreadsInternal() {
if (internalExecutor) {
return minSpareThreads;
} else {
return -1;
}
}
/**
* Maximum amount of worker threads.
*/
private int maxThreads = 200;
public void setMaxThreads(int maxThreads) {
this.maxThreads = maxThreads;
Executor executor = this.executor;
if (internalExecutor && executor instanceof ThreadPoolExecutor) {
// The internal executor should always be an instance of
// org.apache.tomcat.util.threads.ThreadPoolExecutor but it may be
// null if the endpoint is not running.
// This check also avoids various threading issues.
((ThreadPoolExecutor) executor).setMaximumPoolSize(maxThreads);
}
}
public int getMaxThreads() {
if (internalExecutor) {
return maxThreads;
} else {
return -1;
}
}
/**
* Priority of the worker threads.
*/
protected int threadPriority = Thread.NORM_PRIORITY;
public void setThreadPriority(int threadPriority) {
// Can't change this once the executor has started
this.threadPriority = threadPriority;
}
public int getThreadPriority() {
if (internalExecutor) {
return threadPriority;
} else {
return -1;
}
}
/**
* Max keep alive requests
*/
private int maxKeepAliveRequests=100; // as in Apache HTTPD server
public int getMaxKeepAliveRequests() {
// Disable keep-alive if the server socket is not bound
if (bindState.isBound()) {
return maxKeepAliveRequests;
} else {
return 1;
}
}
public void setMaxKeepAliveRequests(int maxKeepAliveRequests) {
this.maxKeepAliveRequests = maxKeepAliveRequests;
}
/**
* Name of the thread pool, which will be used for naming child threads.
*/
private String name = "TP";
public void setName(String name) { this.name = name; }
public String getName() { return name; }
/**
* Name of domain to use for JMX registration.
*/
private String domain;
public void setDomain(String domain) { this.domain = domain; }
public String getDomain() { return domain; }
/**
* 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.
*/
private boolean daemon = true;
public void setDaemon(boolean b) { daemon = b; }
public boolean getDaemon() { return daemon; }
/**
* Expose asynchronous IO capability.
*/
private boolean useAsyncIO = true;
public void setUseAsyncIO(boolean useAsyncIO) { this.useAsyncIO = useAsyncIO; }
public boolean getUseAsyncIO() { return useAsyncIO; }
protected abstract boolean getDeferAccept();
/**
* The default behavior is to identify connectors uniquely with address
* and port. However, certain connectors are not using that and need
* some other identifier, which then can be used as a replacement.
* @return the id
*/
public String getId() {
return null;
}
protected final List<String> negotiableProtocols = new ArrayList<>();
public void addNegotiatedProtocol(String negotiableProtocol) {
negotiableProtocols.add(negotiableProtocol);
}
public boolean hasNegotiableProtocols() {
return (negotiableProtocols.size() > 0);
}
/**
* Handling of accepted sockets.
*/
private Handler<S> handler = null;
public void setHandler(Handler<S> handler ) { this.handler = handler; }
public Handler<S> getHandler() { return handler; }
/**
* Attributes provide a way for configuration to be passed to sub-components
* without the {@link org.apache.coyote.ProtocolHandler} being aware of the
* properties available on those sub-components.
*/
protected HashMap<String, Object> attributes = new HashMap<>();
/**
* Generic property setter called when a property for which a specific
* setter already exists within the
* {@link org.apache.coyote.ProtocolHandler} needs to be made available to
* sub-components. The specific setter will call this method to populate the
* attributes.
*
* @param name Name of property to set
* @param value The value to set the property to
*/
public void setAttribute(String name, Object value) {
if (getLog().isTraceEnabled()) {
getLog().trace(sm.getString("endpoint.setAttribute", name, value));
}
attributes.put(name, value);
}
/**
* Used by sub-components to retrieve configuration information.
*
* @param key The name of the property for which the value should be
* retrieved
*
* @return The value of the specified property
*/
public Object getAttribute(String key) {
Object value = attributes.get(key);
if (getLog().isTraceEnabled()) {
getLog().trace(sm.getString("endpoint.getAttribute", key, value));
}
return value;
}
public boolean setProperty(String name, String value) {
setAttribute(name, value);
final String socketName = "socket.";
try {
if (name.startsWith(socketName)) {
return IntrospectionUtils.setProperty(socketProperties, name.substring(socketName.length()), value);
} else {
return IntrospectionUtils.setProperty(this,name,value,false);
}
}catch ( Exception x ) {
getLog().error(sm.getString("endpoint.setAttributeError", name, value), x);
return false;
}
}
public String getProperty(String name) {
String value = (String) getAttribute(name);
final String socketName = "socket.";
if (value == null && name.startsWith(socketName)) {
Object result = IntrospectionUtils.getProperty(socketProperties, name.substring(socketName.length()));
if (result != null) {
value = result.toString();
}
}
return value;
}
/**
* 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() {
Executor executor = this.executor;
if (executor != null) {
if (executor instanceof ThreadPoolExecutor) {
return ((ThreadPoolExecutor) executor).getPoolSize();
} else if (executor instanceof java.util.concurrent.ThreadPoolExecutor) {
return ((java.util.concurrent.ThreadPoolExecutor) executor).getPoolSize();
} else if (executor instanceof ResizableExecutor) {
return ((ResizableExecutor) executor).getPoolSize();
} else {
return -1;
}
} else {
return -2;
}
}
/**
* Return the amount of threads that are in use
*
* @return the amount of threads that are in use
*/
public int getCurrentThreadsBusy() {
Executor executor = this.executor;
if (executor != null) {
if (executor instanceof ThreadPoolExecutor) {
return ((ThreadPoolExecutor) executor).getActiveCount();
} else if (executor instanceof java.util.concurrent.ThreadPoolExecutor) {
return ((java.util.concurrent.ThreadPoolExecutor) executor).getActiveCount();
} else if (executor instanceof ResizableExecutor) {
return ((ResizableExecutor) executor).getActiveCount();
} else {
return -1;
}
} else {
return -2;
}
}
public boolean isRunning() {
return running;
}
public boolean isPaused() {
return paused;
}
public void createExecutor() {
internalExecutor = true;
TaskQueue taskqueue = new TaskQueue();
TaskThreadFactory tf = new TaskThreadFactory(getName() + "-exec-", daemon, getThreadPriority());
executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), 60, TimeUnit.SECONDS,taskqueue, tf);
taskqueue.setParent( (ThreadPoolExecutor) executor);
}
public void shutdownExecutor() {
Executor executor = this.executor;
if (executor != null && internalExecutor) {
this.executor = null;
if (executor instanceof ThreadPoolExecutor) {
//this is our internal one, so we need to shut it down
ThreadPoolExecutor tpe = (ThreadPoolExecutor) executor;
tpe.shutdownNow();
long timeout = getExecutorTerminationTimeoutMillis();
if (timeout > 0) {
try {
tpe.awaitTermination(timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// Ignore
}
if (tpe.isTerminating()) {
getLog().warn(sm.getString("endpoint.warn.executorShutdown", getName()));
}
}
TaskQueue queue = (TaskQueue) tpe.getQueue();
queue.setParent(null);
}
}
}
/**
* Unlock the server socket acceptor threads using bogus connections.
*/
protected void unlockAccept() {
// Only try to unlock the acceptor if it is necessary
if (acceptor == null || acceptor.getState() != AcceptorState.RUNNING) {
return;
}
InetSocketAddress unlockAddress = null;
InetSocketAddress localAddress = null;
try {
localAddress = getLocalAddress();
} catch (IOException ioe) {
getLog().debug(sm.getString("endpoint.debug.unlock.localFail", getName()), ioe);
}
if (localAddress == null) {
getLog().warn(sm.getString("endpoint.debug.unlock.localNone", getName()));
return;
}
try {
unlockAddress = getUnlockAddress(localAddress);
try (java.net.Socket s = new java.net.Socket()) {
int stmo = 2 * 1000;
int utmo = 2 * 1000;
if (getSocketProperties().getSoTimeout() > stmo) {
stmo = getSocketProperties().getSoTimeout();
}
if (getSocketProperties().getUnlockTimeout() > utmo) {
utmo = getSocketProperties().getUnlockTimeout();
}
s.setSoTimeout(stmo);
s.setSoLinger(getSocketProperties().getSoLingerOn(),getSocketProperties().getSoLingerTime());
if (getLog().isDebugEnabled()) {
getLog().debug("About to unlock socket for:" + unlockAddress);
}
s.connect(unlockAddress,utmo);
if (getDeferAccept()) {
/*
* In the case of a deferred accept / accept filters we need to
* send data to wake up the accept. Send OPTIONS * to bypass
* even BSD accept filters. The Acceptor will discard it.
*/
OutputStreamWriter sw;
sw = new OutputStreamWriter(s.getOutputStream(), "ISO-8859-1");
sw.write("OPTIONS * HTTP/1.0\r\n" +
"User-Agent: Tomcat wakeup connection\r\n\r\n");
sw.flush();
}
if (getLog().isDebugEnabled()) {
getLog().debug("Socket unlock completed for:" + unlockAddress);
}
}
// Wait for up to 1000ms acceptor threads to unlock. Particularly
// for the unit tests, we want to exit this loop as quickly as
// possible. However, we also don't want to trigger excessive CPU
// usage if the unlock takes longer than expected. Therefore, we
// initially wait for the unlock in a tight loop but if that takes
// more than 1ms we start using short sleeps to reduce CPU usage.
long startTime = System.nanoTime();
while (startTime + 1_000_000_000 > System.nanoTime() && acceptor.getState() == AcceptorState.RUNNING) {
if (startTime + 1_000_000 < System.nanoTime()) {
Thread.sleep(1);
}
}
} catch(Throwable t) {
ExceptionUtils.handleThrowable(t);
if (getLog().isDebugEnabled()) {
getLog().debug(sm.getString(
"endpoint.debug.unlock.fail", String.valueOf(getPortWithOffset())), t);
}
}
}
private static InetSocketAddress getUnlockAddress(InetSocketAddress localAddress) throws SocketException {
if (localAddress.getAddress().isAnyLocalAddress()) {
// Need a local address of the same type (IPv4 or IPV6) as the
// configured bind address since the connector may be configured
// to not map between types.
InetAddress loopbackUnlockAddress = null;
InetAddress linkLocalUnlockAddress = null;
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (localAddress.getAddress().getClass().isAssignableFrom(inetAddress.getClass())) {
if (inetAddress.isLoopbackAddress()) {
if (loopbackUnlockAddress == null) {
loopbackUnlockAddress = inetAddress;
}
} else if (inetAddress.isLinkLocalAddress()) {
if (linkLocalUnlockAddress == null) {
linkLocalUnlockAddress = inetAddress;
}
} else {
// Use a non-link local, non-loop back address by default
return new InetSocketAddress(inetAddress, localAddress.getPort());
}
}
}
}
// Prefer loop back over link local since on some platforms (e.g.
// OSX) some link local addresses are not included when listening on
// all local addresses.
if (loopbackUnlockAddress != null) {
return new InetSocketAddress(loopbackUnlockAddress, localAddress.getPort());
}
if (linkLocalUnlockAddress != null) {
return new InetSocketAddress(linkLocalUnlockAddress, localAddress.getPort());
}
// Fallback
return new InetSocketAddress("localhost", localAddress.getPort());
} else {
return localAddress;
}
}
// ---------------------------------------------- Request processing methods
/**
* Process the given SocketWrapper with the given status. Used to trigger
* processing as if the Poller (for those endpoints that have one)
* selected the socket.
*
* @param socketWrapper The socket wrapper to process
* @param event The socket event to be processed
* @param dispatch Should the processing be performed on a new
* container thread
*
* @return if processing was triggered successfully
*/
public boolean processSocket(SocketWrapperBase<S> socketWrapper,
SocketEvent event, boolean dispatch) {
try {
if (socketWrapper == null) {
return false;
}
SocketProcessorBase<S> sc = null;
if (processorCache != null) {
sc = processorCache.pop();
}
if (sc == null) {
sc = createSocketProcessor(socketWrapper, event);
} else {
sc.reset(socketWrapper, event);
}
Executor executor = getExecutor();
if (dispatch && executor != null) {
executor.execute(sc);
} else {
sc.run();
}
} catch (RejectedExecutionException ree) {
getLog().warn(sm.getString("endpoint.executor.fail", socketWrapper) , ree);
return false;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
// This means we got an OOM or similar creating a thread, or that
// the pool and its queue are full
getLog().error(sm.getString("endpoint.process.fail"), t);
return false;
}
return true;
}
protected abstract SocketProcessorBase<S> createSocketProcessor(
SocketWrapperBase<S> socketWrapper, SocketEvent event);
// ------------------------------------------------------- Lifecycle methods
/*
* NOTE: There is no maintenance of state or checking for valid transitions
* within this class other than ensuring that bind/unbind are called in the
* right place. It is expected that the calling code will maintain state and
* prevent invalid state transitions.
*/
public abstract void bind() throws Exception;
public abstract void unbind() throws Exception;
public abstract void startInternal() throws Exception;
public abstract void stopInternal() throws Exception;
private void bindWithCleanup() throws Exception {
try {
bind();
} catch (Throwable t) {
// Ensure open sockets etc. are cleaned up if something goes
// wrong during bind
ExceptionUtils.handleThrowable(t);
unbind();
throw t;
}
}
public final void init() throws Exception {
if (bindOnInit) {
bindWithCleanup();
bindState = BindState.BOUND_ON_INIT;
}
if (this.domain != null) {
// Register endpoint (as ThreadPool - historical name)
oname = new ObjectName(domain + ":type=ThreadPool,name=\"" + getName() + "\"");
Registry.getRegistry(null, null).registerComponent(this, oname, null);
ObjectName socketPropertiesOname = new ObjectName(domain +
":type=SocketProperties,name=\"" + getName() + "\"");
socketProperties.setObjectName(socketPropertiesOname);
Registry.getRegistry(null, null).registerComponent(socketProperties, socketPropertiesOname, null);
for (SSLHostConfig sslHostConfig : findSslHostConfigs()) {
registerJmx(sslHostConfig);
}
}
}
private void registerJmx(SSLHostConfig sslHostConfig) {
if (domain == null) {
// Before init the domain is null
return;
}
ObjectName sslOname = null;
try {
sslOname = new ObjectName(domain + ":type=SSLHostConfig,ThreadPool=\"" +
getName() + "\",name=" + ObjectName.quote(sslHostConfig.getHostName()));
sslHostConfig.setObjectName(sslOname);
try {
Registry.getRegistry(null, null).registerComponent(sslHostConfig, sslOname, null);
} catch (Exception e) {
getLog().warn(sm.getString("endpoint.jmxRegistrationFailed", sslOname), e);
}
} catch (MalformedObjectNameException e) {
getLog().warn(sm.getString("endpoint.invalidJmxNameSslHost",
sslHostConfig.getHostName()), e);
}
for (SSLHostConfigCertificate sslHostConfigCert : sslHostConfig.getCertificates()) {
ObjectName sslCertOname = null;
try {
sslCertOname = new ObjectName(domain +
":type=SSLHostConfigCertificate,ThreadPool=\"" + getName() +
"\",Host=" + ObjectName.quote(sslHostConfig.getHostName()) +
",name=" + sslHostConfigCert.getType());
sslHostConfigCert.setObjectName(sslCertOname);
try {
Registry.getRegistry(null, null).registerComponent(
sslHostConfigCert, sslCertOname, null);
} catch (Exception e) {
getLog().warn(sm.getString("endpoint.jmxRegistrationFailed", sslCertOname), e);
}
} catch (MalformedObjectNameException e) {
getLog().warn(sm.getString("endpoint.invalidJmxNameSslHostCert",
sslHostConfig.getHostName(), sslHostConfigCert.getType()), e);
}
}
}
private void unregisterJmx(SSLHostConfig sslHostConfig) {
Registry registry = Registry.getRegistry(null, null);
registry.unregisterComponent(sslHostConfig.getObjectName());
for (SSLHostConfigCertificate sslHostConfigCert : sslHostConfig.getCertificates()) {
registry.unregisterComponent(sslHostConfigCert.getObjectName());
}
}
public final void start() throws Exception {
if (bindState == BindState.UNBOUND) {
bindWithCleanup();
bindState = BindState.BOUND_ON_START;
}
startInternal();
}
protected void startAcceptorThread() {
acceptor = new Acceptor<>(this);
String threadName = getName() + "-Acceptor";
acceptor.setThreadName(threadName);
Thread t = new Thread(acceptor, threadName);
t.setPriority(getAcceptorThreadPriority());
t.setDaemon(getDaemon());
t.start();
}
/**
* Pause the endpoint, which will stop it accepting new connections and
* unlock the acceptor.
*/
public void pause() {
if (running && !paused) {
paused = true;
releaseConnectionLatch();
unlockAccept();
getHandler().pause();
}
}
/**
* Resume the endpoint, which will make it start accepting new connections
* again.
*/
public void resume() {
if (running) {
paused = false;
}
}
public final void stop() throws Exception {
stopInternal();
if (bindState == BindState.BOUND_ON_START || bindState == BindState.SOCKET_CLOSED_ON_STOP) {
unbind();
bindState = BindState.UNBOUND;
}
}
public final void destroy() throws Exception {
if (bindState == BindState.BOUND_ON_INIT) {
unbind();
bindState = BindState.UNBOUND;
}
Registry registry = Registry.getRegistry(null, null);
registry.unregisterComponent(oname);
registry.unregisterComponent(socketProperties.getObjectName());
for (SSLHostConfig sslHostConfig : findSslHostConfigs()) {
unregisterJmx(sslHostConfig);
}
}
protected abstract Log getLog();
protected LimitLatch initializeConnectionLatch() {
if (maxConnections==-1) {
return null;
}
if (connectionLimitLatch==null) {
connectionLimitLatch = new LimitLatch(getMaxConnections());
}
return connectionLimitLatch;
}
private void releaseConnectionLatch() {
LimitLatch latch = connectionLimitLatch;
if (latch!=null) {
latch.releaseAll();
}
connectionLimitLatch = null;
}
protected void countUpOrAwaitConnection() throws InterruptedException {
if (maxConnections==-1) {
return;
}
LimitLatch latch = connectionLimitLatch;
if (latch!=null) {
latch.countUpOrAwait();
}
}
protected long countDownConnection() {
if (maxConnections==-1) {
return -1;
}
LimitLatch latch = connectionLimitLatch;
if (latch!=null) {
long result = latch.countDown();
if (result<0) {
getLog().warn(sm.getString("endpoint.warn.incorrectConnectionCount"));
}
return result;
} else {
return -1;
}
}
/**
* Close the server socket (to prevent further connections) if the server
* socket was originally bound on {@link #start()} (rather than on
* {@link #init()}).
*
* @see #getBindOnInit()
*/
public final void closeServerSocketGraceful() {
if (bindState == BindState.BOUND_ON_START) {
// Stop accepting new connections
acceptor.stop(-1);
// Release locks that may be preventing the acceptor from stopping
releaseConnectionLatch();
unlockAccept();
// Signal to any multiplexed protocols (HTTP/2) that they may wish
// to stop accepting new streams
getHandler().pause();
// Update the bindState. This has the side-effect of disabling
// keep-alive for any in-progress connections
bindState = BindState.SOCKET_CLOSED_ON_STOP;
try {
doCloseServerSocket();
} catch (IOException ioe) {
getLog().warn(sm.getString("endpoint.serverSocket.closeFailed", getName()), ioe);
}
}
}
/**
* Wait for the client connections to the server to close gracefully. The
* method will return when all of the client connections have closed or the
* method has been waiting for {@code waitTimeMillis}.
*
* @param waitMillis The maximum time to wait in milliseconds for the
* client connections to close.
*
* @return The wait time, if any remaining when the method returned
*/
public final long awaitConnectionsClose(long waitMillis) {
while (waitMillis > 0 && !connections.isEmpty()) {
try {
Thread.sleep(50);
waitMillis -= 50;
} catch (InterruptedException e) {
Thread.interrupted();
waitMillis = 0;
}
}
return waitMillis;
}
/**
* Actually close the server socket but don't perform any other clean-up.
*
* @throws IOException If an error occurs closing the socket
*/
protected abstract void doCloseServerSocket() throws IOException;
protected abstract U serverSocketAccept() throws Exception;
protected abstract boolean setSocketOptions(U socket);
/**
* Close the socket when the connection has to be immediately closed when
* an error occurs while configuring the accepted socket or trying to
* dispatch it for processing. The wrapper associated with the socket will
* be used for the close.
* @param socket The newly accepted socket
*/
protected void closeSocket(U socket) {
SocketWrapperBase<S> socketWrapper = connections.get(socket);
if (socketWrapper != null) {
socketWrapper.close();
}
}
/**
* Close the socket. This is used when the connector is not in a state
* which allows processing the socket, or if there was an error which
* prevented the allocation of the socket wrapper.
* @param socket The newly accepted socket
*/
protected abstract void destroySocket(U socket);
}
|