開篇
這篇博文的主要目的是為了理清楚Tomcat監聽的初始化流程,所謂的監聽初始化流程是指Tomcat啟動後直至Accept過程就緒能夠監聽連接配接到來為止。
隻有理清楚監聽的初始化後流程後才能更好的了解Tomcat處理請求的過程,是以也算是基礎的一部分吧。
整篇博文的思路脈絡是先講解初始化過程中各個元件的關聯(架構圖+源碼),然後講解清楚初始化的過程(時序圖+源碼),我想應該是可以講明白的。
文末慣例有招聘資訊彩蛋。
元件關聯說明
說明:
-
- Service元件(StandardService)包含Connector元件。
-
- Connector元件包含ProtocolHandler元件。
-
- ProtocolHandler元件包含AbstractEndpoint元件。
-
- Connector包含CoyoteAdapter對象,CoyoteAdapter儲存至ProtocolHandler對象。
StandardService
public class StandardService extends LifecycleMBeanBase implements Service {
protected Connector connectors[] = new Connector[0];
}
-
- StandardService包含Connector對象。
Connector
public class Connector extends LifecycleMBeanBase {
protected Service service = null;
protected int port = -1;
// 預設的protocolHandler的實作類
protected String protocolHandlerClassName =
"org.apache.coyote.http11.Http11NioProtocol";
// protocolHandler對象
protected final ProtocolHandler protocolHandler;
// CoyoteAdapter對象
protected Adapter adapter = null;
- Connector對象包含ProtocolHandler對象。
ProtocolHandler
- ProtocolHandler具體實作包括ajp和http兩類。
public abstract class AbstractProtocol<S> implements ProtocolHandler,
MBeanRegistration {
private final AbstractEndpoint<S> endpoint;
private Handler<S> handler;
}
- ProtocolHandler的抽象實作類AbstractProtocol包含EndPoint對象。
public class Http11NioProtocol extends AbstractHttp11JsseProtocol<NioChannel> {
public Http11NioProtocol() {
super(new NioEndpoint());
}
}
- Http11NioProtocol作為ProtocolHandler的實作類之一,注意EndPoint的對象的建立。
Endpoint
-
- AbstractEndpoint的實作類包括NioEndpoint、Nio2Endpoint、AprEndpoint。
public abstract class AbstractEndpoint<S> {
protected Acceptor[] acceptors;
private int port;
private InetAddress address;
}
-
- AbstractEndpoint包含 Acceptor[] acceptors。
-
- AbstractEndpoint包含監聽port和address。
監聽初始化流程
-
- 監聽的初始化過程包括三個階段,展現在Connector建立&初始化&啟動。
-
- Connector建立包括建立Connector、protocolHandler、Endpoint核心對象。
-
- Connector的初始化包括初始化Connector、protocolHandler、Endpoint核心對象。
-
- Connector的啟動包括啟動Connector、protocolHandler、Endpoint核心對象。
-
- TCP當中經典server端啟動過程在Endpoint對象中實作,負責處理連接配接請求。
public class Connector extends LifecycleMBeanBase {
public Connector(String protocol) {
setProtocol(protocol);
ProtocolHandler p = null;
try {
Class<?> clazz = Class.forName(protocolHandlerClassName);
p = (ProtocolHandler) clazz.getConstructor().newInstance();
} catch (Exception e) {
} finally {
this.protocolHandler = p;
}
}
protected void initInternal() throws LifecycleException {
super.initInternal();
adapter = new CoyoteAdapter(this);
protocolHandler.setAdapter(adapter);
try {
protocolHandler.init();
} catch (Exception e) {
}
}
protected void startInternal() throws LifecycleException {
setState(LifecycleState.STARTING);
try {
protocolHandler.start();
} catch (Exception e) {
}
}
}
-
- Connector包含建立、初始化、啟動三個階段。
-
- Connector的三個階段對應protocolHnalder的建立、初始化、啟動三個階段。
protocolHandler
public abstract class AbstractProtocol<S> implements ProtocolHandler,
MBeanRegistration {
private final AbstractEndpoint<S> endpoint;
private Handler<S> handler;
public AbstractProtocol(AbstractEndpoint<S> endpoint) {
this.endpoint = endpoint;
setSoLinger(Constants.DEFAULT_CONNECTION_LINGER);
setTcpNoDelay(Constants.DEFAULT_TCP_NO_DELAY);
}
public void init() throws Exception {
if (getLog().isInfoEnabled()) {
getLog().info(sm.getString("abstractProtocolHandler.init", getName()));
}
if (oname == null) {
// Component not pre-registered so register it
oname = createObjectName();
if (oname != null) {
Registry.getRegistry(null, null).registerComponent(this, oname, null);
}
}
if (this.domain != null) {
rgOname = new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getName());
Registry.getRegistry(null, null).registerComponent(
getHandler().getGlobal(), rgOname, null);
}
String endpointName = getName();
endpoint.setName(endpointName.substring(1, endpointName.length()-1));
endpoint.setDomain(domain);
endpoint.init();
}
public void start() throws Exception {
endpoint.start();
asyncTimeout = new AsyncTimeout();
Thread timeoutThread = new Thread(asyncTimeout, getNameInternal() + "-AsyncTimeout");
int priority = endpoint.getThreadPriority();
if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) {
priority = Thread.NORM_PRIORITY;
}
timeoutThread.setPriority(priority);
timeoutThread.setDaemon(true);
timeoutThread.start();
}
}
public class Http11NioProtocol extends AbstractHttp11JsseProtocol<NioChannel> {
public Http11NioProtocol() {
super(new NioEndpoint());
}
}
-
- ProtocolHandler包含建立、初始化、啟動三個階段。
-
- ProtocolHandler的三個階段對應Endpoint的建立、初始化、啟動三個階段。
public abstract class AbstractEndpoint<S> {
public void init() throws Exception {
if (bindOnInit) {
bind();
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);
for (SSLHostConfig sslHostConfig : findSslHostConfigs()) {
registerJmx(sslHostConfig);
}
}
}
public final void start() throws Exception {
if (bindState == BindState.UNBOUND) {
bind();
bindState = BindState.BOUND_ON_START;
}
startInternal();
}
public abstract void startInternal() throws Exception;
public abstract void bind() throws Exception;
}
-
- Endpoint包含建立、初始化、啟動三個階段。
-
- AbstractEndpoint類闆設計模式提供init&start方法。
-
- AbstractEndpoint類init方法實作bind操作,start方法負責啟動監聽。
public class NioEndpoint extends AbstractJsseEndpoint<NioChannel> {
public void bind() throws Exception {
if (!getUseInheritedChannel()) {
serverSock = ServerSocketChannel.open();
socketProperties.setProperties(serverSock.socket());
InetSocketAddress addr = (getAddress()!=null?new InetSocketAddress(getAddress(),getPort()):new InetSocketAddress(getPort()));
serverSock.socket().bind(addr,getAcceptCount());
} else {
// Retrieve the channel provided by the OS
Channel ic = System.inheritedChannel();
if (ic instanceof ServerSocketChannel) {
serverSock = (ServerSocketChannel) ic;
}
if (serverSock == null) {
throw new IllegalArgumentException(sm.getString("endpoint.init.bind.inherited"));
}
}
serverSock.configureBlocking(true); //mimic APR behavior
// Initialize thread count defaults for acceptor, poller
if (acceptorThreadCount == 0) {
// FIXME: Doesn't seem to work that well with multiple accept threads
acceptorThreadCount = 1;
}
if (pollerThreadCount <= 0) {
//minimum one poller thread
pollerThreadCount = 1;
}
setStopLatch(new CountDownLatch(pollerThreadCount));
// Initialize SSL if needed
initialiseSsl();
selectorPool.open();
}
public void startInternal() throws Exception {
if (!running) {
running = true;
paused = false;
processorCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
socketProperties.getProcessorCache());
eventCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
socketProperties.getEventCache());
nioChannels = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE,
socketProperties.getBufferPool());
// Create worker collection
if ( getExecutor() == null ) {
createExecutor();
}
initializeConnectionLatch();
// Start poller threads
pollers = new Poller[getPollerThreadCount()];
for (int i=0; i<pollers.length; i++) {
pollers[i] = new Poller();
Thread pollerThread = new Thread(pollers[i], getName() + "-ClientPoller-"+i);
pollerThread.setPriority(threadPriority);
pollerThread.setDaemon(true);
pollerThread.start();
}
startAcceptorThreads();
}
}
protected class Acceptor extends AbstractEndpoint.Acceptor {
public void run() {
int errorDelay = 0;
while (running) {
while (paused && running) {
state = AcceptorState.PAUSED;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore
}
}
if (!running) {
break;
}
state = AcceptorState.RUNNING;
try {
countUpOrAwaitConnection();
SocketChannel socket = null;
try {
socket = serverSock.accept();
} catch (IOException ioe) {
}
errorDelay = 0;
if (running && !paused) {
if (!setSocketOptions(socket)) {
closeSocket(socket);
}
} else {
closeSocket(socket);
}
} catch (Throwable t) {
}
}
state = AcceptorState.ENDED;
}
}
protected boolean setSocketOptions(SocketChannel socket) {
try {
socket.configureBlocking(false);
Socket sock = socket.socket();
socketProperties.setProperties(sock);
NioChannel channel = nioChannels.pop();
if (channel == null) {
SocketBufferHandler bufhandler = new SocketBufferHandler(
socketProperties.getAppReadBufSize(),
socketProperties.getAppWriteBufSize(),
socketProperties.getDirectBuffer());
if (isSSLEnabled()) {
channel = new SecureNioChannel(socket, bufhandler, selectorPool, this);
} else {
channel = new NioChannel(socket, bufhandler);
}
} else {
channel.setIOChannel(socket);
channel.reset();
}
getPoller0().register(channel);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
try {
log.error("",t);
} catch (Throwable tt) {
ExceptionUtils.handleThrowable(tt);
}
// Tell to close the socket
return false;
}
return true;
}
}
-
- NioEndpoint是AbstractEndpoint的具體實作類之一。
-
- NioEndpoint實作具體的bind和start方法。
-
- NioEndpoint的Acceptor作為具體的實作負責監聽連接配接。
-
- setSocketOptions負責處理新連接配接并通過getPoller0().register(channel)注冊。