您的位置:首页 > 运维架构 > Tomcat

tomcat源码分析(二)启动---Debug方式

2013-08-02 11:31 525 查看
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[i] instanceof Lifecycle)
46                     ((Lifecycle) connectors[i]).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[i] instanceof Lifecycle)
35                 ((Lifecycle) children[i]).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[i]))
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[i] instanceof Lifecycle)
((Lifecycle) connectors[i]).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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: