Tomcat源碼解析:初始化

Bootstrap

啓動Tomcat只需要執行Bootstrap中的#main方法即可。

public static void main(String[] args) {
     Bootstrap bootstrap = new Bootstrap();
     bootstrap.init();//實例化Catalina,並設置classloader
    //...
    if (command.equals("start")) {
        daemon.setAwait(true);
        daemon.load(args);//解析xml,實例化組件,並執行Lifecycle的init階段
        daemon.start();//start階段
    }
}

init

初始化classloader ,實例化Catalina類,並且反射調用setParentClassLoader將sharedLoader設置進去。

public void init() throws Exception {
    //初始化commonLoader catalinaLoader sharedLoader
    initClassLoaders();

    Thread.currentThread().setContextClassLoader(catalinaLoader);

    SecurityClassLoad.securityClassLoad(catalinaLoader);

    // Load our startup class and call its process() method
    if (log.isDebugEnabled())
        log.debug("Loading startup class");
    Class<?> startupClass = catalinaLoader.loadClass("org.apache.catalina.startup.Catalina");
    Object startupInstance = startupClass.getConstructor().newInstance();

    // Set the shared extensions class loader
    if (log.isDebugEnabled())
        log.debug("Setting startup class properties");
    String methodName = "setParentClassLoader";
    Class<?>[] paramTypes = new Class[1];
    paramTypes[0] = Class.forName("java.lang.ClassLoader");
    Object[] paramValues = new Object[1];
    paramValues[0] = sharedLoader;
    Method method =
        startupInstance.getClass().getMethod(methodName, paramTypes);
    method.invoke(startupInstance, paramValues);

    catalinaDaemon = startupInstance;
}

load

load方法會反射調用Catalina#load方法進行解析xml,實例化組件,並執行Lifecycle的init階段。

private void load(String[] arguments) throws Exception {

    // Call the load() method
    String methodName = "load";
    Object[] param;
    Class<?>[] paramTypes;
    if (arguments==null || arguments.length==0) {
        paramTypes = null;
        param = null;
    } else {
        paramTypes = new Class[1];
        paramTypes[0] = arguments.getClass();
        param = new Object[1];
        param[0] = arguments;
    }
    Method method =
        catalinaDaemon.getClass().getMethod(methodName, paramTypes);
    if (log.isDebugEnabled()) {
        log.debug("Calling startup class " + method);
    }
    method.invoke(catalinaDaemon, param);
}

Catalina

load

public void load() {

    //...

    initDirs();

    // Before digester - it may be needed
    initNaming();

    // Set configuration source //獲取server.xml的存放位置
    ConfigFileLoader.setSource(new CatalinaBaseConfigurationSource(Bootstrap.getCatalinaBaseFile(), getConfigFile()));
    File file = configFile();

    // Create and execute our Digester 
    //將需要的class,屬性及需要執行的方法封裝存入Digester 
    // 定義解析server.xml的配置,告訴Digester哪個xml標籤應該解析成什麼類
    Digester digester = createStartDigester();
    //解析server.xml
    try (ConfigurationSource.Resource resource = ConfigFileLoader.getSource().getServerXml()) {
        InputStream inputStream = resource.getInputStream();
        InputSource inputSource = new InputSource(resource.getURI().toURL().toString());
        inputSource.setByteStream(inputStream);
        digester.push(this);// 把Catalina作爲一個頂級實例
        digester.parse(inputSource);//解析xml,會實例化各個組件,比如Server、Container、Connector等
    } catch (Exception e) {
        //...
    }
    // 給Server設置catalina信息
    getServer().setCatalina(this);
    getServer().setCatalinaHome(Bootstrap.getCatalinaHomeFile());
    getServer().setCatalinaBase(Bootstrap.getCatalinaBaseFile());

    // Stream redirection
    initStreams();//初始化System.out和err

    // Start the new server 
    // 調用Lifecycle的init階段
    //...
    getServer().init();
    
}
  • 首先找到server.xml
  • 使用Digester來解析xml,並按執行提前配置好的規則
  • 調用Lifecycle的init階段

因爲Server、Container、Connector等的實例化是在解析xml時完成的,所以需要先了解一下Digester是什麼。

Digester

Digester是一款用於將XML轉換成Java對象的事件驅動型工具,是對SAX的高層次封裝。它提供一套對象棧機制用於構建Java對象,這是因爲XML是分層結構,所以創建的Java對象也應該是分層級的樹狀結構,而且還要根據XML內容組織各層級Java對象的內部結構以及設置相關屬性。

這裏主要對Digester在Tomcat中使用的處理規則進行說明。

規則類 描述
ObjectCreateRule 當begin()方法調用時,會將指定的java class實例化,並將其放入對象棧。具體的java類可由該規則的構造方法傳入,也可以通過當前處理XML節點的某個屬性指定,屬性名稱通過構造方法傳入。當end()方法調用時,創建的對象將從棧中取出
SetPropertiesRule 當begin()方法調用時,Digester使用setter方法將XML節點屬性值設置到棧頂的對象中。
SetNextRule 當end()方法調用時,Digester會棧頂對象實例作爲屬性設置到父class(即棧頂對象後一個對象,index爲1)中

這裏拿ObjectCreateRule來做個示範

ObjectCreateRule

public void begin(String namespace, String name, Attributes attributes)
    throws Exception {

    String realClassName = getRealClassName(attributes);
    //...
    // Instantiate the new object and push it on the context stack
    Class<?> clazz = digester.getClassLoader().loadClass(realClassName);
    Object instance = clazz.getConstructor().newInstance();
    digester.push(instance);
}

public void end(String namespace, String name) throws Exception {
    Object top = digester.pop();
    //...
}

而層級結構在createStartDigester()配置,這裏同時會初始化監聽器,包括定義在server.xml裏的和createStartDigester()裏的。

Catalina#createStartDigester

protected Digester createStartDigester() {
    Digester digester = new Digester();
    //...
    //創建server實例,默認實現爲StandardServer
    digester.addObjectCreate("Server",
                             "org.apache.catalina.core.StandardServer",
                             "className");
    digester.addSetProperties("Server");
    digester.addSetNext("Server",
                        "setServer",
                        "org.apache.catalina.Server");
    //...
}
  • 首先實例化StandardServer。
  • 然後將xml裏配置的Server的屬性,如port和shutdown等調用set方法設置到server
<Server port="8095" shutdown="SHUTDOWN">
    ...
</Server>
  • 最後調用setServer將當前StandardServer設置到Catalina中。

需要注意的是:EngineConfig,HostConfig,ContextConfig都是在這裏作爲生命週期監聽器實例化並設置到對應的節點中去的。

這裏放一張xml解析完成後的圖,方便理解

在這裏插入圖片描述

init

解析完成後,會進行初始化,這裏會調用LifecycleBase#init方法,從server開始調用init方法,進行初始化。

getServer().init();

LifecycleBase#init

這裏先由LifecycleBase改變當前狀態值爲INITIALIZING,併發出事件通知,即執行當前事件的監聽器,然後執行各個節點的初始化方法,最後在將狀態設置爲初始化完成INITIALIZED,併發出事件通知。這裏的server,即StandardServer只會改變自己的狀態值,而不會改變子容器service的狀態值。而且考慮到併發修改狀態值的問題,init方法使用了synchronized鎖,並用volatile修飾state值。

public final synchronized void init() throws LifecycleException {
    if (!state.equals(LifecycleState.NEW)) {
        invalidTransition(Lifecycle.BEFORE_INIT_EVENT);
    }

    try {
        //將狀態設置爲初始化中,並執行監聽器
        setStateInternal(LifecycleState.INITIALIZING, null, false);
        //真正的初始化方法
        initInternal();
         //將狀態設置爲初始化完成,並執行監聽器
        setStateInternal(LifecycleState.INITIALIZED, null, false);
    } catch (Throwable t) {
        handleSubClassException(t, "lifecycleBase.initFail", toString());
    }
}

然後會執行server的初始化方法。

Server初始化

StadardServer#initInternal

protected void initInternal() throws LifecycleException {

    super.initInternal();

    // Initialize utility executor
    reconfigureUtilityExecutor(getUtilityThreadsInternal(utilityThreads));
    register(utilityExecutor, "type=UtilityExecutor");

    // 往jmx中註冊全局的String cache,儘管這個cache是全局聽,但是如果在同一個jvm中存在多個Server,
    // 那麼則會註冊多個不同名字的StringCache,這種情況在內嵌的tomcat中可能會出現
    onameStringCache = register(new StringCache(), "type=StringCache");

    // Register the MBeanFactory // 註冊MBeanFactory,用來管理Server
    MBeanFactory factory = new MBeanFactory();
    factory.setContainer(this);
    onameMBeanFactory = register(factory, "type=MBeanFactory");

    // Register the naming resources // 初始化NamingResources
    globalNamingResources.init();

    // Populate the extension validator with JARs from common and shared
    // lass loaders
    if (getCatalina() != null) {
        //...
    }
    // Initialize our defined Services  // 初始化內部的Service
    for (int i = 0; i < services.length; i++) {
        services[i].init();
    }
}
  1. 先是將自己註冊到jmx
  2. 然後註冊StringCache和MBeanFactory
  3. 初始化/NamingResources。
  4. 調用service的init

Service初始化

service的初始化也調用了lifecycleBase的init的方法,與server一樣,這裏主要關注本身的service方法。

StandardService#initInternal

protected void initInternal() throws LifecycleException {

    super.initInternal();
    // 初始化Engine
    if (engine != null) {
        engine.init();
    }

    // Initialize any Executors // 存在Executor線程池,則進行初始化,默認是沒有的
    for (Executor executor : findExecutors()) {
        if (executor instanceof JmxEnabled) {
            ((JmxEnabled) executor).setDomain(getDomain());
        }
        executor.init();
    }

    // Initialize mapper listener
    mapperListener.init();

    // Initialize our defined Connectors // 初始化Connector
    synchronized (connectorsLock) {
        for (Connector connector : connectors) {
            connector.init();
        }
    }
}
  1. 註冊jms
  2. 初始化Engine。
  3. 初始化線程池
  4. 初始化Connector

Engine初始化

StandardEgine#initInternal

protected void initInternal() throws LifecycleException {
    getRealm();
    super.initInternal();
}

public Realm getRealm() {
    Realm configured = super.getRealm();
    // If no set realm has been called - default to NullRealm
    // This can be overridden at engine, context and host level
    if (configured == null) {
        configured = new NullRealm();
        this.setRealm(configured);
    }
    return configured;
}
  1. 如果當前Engine沒有顯示配置Relam,則會獲取默認的Relam實現,即NullRealm。這裏在這個版本的server.xml裏配置了LockOutRealm,用於防止通過蠻力攻擊猜測用戶密碼的嘗試。
<Realm className="org.apache.catalina.realm.LockOutRealm">
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
           resourceName="UserDatabase"/>
</Realm>
  1. 調用父類ContainerBaseinitInternal

ContainerBase#initInternal做了兩個操作,首先創建start、stop線程池,而這個線程池默認情況下,線程數是1,然後註冊jms。代碼如下:

private int startStopThreads = 1;
protected ExecutorService startStopExecutor;

protected void initInternal() throws LifecycleException {
    reconfigureStartStopExecutor(getStartStopThreads());
    super.initInternal();
}


private void reconfigureStartStopExecutor(int threads) {
    if (threads == 1) {
        // Use a fake executor
        if (!(startStopExecutor instanceof InlineExecutorService)) {
            startStopExecutor = new InlineExecutorService();
        }
    } else {
        // Delegate utility execution to the Service
        Server server = Container.getService(this).getServer();
        server.setUtilityThreads(threads);
        startStopExecutor = server.getUtilityExecutor();
    }
}

public int getStartStopThreads() {
    return startStopThreads;
}

那麼這個startStopExecutor的作用是什麼呢?這部分代碼在當前類的startInternalstopInternal方法中。

  1. 在start時,如果有子容器,將子容器的start方法放到線程池來操作
  2. 在stop時,同上。

到這裏Engine的初始化就結束了,而他的子容器Host則是在start階段才進行初始化。

Connector初始化

Connector的初始化和上面的步驟也一樣,這裏默認會對HTTP/1.1和AJP/1.3做初始化。這個配置來源於server.xml中。

<Connector port="8091" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" />
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

Connector#initInternal

protected void initInternal() throws LifecycleException {

    super.initInternal();

    // Initialize adapter
    // 初始化Coyote適配器
    adapter = new CoyoteAdapter(this);
    protocolHandler.setAdapter(adapter);
    if (service != null) {
        protocolHandler.setUtilityExecutor(service.getServer().getUtilityExecutor());
    }
    //...
    // 初始化ProtocolHandler,這個init不是Lifecycle定義的init,而是ProtocolHandler接口的init
    try {
        protocolHandler.init();
    } catch (Exception e) {
        throw new LifecycleException(
            sm.getString("coyoteConnector.protocolHandlerInitializationFailed"), e);
    }
}
  1. 實例化CoyoteAdapter,並將其作爲protocolHandler的適配器。

  2. 執行protocolHandler的初始化,這裏的初始化並不是生命週期的init階段,而是protocolHandler的init方法,而protocolHandler的配置是再Connector的構造方法裏。

private int maxCookieCount = 200;

protected int maxParameterCount = 10000;

protected int maxPostSize = 2 * 1024 * 1024;

protected int maxSavePostSize = 4 * 1024;
public Connector(String protocol) {
    boolean aprConnector = AprLifecycleListener.isAprAvailable() &&
        AprLifecycleListener.getUseAprConnector();

    if ("HTTP/1.1".equals(protocol) || protocol == null) {
        if (aprConnector) {
            protocolHandlerClassName = "org.apache.coyote.http11.Http11AprProtocol";
        } else {
            protocolHandlerClassName = "org.apache.coyote.http11.Http11NioProtocol";
        }
    } else if ("AJP/1.3".equals(protocol)) {
        if (aprConnector) {
            protocolHandlerClassName = "org.apache.coyote.ajp.AjpAprProtocol";
        } else {
            protocolHandlerClassName = "org.apache.coyote.ajp.AjpNioProtocol";
        }
    } else {
        protocolHandlerClassName = protocol;
    }

    // Instantiate protocol handler
    ProtocolHandler p = null;
    try {
        Class<?> clazz = Class.forName(protocolHandlerClassName);
        p = (ProtocolHandler) clazz.getConstructor().newInstance();
    } catch (Exception e) {
        log.error(sm.getString(
            "coyoteConnector.protocolHandlerInstantiationFailed"), e);
    } finally {
        this.protocolHandler = p;
    }

    // Default for Connector depends on this system property
    setThrowOnFailure(Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE"));
}

這裏主要對Http11NioProtocol做分析,可以看到在實例化Connector時會初始化一些連接參數,但卻沒有connectTimeout,那麼connectTimeout是在哪裏被設置進去呢?,從Connector的構造函數中,看到實例化了一個默認的 Http11NioProtocol,而實例化Http11NioProtocol時,在其父類的構造方法裏發現,會設置一個connectTimeout的默認值,默認值是60000,如果在server.xml裏配置了connectTimeout,會在解析xml時覆蓋這個默認值。

public Http11NioProtocol() {
    super(new NioEndpoint());
}

public AbstractHttp11JsseProtocol(AbstractJsseEndpoint<S,?> endpoint) {
    super(endpoint);
}

public AbstractHttp11Protocol(AbstractEndpoint<S,?> endpoint) {
    super(endpoint);
    setConnectionTimeout(Constants.DEFAULT_CONNECTION_TIMEOUT);
    ConnectionHandler<S> cHandler = new ConnectionHandler<>(this);
    setHandler(cHandler);
    getEndpoint().setHandler(cHandler);
}

ProtocolHandler初始化

Http11NioProtocol的init方法的主要實現是在AbstractProtocol裏,首先完成jmx的註冊,然後對NioEndpoint進行初始化。

AbstractProtocol#init

public void init() throws Exception {
   if (getLog().isInfoEnabled()) {
       getLog().info(sm.getString("abstractProtocolHandler.init", getName()));
       logPortOffset();
   }

   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
   endpoint.init();
}

Endpoint初始化

Endpoint的初始化主要是完成對端口的綁定和監聽。

AbstractEndpoint.java

public final void init() throws Exception {
    if (bindOnInit) {
        bindWithCleanup();//綁定端口,連接socket
        bindState = BindState.BOUND_ON_INIT;
    }
    if (this.domain != null) {
        // Register endpoint (as ThreadPool - historical name)
        //...
    }
}

private void bindWithCleanup() throws Exception {
    try {
        bind();//這裏是重點
    } catch (Throwable t) {
        // ...
    }
}

而端口的綁定是在NioEndpoint裏。

NioEndpoint#bind

public void bind() throws Exception {
    initServerSocket();

    // Initialize thread count defaults for acceptor, poller // 初始化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 // 如果有必要的話初始化ssl
    initialiseSsl();
    // 初始化selector
    selectorPool.open(getName());
}

protected void initServerSocket() throws Exception {
    if (!getUseInheritedChannel()) {// 實例化ServerSocketChannel,並且綁定端口和地址
        serverSock = ServerSocketChannel.open();//創建socket
        socketProperties.setProperties(serverSock.socket());//將超時時間等設置到socket中
        InetSocketAddress addr = new InetSocketAddress(getAddress(), getPortWithOffset());
        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
}
  1. 首先創建socket,然後將連接屬性設置到socket中。
  2. 初始化acceptor、poller線程的數量。
  3. 初始化selector,並啓動BlockPoller線程,這個poller暫時不知道是幹啥的。

至此,整個初始化過程便告一段落。整個初始化過程,由parent組件控制child組件的初始化,一層層往下傳遞,直到最後全部初始化。

參考:https://blog.csdn.net/Dwade_mia/article/details/79051444

​ 《Tomcat架構解析》劉光瑞

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章