设为首页 收藏本站
查看: 682|回复: 0

[经验分享] tomcat源码分析(二)启动---Debug方式

[复制链接]

尚未签到

发表于 2015-8-12 08:14:08 | 显示全部楼层 |阅读模式
1.Bootstrap.java


    /**
* Start the Catalina daemon.
*/
public void start()
throws Exception {
if( catalinaDaemon==null ) init();
Method method = catalinaDaemon.getClass().getMethod("start", (Class [] )null);
        method.invoke(catalinaDaemon, (Object [])null);
}
  2.Catalina.java



1     /**
2      * Start a new server instance.
3      */
4     public void start() {
5
6         if (server == null) {
7             load();
8         }
9
10         long t1 = System.nanoTime();
11         
12         // Start the new server
13         if (server instanceof Lifecycle) {
14             try {
15                 ((Lifecycle) server).start();
16             } catch (LifecycleException e) {
17                 log.error("Catalina.start: ", e);
18             }
19         }
20
21         long t2 = System.nanoTime();
22         if(log.isInfoEnabled())
23             log.info("Server startup in " + ((t2 - t1) / 1000000) + " ms");
24
25         try {
26             // Register shutdown hook
27             if (useShutdownHook) {
28                 if (shutdownHook == null) {
29                     shutdownHook = new CatalinaShutdownHook();
30                 }
31                 Runtime.getRuntime().addShutdownHook(shutdownHook);
32             }
33         } catch (Throwable t) {
34             // This will fail on JDK 1.2. Ignoring, as Tomcat can run
35             // fine without the shutdown hook.
36         }
37
38         if (await) {
39             await();
40             stop();
41         }
42
43     }
  3.standardServer.java



1     /**
2      * Prepare for the beginning of active use of the public methods of this
3      * component.  This method should be called before any of the public
4      * methods of this component are utilized.  It should also send a
5      * LifecycleEvent of type START_EVENT to any registered listeners.
6      *
7      * @exception LifecycleException if this component detects a fatal error
8      *  that prevents this component from being used
9      */
10     public void start() throws LifecycleException {
11
12         // Validate and update our current component state
13         if (log.isInfoEnabled() && started) {
14             log.info(sm.getString("standardService.start.started"));
15         }
16         
17         if( ! initialized )
18             init();
19
20         // Notify our interested LifecycleListeners
21         lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);
22         if(log.isInfoEnabled())
23             log.info(sm.getString("standardService.start.name", this.name));
24         lifecycle.fireLifecycleEvent(START_EVENT, null);
25         started = true;
26
27         // Start our defined Container first
28         if (container != null) {
29             synchronized (container) {
30                 if (container instanceof Lifecycle) {
31                     ((Lifecycle) container).start();
32                 }
33             }
34         }
35
36         synchronized (executors) {
37             for ( int i=0; i<executors.size(); i++ ) {
38                 executors.get(i).start();
39             }
40         }
41
42         // Start our defined Connectors second
43         synchronized (connectors) {
44             for (int i = 0; i < connectors.length; i++) {
45                 if (connectors instanceof Lifecycle)
46                     ((Lifecycle) connectors).start();
47             }
48         }
49         
50         // Notify our interested LifecycleListeners
51         lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);
52
53     }
  StandardEngine.java



1     public void start() throws LifecycleException {
2         if( started ) {
3             return;
4         }
5         if( !initialized ) {
6             init();
7         }
8
9         // Look for a realm - that may have been configured earlier.
10         // If the realm is added after context - it'll set itself.
11         if( realm == null ) {
12             ObjectName realmName=null;
13             try {
14                 realmName=new ObjectName( domain + ":type=Realm");
15                 if( mserver.isRegistered(realmName ) ) {
16                     mserver.invoke(realmName, "init",
17                             new Object[] {},
18                             new String[] {}
19                     );            
20                 }
21             } catch( Throwable t ) {
22                 log.debug("No realm for this engine " + realmName);
23             }
24         }
25            
26         // Log our server identification information
27         //System.out.println(ServerInfo.getServerInfo());
28         if(log.isInfoEnabled())
29             log.info( "Starting Servlet Engine: " + ServerInfo.getServerInfo());
30         if( mbeans != null ) {
31             try {
32                 Registry.getRegistry(null, null)
33                     .invoke(mbeans, "start", false);
34             } catch (Exception e) {
35                 log.error("Error in start() for " + mbeansFile, e);
36             }
37         }
38
39         // Standard container startup
40         super.start();
41
42     }
  ContainerBase.java



1     public synchronized void start() throws LifecycleException {
2
3         // Validate and update our current component state
4         if (started) {
5             if(log.isInfoEnabled())
6                 log.info(sm.getString("containerBase.alreadyStarted", logName()));
7             return;
8         }
9         
10         // Notify our interested LifecycleListeners
11         lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);
12
13         started = true;
14
15         // Start our subordinate components, if any
16         if ((loader != null) && (loader instanceof Lifecycle))
17             ((Lifecycle) loader).start();
18         logger = null;
19         getLogger();
20         if ((logger != null) && (logger instanceof Lifecycle))
21             ((Lifecycle) logger).start();
22         if ((manager != null) && (manager instanceof Lifecycle))
23             ((Lifecycle) manager).start();
24         if ((cluster != null) && (cluster instanceof Lifecycle))
25             ((Lifecycle) cluster).start();
26         if ((realm != null) && (realm instanceof Lifecycle))
27             ((Lifecycle) realm).start();
28         if ((resources != null) && (resources instanceof Lifecycle))
29             ((Lifecycle) resources).start();
30
31         // Start our child containers, if any
32         Container children[] = findChildren();
33         for (int i = 0; i < children.length; i++) {
34             if (children instanceof Lifecycle)
35                 ((Lifecycle) children).start();
36         }
37
38         // Start the Valves in our pipeline (including the basic), if any
39         if (pipeline instanceof Lifecycle)
40             ((Lifecycle) pipeline).start();
41
42         // Notify our interested LifecycleListeners
43         lifecycle.fireLifecycleEvent(START_EVENT, null);
44
45         // Start our thread
46         threadStart();
47
48         // Notify our interested LifecycleListeners
49         lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);
50
51     }
  UserDatabaseRealm.java



    public synchronized void start() throws LifecycleException {
// Perform normal superclass initialization
super.start();
try {
StandardServer server = (StandardServer) ServerFactory.getServer();
Context context = server.getGlobalNamingContext();
database = (UserDatabase) context.lookup(resourceName);
} catch (Throwable e) {
containerLog.error(sm.getString("userDatabaseRealm.lookup",
resourceName),
e);
database = null;
}
if (database == null) {
throw new LifecycleException
(sm.getString("userDatabaseRealm.noDatabase", resourceName));
}
}
  StandardHost.java



    public synchronized void start() throws LifecycleException {
if( started ) {
return;
}
if( ! initialized )
init();
// Look for a realm - that may have been configured earlier.
// If the realm is added after context - it'll set itself.
if( realm == null ) {
ObjectName realmName=null;
try {
realmName=new ObjectName( domain + ":type=Realm,host=" + getName());
if( mserver.isRegistered(realmName ) ) {
mserver.invoke(realmName, "init",
new Object[] {},
new String[] {}
);            
}
} catch( Throwable t ) {
log.debug("No realm for this host " + realmName);
}
}
// Set error report valve
if ((errorReportValveClass != null)
&& (!errorReportValveClass.equals(""))) {
try {
boolean found = false;
if(errorReportValveObjectName != null) {
ObjectName[] names =
((StandardPipeline)pipeline).getValveObjectNames();
for (int i=0; !found && i<names.length; i++)
if(errorReportValveObjectName.equals(names))
found = true ;
}
if(!found) {              
Valve valve = (Valve) Class.forName(errorReportValveClass)
.newInstance();
addValve(valve);
errorReportValveObjectName = ((ValveBase)valve).getObjectName() ;
}
} catch (Throwable t) {
log.error(sm.getString
("standardHost.invalidErrorReportValveClass",
errorReportValveClass));
}
}
if(log.isDebugEnabled()) {
if (xmlValidation)
log.debug(sm.getString("standardHost.validationEnabled"));
else
log.debug(sm.getString("standardHost.validationDisabled"));
}
super.start();
}
  StandardPipeline.java



    public synchronized void start() throws LifecycleException {
// Validate and update our current component state
if (started)
throw new LifecycleException
(sm.getString("standardPipeline.alreadyStarted"));
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);
started = true;
// Start the Valves in our pipeline (including the basic), if any
Valve current = first;
if (current == null) {
current = basic;
}
while (current != null) {
if (current instanceof Lifecycle)
((Lifecycle) current).start();
registerValve(current);
current = current.getNext();
}
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(START_EVENT, null);
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);
}
  ContainerBase.java



    /**
* Start the background thread that will periodically check for
* session timeouts.
*/
protected void threadStart() {
if (thread != null)
return;
if (backgroundProcessorDelay <= 0)
return;
threadDone = false;
String threadName = "ContainerBackgroundProcessor[" + toString() + "]";
thread = new Thread(new ContainerBackgroundProcessor(), threadName);
thread.setDaemon(true);
thread.start();
}
  --------------------------------------------------------------------------------------------------------------------------------------------------------------------
  StandardServce.java



        // Start our defined Connectors second
synchronized (connectors) {
for (int i = 0; i < connectors.length; i++) {
if (connectors instanceof Lifecycle)
((Lifecycle) connectors).start();
}
}
  Connector.java



    public void start() throws LifecycleException {
if( !initialized )
initialize();
// Validate and update our current state
if (started ) {
if(log.isInfoEnabled())
log.info(sm.getString("coyoteConnector.alreadyStarted"));
return;
}
lifecycle.fireLifecycleEvent(START_EVENT, null);
started = true;
// We can't register earlier - the JMX registration of this happens
// in Server.start callback
if ( this.oname != null ) {
// We are registred - register the adapter as well.
try {
Registry.getRegistry(null, null).registerComponent
(protocolHandler, createObjectName(this.domain,"ProtocolHandler"), null);
} catch (Exception ex) {
log.error(sm.getString
("coyoteConnector.protocolRegistrationFailed"), ex);
}
} else {
if(log.isInfoEnabled())
log.info(sm.getString
("coyoteConnector.cannotRegisterProtocol"));
}
try {
            protocolHandler.start();
} catch (Exception e) {
String errPrefix = "";
if(this.service != null) {
errPrefix += "service.getName(): \"" + this.service.getName() + "\"; ";
}
throw new LifecycleException
(errPrefix + " " + sm.getString
("coyoteConnector.protocolHandlerStartFailed", e));
}
if( this.domain != null ) {
mapperListener.setDomain( domain );
//mapperListener.setEngine( service.getContainer().getName() );
            mapperListener.init();
try {
ObjectName mapperOname = createObjectName(this.domain,"Mapper");
if (log.isDebugEnabled())
log.debug(sm.getString(
"coyoteConnector.MapperRegistration", mapperOname));
Registry.getRegistry(null, null).registerComponent
(mapper, mapperOname, "Mapper");
} catch (Exception ex) {
log.error(sm.getString
("coyoteConnector.protocolRegistrationFailed"), ex);
}
}
}
  Http11Protocol.java



1     public void start() throws Exception {
2         if (this.domain != null) {
3             try {
4                 tpOname = new ObjectName
5                     (domain + ":" + "type=ThreadPool,name=" + getName());
6                 Registry.getRegistry(null, null)
7                     .registerComponent(endpoint, tpOname, null );
8             } catch (Exception e) {
9                 log.error("Can't register endpoint");
10             }
11             rgOname=new ObjectName
12                 (domain + ":type=GlobalRequestProcessor,name=" + getName());
13             Registry.getRegistry(null, null).registerComponent
14                 ( cHandler.global, rgOname, null );
15         }
16
17         try {
18             endpoint.start();
19         } catch (Exception ex) {
20             log.error(sm.getString("http11protocol.endpoint.starterror"), ex);
21             throw ex;
22         }
23         if (log.isInfoEnabled())
24             log.info(sm.getString("http11protocol.start", getName()));
25     }
  JIoEndpoint.java



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


    /**
* 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.
*/
public void run() {
// Loop until we receive a shutdown command
while (running) {
// Loop if endpoint is paused
while (paused) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
                    }
}
// Accept the next incoming connection from the server socket
try {
                    Socket socket = serverSocketFactory.acceptSocket(serverSocket);
serverSocketFactory.initSocket(socket);
// Hand this socket off to an appropriate processor
if (!processSocket(socket)) {
// Close socket right away
try {
socket.close();
} catch (IOException e) {
// Ignore
                        }
}
}catch ( IOException x ) {
if ( running ) log.error(sm.getString("endpoint.accept.fail"), x);
} catch (Throwable t) {
log.error(sm.getString("endpoint.accept.fail"), t);
}
// The processor will recycle itself when it finishes

}
}
}
  


       Catalina.start()
c1) Starts the NamingContext and binds all JNDI references into it
c2) Starts the services under <Server> which are:
StandardService -> starts Engine (ContainerBase ->Logger,Loader,Realm,Cluster etc)
c3) StandardHost (started by the service)
Configures a ErrorReportValvem to do proper HTML output for different HTTP
errors codes
Starts the Valves in the pipeline (at least the ErrorReportValve)
Configures the StandardHostValve,
this valves ties the Webapp Class loader to the thread context
it also finds the session for the request
and invokes the context pipeline
Starts the HostConfig component
This component deploys all the webapps
(webapps & conf/Catalina/localhost/*.xml)
Webapps are installed using the deployer (StandardHostDeployer)
The deployer will create a Digester for your context, this digester
will then invoke ContextConfig.start()
The ContextConfig.start() will process the default web.xml (conf/web.xml)
and then process the applications web.xml (WEB-INF/web.xml)
c4) During the lifetime of the container (StandardEngine) there is a background thread that
keeps checking if the context has changed. If a context changes (timestamp of war file,
context xml file, web.xml) then a reload is issued (stop/remove/deploy/start)

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-97653-1-1.html 上篇帖子: 【翻译】Tomcat 6.0 安装与启动 下篇帖子: Tomcat的数据源配置
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表