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

[经验分享] tomcat源码分析(一)初始化---Debug方式

[复制链接]

尚未签到

发表于 2015-8-12 08:01:13 | 显示全部楼层 |阅读模式
  引用网址:
  http://tomcat.apache.org/tomcat-6.0-doc/architecture/startup/serverStartup.txt
  http://tomcat.apache.org/tomcat-6.0-doc/architecture/startup/serverStartup.pdf

Tomcat启动时序
第一步:初始化
类: org.apache.catalina.startup.Bootstrap


1     /**
2      * Initialize daemon.
3      */
4     public void init()
5         throws Exception
6     {
7
8         // Set Catalina path,home and base value is set to system.getProperties("user.dir"),把程序当前目录设置为catalina home和base的值。
9         setCatalinaHome();
10         setCatalinaBase();
11
12         initClassLoaders();
13
14         Thread.currentThread().setContextClassLoader(catalinaLoader);
15
16         SecurityClassLoad.securityClassLoad(catalinaLoader);
17
18         // Load our startup class and call its process() method
19         if (log.isDebugEnabled())
20             log.debug("Loading startup class");
21         Class startupClass =
22             catalinaLoader.loadClass
23             ("org.apache.catalina.startup.Catalina");
24         Object startupInstance = startupClass.newInstance();
25
26         // Set the shared extensions class loader
27         if (log.isDebugEnabled())
28             log.debug("Setting startup class properties");
29         String methodName = "setParentClassLoader";
30         Class paramTypes[] = new Class[1];
31         paramTypes[0] = Class.forName("java.lang.ClassLoader");
32         Object paramValues[] = new Object[1];
33         paramValues[0] = sharedLoader;
34         Method method =
35             startupInstance.getClass().getMethod(methodName, paramTypes);
36         method.invoke(startupInstance, paramValues);
37
38         catalinaDaemon = startupInstance;
39
40     }
工作流程如下:
a) Set up classloaders
commonLoader (common)-> System Loader
sharedLoader (shared)-> commonLoader -> System Loader
catalinaLoader(server) -> commonLoader -> System Loader
b) Load startup class (reflection)
org.apache.catalina.startup.Catalina
setParentClassloader -> sharedLoader
Thread.contextClassloader -> catalinaLoader
c) Bootstrap.daemon.init() complete
第二步: 处理命令行参数 (start, startd, stop, stopd)
类: org.apache.catalina.startup.Bootstrap (假定命令为start)


        try {
String command = "start";
if (args.length > 0) {
command = args[args.length - 1];
}
if (command.equals("startd")) {
args[0] = "start";
daemon.load(args);
daemon.start();
} else if (command.equals("stopd")) {
args[0] = "stop";
daemon.stop();
} else if (command.equals("start")) {
                daemon.setAwait(true);
daemon.load(args);
daemon.start();
} else if (command.equals("stop")) {
daemon.stopServer(args);
} else {
log.warn("Bootstrap: command \"" + command + "\" does not exist.");
}
} catch (Throwable t) {
t.printStackTrace();
}
  

工作流程如下:
a) Catalina.setAwait(true);
b) Catalina.load()


1     public void load() {
2
3         long t1 = System.nanoTime();
4
5         initDirs();
6
7         // Before digester - it may be needed
8
9         initNaming();
10
11         // Create and execute our Digester
12         Digester digester = createStartDigester();
13
14         InputSource inputSource = null;
15         InputStream inputStream = null;
16         File file = null;
17         try {
18             file = configFile();
19             inputStream = new FileInputStream(file);
20             inputSource = new InputSource("file://" + file.getAbsolutePath());
21         } catch (Exception e) {
22             ;
23         }
24         if (inputStream == null) {
25             try {
26                 inputStream = getClass().getClassLoader()
27                     .getResourceAsStream(getConfigFile());
28                 inputSource = new InputSource
29                     (getClass().getClassLoader()
30                      .getResource(getConfigFile()).toString());
31             } catch (Exception e) {
32                 ;
33             }
34         }
35
36         // This should be included in catalina.jar
37         // Alternative: don't bother with xml, just create it manually.
38         if( inputStream==null ) {
39             try {
40                 inputStream = getClass().getClassLoader()
41                 .getResourceAsStream("server-embed.xml");
42                 inputSource = new InputSource
43                 (getClass().getClassLoader()
44                         .getResource("server-embed.xml").toString());
45             } catch (Exception e) {
46                 ;
47             }
48         }
49         
50
51         if ((inputStream == null) && (file != null)) {
52             log.warn("Can't load server.xml from " + file.getAbsolutePath());
53             return;
54         }
55
56         try {
57             inputSource.setByteStream(inputStream);
58             digester.push(this);
59             digester.parse(inputSource);
60             inputStream.close();
61         } catch (Exception e) {
62             log.warn("Catalina.start using "
63                                + getConfigFile() + ": " , e);
64             return;
65         }
66
67         // Stream redirection
68         initStreams();
69
70         // Start the new server
71         if (server instanceof Lifecycle) {
72             try {
73                 server.initialize();
74             } catch (LifecycleException e) {
75                 log.error("Catalina.start", e);
76             }
77         }
78
79         long t2 = System.nanoTime();
80         if(log.isInfoEnabled())
81             log.info("Initialization processed in " + ((t2 - t1) / 1000000) + " ms");
82
83     }
  standardServer.java



1     public void initialize()
2         throws LifecycleException
3     {
4         if (initialized) {
5                 log.info(sm.getString("standardServer.initialize.initialized"));
6             return;
7         }
8         lifecycle.fireLifecycleEvent(INIT_EVENT, null);
9         initialized = true;
10
11         if( oname==null ) {
12             try {
13                 oname=new ObjectName( "Catalina:type=Server");
14                 Registry.getRegistry(null, null)
15                     .registerComponent(this, oname, null );
16             } catch (Exception e) {
17                 log.error("Error registering ",e);
18             }
19         }
20         
21         // Register global String cache
22         try {
23             ObjectName oname2 =
24                 new ObjectName(oname.getDomain() + ":type=StringCache");
25             Registry.getRegistry(null, null)
26                 .registerComponent(new StringCache(), oname2, null );
27         } catch (Exception e) {
28             log.error("Error registering ",e);
29         }
30
31         // Initialize our defined Services
32         for (int i = 0; i < services.length; i++) {
33             services.initialize();
34         }
35     }
  standardService.java



    public void initialize()
throws LifecycleException
{
// Service shouldn't be used with embeded, so it doesn't matter
if (initialized) {
if(log.isInfoEnabled())
log.info(sm.getString("standardService.initialize.initialized"));
return;
}
initialized = true;
if( oname==null ) {
try {
// Hack - Server should be deprecated...
Container engine=this.getContainer();
domain=engine.getName();
oname=new ObjectName(domain + ":type=Service,serviceName="+name);
this.controller=oname;
Registry.getRegistry(null, null)
.registerComponent(this, oname, null);
Executor[] executors = findExecutors();
for (int i = 0; i < executors.length; i++) {
ObjectName executorObjectName =
new ObjectName(domain + ":type=Executor,name=" + executors.getName());
Registry.getRegistry(null, null)
.registerComponent(executors, executorObjectName, null);
}
} catch (Exception e) {
log.error(sm.getString("standardService.register.failed",domain),e);
}

}
if( server==null ) {
// Register with the server
// HACK: ServerFactory should be removed...
            
ServerFactory.getServer().addService(this);
}

// Initialize our defined Connectors
synchronized (connectors) {
for (int i = 0; i < connectors.length; i++) {
                    connectors.initialize();
}
}
}
  connector.java



1     public void initialize()
2         throws LifecycleException
3     {
4         if (initialized) {
5             if(log.isInfoEnabled())
6                 log.info(sm.getString("coyoteConnector.alreadyInitialized"));
7            return;
8         }
9
10         this.initialized = true;
11
12         if( oname == null && (container instanceof StandardEngine)) {
13             try {
14                 // we are loaded directly, via API - and no name was given to us
15                 StandardEngine cb=(StandardEngine)container;
16                 oname = createObjectName(cb.getName(), "Connector");
17                 Registry.getRegistry(null, null)
18                     .registerComponent(this, oname, null);
19                 controller=oname;
20             } catch (Exception e) {
21                 log.error( "Error registering connector ", e);
22             }
23             if(log.isDebugEnabled())
24                 log.debug("Creating name for connector " + oname);
25         }
26
27         // Initializa adapter
28         adapter = new CoyoteAdapter(this);
29         protocolHandler.setAdapter(adapter);
30
31         IntrospectionUtils.setProperty(protocolHandler, "jkHome",
32                                        System.getProperty("catalina.base"));
33
34         try {
35             protocolHandler.init();
36         } catch (Exception e) {
37             throw new LifecycleException
38                 (sm.getString
39                  ("coyoteConnector.protocolHandlerInitializationFailed", e));
40         }
41     }
  Http11Protocol.java初始化



1     public void init() throws Exception {
2         endpoint.setName(getName());
3         endpoint.setHandler(cHandler);
4
5         // Verify the validity of the configured socket factory
6         try {
7             if (isSSLEnabled()) {
8                 sslImplementation =
9                     SSLImplementation.getInstance(sslImplementationName);
10                 socketFactory = sslImplementation.getServerSocketFactory();
11                 endpoint.setServerSocketFactory(socketFactory);
12             } else if (socketFactoryName != null) {
13                 socketFactory = (ServerSocketFactory) Class.forName(socketFactoryName).newInstance();
14                 endpoint.setServerSocketFactory(socketFactory);
15             }
16         } catch (Exception ex) {
17             log.error(sm.getString("http11protocol.socketfactory.initerror"),
18                       ex);
19             throw ex;
20         }
21
22         if (socketFactory!=null) {
23             Iterator<String> attE = attributes.keySet().iterator();
24             while( attE.hasNext() ) {
25                 String key = attE.next();
26                 Object v=attributes.get(key);
27                 socketFactory.setAttribute(key, v);
28             }
29         }
30         
31         try {
32             endpoint.init();
33         } catch (Exception ex) {
34             log.error(sm.getString("http11protocol.endpoint.initerror"), ex);
35             throw ex;
36         }
37         if (log.isInfoEnabled())
38             log.info(sm.getString("http11protocol.init", getName()));
39
40     }
  JIoEndpoint.java
  * Handle incoming TCP connections.
*
* This class implement a simple server model: one listener thread accepts on a socket and
* creates a new worker thread for each incoming connection.
*
* More advanced Endpoints will reuse the threads, use queues, etc.



1     public void init()
2         throws Exception {
3
4         if (initialized)
5             return;
6         
7         // Initialize thread count defaults for acceptor
8         if (acceptorThreadCount == 0) {
9             acceptorThreadCount = 1;
10         }
11         if (serverSocketFactory == null) {
12             serverSocketFactory = ServerSocketFactory.getDefault();
13         }
14         if (serverSocket == null) {
15             try {
16                 if (address == null) {
17                     serverSocket = serverSocketFactory.createSocket(port, backlog);
18                 } else {
19                     serverSocket = serverSocketFactory.createSocket(port, backlog, address);
20                 }
21             } catch (BindException be) {
22                 if (address == null)
23                     throw new BindException(be.getMessage() + "<null>:" + port);
24                 else
25                     throw new BindException(be.getMessage() + " " +
26                             address.toString() + ":" + port);
27             }
28         }
29         //if( serverTimeout >= 0 )
30         //    serverSocket.setSoTimeout( serverTimeout );
31         
32         initialized = true;
33         
34     }
  

b1) initDirs() -> set properties like
catalina.home
catalina.base == catalina.home (most cases)
b2) initNaming
setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
org.apache.naming.java.javaURLContextFactory ->default)
b3) createStartDigester()
Configures a digester for the main server.xml elements like
org.apache.catalina.core.StandardServer (can change of course :)
org.apache.catalina.deploy.NamingResources
Stores naming resources in the J2EE JNDI tree
org.apache.catalina.LifecycleListener
implements events for start/stop of major components
org.apache.catalina.core.StandardService
The single entry for a set of connectors,
so that a container can listen to multiple connectors
ie, single entry
org.apache.coyote.tomcat5.CoyoteConnector
Connectors to listen for incoming requests only
It also adds the following rulesets to the digester
NamingRuleSet
EngineRuleSet
HostRuleSet
ContextRuleSet
b4) Load the server.xml and parse it using the digester
Parsing the server.xml using the digester is an automatic
XML-object mapping tool, that will create the objects defined in server.xml
Startup of the actual container has not started yet.
b5) Assigns System.out and System.err to the SystemLogHandler class
b6) Calls initialize on all components, this makes each object register itself with the
JMX agent.
During the process call the Connectors also initialize the adapters.
The adapters are the components that do the request pre-processing.
Typical adapters are HTTP1.1 (default if no protocol is specified,
org.apache.coyote.http11.Http11Protocol)
AJP1.3 for mod_jk etc.

  
  
  

运维网声明 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-97644-1-1.html 上篇帖子: tomcat源码分析 catalina load 过程 下篇帖子: Tomcat embed
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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

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

扫描微信二维码查看详情

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


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


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


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



合作伙伴: 青云cloud

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