Tomcat Architecture Analysis

Source: Internet
Author: User

Although I have analyzed the source code, I have never had time to paste it with others.

 

Tomcat source code analysis (startup Framework)
Preface:
This article is some of my experiences after reading the Tomcat source code.
It mainly explains the Tomcat System Framework and startup process. If you have any mistakes, please criticize them!
Suggestion:
After all, the Tomcat framework is still complicated,
It is not easy to understand the Tomcat framework from the perspective of text. Therefore, you must practice, practice, and practice again. We recommend that you download the Tomcat source code and debug it,
Then, track the startup process in one step. If you have any questions, refer to this article to see if it is helpful. I believe that the effect and learning speed will be much better!

1.
Overall framework structure of Tomcat
The basic framework of Tomcat is divided into four layers.
Top level elements:

Server
Service
Connector
HTTP
AJP

Container
Engine
Host
Context
Component

Manager
Logger
Loader
Pipeline
Valve

...
Servers and services are on the top of the framework.
Server: it is actually the backgroud program,
The server in Tomcat is used to start and listen to server events (such as restart and close commands. In the standard tomcat configuration file server. XML,
We can see "<server port =" 8005 "shutdown =" shutdown"
DEBUG = "0"> "shutdown" is the command used by the server to listen to server events)
Service:
In tomcat, service is a solution to a type of problems. Usually we use the tomcat-standalone provided by Tomcat by default.
Service. In this way, the service not only provides us with parsing JSP and Servlet services, but also provides us with parsing static text services.


Connector: Tomcat handles problems in the container, and where does the container obtain the input information?
Connector is dedicated
This. It encapsulates the data passed from the socket into a request and passes it to the container for processing.

We usually use two types of ctor, called HTTP connectoer, to pass HTTP requests. The other is AJP,
When we integrate Apache and tomcat, Apache and tomcat interact through this protocol.
(When talking about the integration of Apache and tomcat, we usually aim to get apache static resources,
Let Tomcat parse dynamic JSP or servlet .)
Container: When HTTP
When connector transmits the requirement to the top-level container: Engin, our line of sight should be moved to the container layer.

At the container layer, we have three types of containers: Engin, host, and context.
Engin:
After receiving the request passed by the service, the service returns the result to the service
This media interacts with engin ).
HOST: engin does not process the request received by the service itself,
Instead, it is handed over to the appropriate host for processing.
Host is the meaning of a virtual host. Generally, we only use one host, that is, "localhost.

Context: After the host receives a request from the host, it will not be processed by itself, but it will be handled by the appropriate context.
For example:
<Http: // 127.0.0.1: 8080/Foo/index. jsp
>

<Http: // 127.0.1: 8080/BAR/index. jsp
>

The former is handed over to the context of Foo for processing, and the latter to the context of bar for processing.
Obviously!
Context is actually a web app.
We usually do this configuration in server. xml.

<Context Path = "/foo" docbase = "D:/project/Foo/Web"/>

The context container is used to do what we should do.

Compenent: Next,
Let's continue with the usage of component.
First, we need to understand the relationship between containers and components.
The requirement is passed to the container,
When appropriate, it is passed to the next container for processing.
The container contains a variety of components, which can be understood as providing a variety of value-added services.

MANAGER: when the Manager component is installed in a container, the container supports session management. In fact, session management is performed in Tomcat,
The Manager component is installed in the context.
Logger: When the logger component is installed in a container,
What happened in this container is recorded by this component! We usually see catalina_log.time.txt and
Localhost.time.txt and localhost_examples_log.time.txt. This is because we are: Engin,
Host and context (examples) containers are installed with the logger component, which is also the default installation, also known as the standard :)
Loader:
The loader component is usually used only for our context container,
Loader is used to start the context and manage the classloader of this context.
Pipline:
Pipeline is such a thing. When a container decides to deliver the requirements passed from the upper level to the sub-container,
He puts this requirement in the pipeline of the container. When the requests flow in the pipeline, they will be intercepted by various valves in the pipeline.
For example, two valves are placed in the pipe. The first valve is called "access_allow_vavle". That is to say, when the demand flow is over, it will check the IP address of the demand,
If this IP address is already in the blacklist, sure, kill! The second valve is called defaul_access_valve, which performs routine checks,
If yes, OK to pass the requirement to the sub-container of the current container. In this way, the requirement is passed in each container, flows, and finally reaches the destination.

Valve: the valve mentioned above.
Tomcat is something like this,
We can simply understand the Tomcat framework in this way. It is a top-down structure that contains sub-containers.
2. Tomcat Startup Process

This article describes how to start Tomcat. Since we have a general understanding of the Framework Structure of Tomcat, we can guess how to start Tomcat in the hope of business,
The parent container is started first, and then the sub-containers in the parent container are started one by one. When a container is started, the component installed on it is started. When all components are started,
When all containers are started, Tomcat itself is started.
Naturally, we can also guess That tomcat startup will be divided into two parts,
The first step is assembly. Step 2: start the job.
The Assembly is to install sub-containers for the parent container and install components for each container.
In this place we will use digester mode, as for Digester mode what, what is used, how to work. Please refer to >

After the Assembly is started, once the Assembly is successful, we only need to ignment the top wire, and the entire Tomcat will be activated.
This is just like when we want to drive a car that has already been assembled. We just need to insert the key into the key hole, twist it, the engine of the car will start up, and the air conditioner will start up, the security device will take effect,
As a result, the car was launched. (This process is indeed merged with the Tomcat startup process, so we have to doubt it.
Tomcat is developed in Java at GE ).
2.1 interesting names:
Catalina
Tomcat

Bootstrap
Engin
Host
Context
They are very interesting:

Catalina: long-range bomber
Tomcat: pandatv --
A type of Bomber (this reminds me of the pandatv mobile phone that is proud of Chinese people. Can it be called tomcat in English ??? And reminds me of another advertisement:
Waveguide-fighters in mobile phones and fighters in Boeing-aircraft planes)
Bootstap: boot
Engin: Engine
Host:
Host, territory
Context: content, target, and context

... After many years, modern humans have been extinct.
The post-modern creature found these words scattered in one piece. A wise guy has translated these things:
Under the guidance of ground service personnel (bootstrap,
Catalina jumped up, far from being a panda bomber (Tomcat! With excellent engine technology (engin ),
The pandatv bomber flew over the enemy's territory and targeted the context and threw a nuclear warhead destroying the earth ~ Modern life is like this ~
 

To sum up, it makes us think that GE is also involved in the production of military equipment?
Oppose American imperialism! We are opposed to US hegemony! Long live peace! Long live freedom!


The history of 2.2 is so amazing!
Tomcat is started from the org. Apache. Catalina. startup. Bootstrap class!

Two things are done in Bootstrap:
1. Three types of classloader are specified:
Commonloader:
Common/classes, common/lib, common/endorsed
Catalinaloader:
Server/classes, server/lib, and commonloader
Sharedloader:
Shared/classes, shared/lib, and commonloader
2. Boot Catalina.

Use reflection technology to call the process method of org. Apache. Catalina. startup. Catalina and pass the parameters in the past.


2.3 Catalina. Java
Catalina has completed several important tasks:
1.
Use digester technology to assemble Tomcat containers and components.
1.1 The main content of the assembly work is to install various major components.
For example, what kind of servcie is available under the server. The number of contexts that a host can contain. Which components are used by context.

1.2 at the same time, mbeans configuration has been completed in the assembly process. Here, I briefly but not very accurately describe what mbean is and what it uses.

We have created our own objects and managed them by ourselves! But what if we create an object and want others to manage it? I want to at least tell others what we all have,
And how can I find it! JMX technology provides us with a means. JMX has three main features. Mbean, agent, connector.

Mbean: used to map our objects. Maybe mbean is the object we created, maybe not, but with it, we can reference our object.

AGENT: You can find mbean.
Connector: Method of connecting to the agent. It can be HTTP,
It can also be RMI or directly through socket.
What happens during Tomcat assembly:
The initialization of the globalresourceslifecyclelistener class will be triggered:
Protected static
Registry registry = mbeanutils. createregistry (); will run

Mbeanutils. createregistry ()
Mbeans will be created based on the configuration file/org/Apache/Catalina/mbeans/mbeans-descriptors.xml.
OK. You can access all components in Tomcat from the outside. (A bit like a backdoor)
2. initialize the top-level server.
In fact, it is usually configured to the Service's two ctor. (HTTP, AJP)
3. Start from the container server,
Ignite the entire tomcat.
4. Create a hook program for the server to check that when the server is shut down,
Disable Tomcat containers.
5. Listen to port 8005. If "shutdown" is sent (the default cultivation string,
Disable 8005 serversocket.
2.4 start various containers
1. Server

Before the server container is started (before_start), start (start), and after_start (after_start,
And run the corresponding event processor.
Start the sub-container of the server: servcie.
2. Service

Sub-container for starting service: engin
Start Connector
3. engin

At the engin level and below, Tomcat uses a consistent startup method.
First,
Run specific tasks of each container
Then, the pre-startup event is triggered.
Immediately, set the label to indicate that the container has been started.

Next, start various components in the container: loader, logger, Manager, etc.

Then, start the mapping component. (Note 1)
Followed by the promoter container.
Next, start the pipeline of the container (pipline)

Then, trigger the startup event
Finally, the post-startup event is triggered.
 
Engin will roughly do this,
Generally, the host will do the same, while the context will do the same. Obviously, we need to use the code reuse technology here.
Tomcat uses abstract classes to handle this problem. Containerbase. Finally, the code that completes complex functions is neat,
Able and refreshing, it is really amazing, fine products come, intuition like Jia Zhen, another tooth cheek fragrance, nostalgia round-trip ah!


Before engin is triggered, the only listener: enginconfig bound to engin is activated.

Basically, this enginconfig class does not do anything, that is, it sets the debug level of enginconfig to the same as that of Engin. The other is to output several lines of text,
This indicates that engin has been configured and has not done any substantive work.
NOTE 1: The mapping component is useful,
When a requirement is transferred from the parent container to the sub-container, and the parent container has multiple sub-containers, which sub-container should be selected to handle the requirement? This is caused by mapping
Component.

4. Host
Same as engin,
The START () method in containerbase is also called, but some self-owned tasks have been done before, that is, to the channel (pipline) of the host container,
Installed
"Org. Apache. Catalina. Valves. errorreportvalve" valve.

The purpose of this valve is as follows: after the requirement is passed to the host by Engin, it will continue to be passed to the context for specific processing.
The requirement here is actually the request and response passed as the parameter. Therefore, after the context completes processing the requirement, the response is usually changed.
However, the role of org. Apache. Catalina. Valves. errorreportvalve is to check whether the response contains errors,
If yes, perform corresponding processing.
5. Context
Here,
Finally, it turned to the real drama of Tomcat startup, and started context.
Standardcontext. Start ()
The method for starting the context container is called by standardhost.
5.1 webappresources
The specific directory to which the context points
5.2 concontex is installed. defacontext context is the default context.
If defaultcontext is installed under a host and a database connection pool resource is installed in defaultcontext.
All other context under the host can directly use the database connection pool without additional configuration.
5.3 specify loader.
Generally, the default org. Apache. Catalina. loader. webapploader class is used.
Loader is used to specify the classes and jar packages used in this context.
5.4 specify manager.
Generally, the default org. Apache. Catalina. session. standardmanager is used.
Manager is used to manage sessions.
In fact, session management is also well implemented. Take a simple session management as an example.
When the request is passed, there is a sessionid attribute in the request object. OK. After obtaining this sessionid,
We can use it as the key of the map, and we can place the value in a hashmap. hashmap, and then put what we want to put.
5.5
There is a work directory under postworkdirectory (). tomcat. We threw all the temporary files there. This step is to create a directory there.
Generally, a directory is generated in % catalina_home %/work/standalone/localhost.
5.6
Binding thread. Here, Class Loader swaps should occur. We can see all the classes and Lib in Tomcat before.
Next we need to see the class under the current context. Therefore, you need to set contextclassloader,
At the same time, we need to record the old classloader because it will be used later.
5.7 start loader.
Specify the specific classes and jar files used in the context. If reloadable is set to true,
A thread is started to monitor the changes in classes, and context is restarted if there is a change.
5.8 start Logger
5.9
Triggers a listener installed on it.
Lifecycle. firelifecycleevent (start_event, null );
Work
As one of the listeners, contextconfig will be started. contextconfig is used to configure web. xml.
For example, how many servlets and filters are contained in the context are installed in the context.
5.9.1
Defaultconfig. The tomcat/CONF/Web. xml file must be configured for each context.
5.9.2
Applicationconfig configure your own WEB-INF/Web. xml file
5.9.3
Validatesecurityroles permission verification. Normally we are accessing/admin
Or/manager, the user must be either admin or manager to access. In addition, we can restrict the resources that can be accessed, but which cannot.
All are implemented here.
5.9.4 tldscan: Tag lab)
5.10 start Manager
5.11
Postwelcomefiles:
Index.html#index.htm, index. jsp
It is bound to the context by default.
5.12 listenerstart configure listener
5.13
Filterstart: Configure Filter
5.14
Start a servlet with <load-on-startup> 1 </load-on-startup>.
 
The order is from small to large: 1, 2, 3... Last 0
By default, at least three servlets are started:
 
Org. Apache. Catalina. servlets. DefaultServlet
Servlet for processing static resources.
What images? HTML? CSS? JS? Look for him?
 
Org. Apache. Catalina. servlets. invokerservlet
No servlet is processed
Those servlets of mapping.
Org. Apache. Jasper. servlet. jspservlet

Process.
5.15 The context has been started.
How many steps have you taken,
Context is finally started.
OK! Here, each container and component is started. Tomcat has finally worked tirelessly to serve the people!
3.
References:
Http://jakarta.apache.org/tomcat/
>

Http://www.onjava.com/pub/a/onjava/2003/05/14/java_webserver.html
>


4. Postscript
This article explains the Tomcat startup framework and the details of the Message Processing Process in Tomcat.
The content of the article has been written and is being sorted out. I believe it will soon be possible for everyone to study and make progress together.

This article is written by analyzing the Tomcat source code on its own, so there must be a personal subjective color,
There will inevitably be a one-sided aspect. If there are any mistakes, please criticize and advise. This will not only allow the younger siblings who have just started to study tomcat to take a detour, but also allow me to learn something.

Email: sojan_java@yahoo.com.cn

5. Tomcat
Source code analysis (Message Processing)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.