IIS Architecture , A history
IIS Architecture
IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is used to host your ASP.NET Web application. IIS has it's own ASP.NET Process Engine to handle the ASP.NET request. So, when a request comes from client to server, IIS takes that request and process it and send response back to clients.
Request Processing :
Now let’s have a look how they do things internally. Before we move ahead, you have to know about two main concepts
1. WorkerProcess
2. Application Pool
Worker Process:
Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system. All the ASP.Net functionality runs under the scope of worker process.
When a request comes to the server from a client worker process is responsible to generate the request and response.
In a single word we can say worker process is the heart of ASP.NET Web Application which runs on IIS.
Application Pool: Application pool is the container of worker process. Application pools are used to separate sets of IIS worker processes that share the same configuration. Application pools enable a better security, reliability, and availability for any web application.
The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected.
This makes sure that a particular web application doesn't not impact other web application as they are configured into different application pools.
Application Pool with multiple worker process is called “Web Garden”.
Now, I have covered all the basic stuff like Web server, Application Pool, Worker process. Now let’s have look how IIS process the request when a new request comes up fromclient.
If we look into the IIS 6.0 Architecture, we can divided them into Two Layer
1. KernelMode
2. User Mode
Now, Kernel mode is introduced with IIS 6.0, which contains the HTTP.SYS. So whenever a request comes from Client to Server, it will hit HTTP.SYS First.
Now, HTTP.SYS is Responsible for pass the request to particular Application pool. Now here is one question, How HTTP.SYS comes to know where to send the request? This is not a random pickup. Whenever we creates a new Application Pool, the ID of the Application Pool is being generated and it’s registered with the HTTP.SYS. So whenever HTTP.SYS Received the request from any web application, it checks for the Application Pool and based on the application pool it send the request.
So, this was the first steps of IIS Request Processing.
Till now, Client Requested for some information and request came to the Kernel level of IIS means at HTTP.SYS. HTTP.SYS has been identified the name of the application pool where to send. Now, let’s see how this request moves from HTTP.SYS to Application Pool.
In User Level of IIS, we have Web Admin Services (WAS) which takes the request from HTTP.SYS and pass it to the respective application pool.
When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process “w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds the mapping into IIS.
Note : Sometimes if we install IIS after installing asp.net, we need to register the extension with IIS using aspnet_regiis command.
When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.
When this methods called, a new instance of HTTPContext is been created. Which is accessible using HTTPContext.Current Properties. This object still remains alive during life time of object request. Using HttpContext.Current we can access some other objects like Request, Response, Session etc.
After that HttpRuntime load an HttpApplication object with the help of HttpApplicationFactory class.. Each and every request should pass through the corresponding HTTPModule to reach to HTTPHandler, this list of module are configured by the HTTPApplication.
Now, the concept comes called “HTTPPipeline”. It is called a pipeline because it contains a set of HttpModules ( For Both Web.config and Machine.config level) that intercept the request on its way to the HttpHandler. HTTPModules are classes that have access to the incoming request. We can also create our own HTTPModule if we need to handle anything during upcoming request and response.
HTTP Handlers are the endpoints in the HTTP pipeline. All request that are passing through the HTTPModule should reached to HTTPHandler. Then HTTP Handler generates the output for the requested resource. So, when we requesting for any aspx web pages, it returns the corresponding HTML output.
All the request now passes from httpModule to respective HTTPHandler then method and the ASP.NET Page life cycle starts. This ends the IIS Request processing and start the ASP.NET Page Lifecycle.
Isolation level
IIS has three level of isolation:-
LOW (IIS process):- In this main IIS process and ASP.NET application run in same process.
So if any one crashes the other is also affected. Example let’s say (well this is not possible)
I have hosted yahoo, hotmail .Amazon and Google on a single PC. So all application and
the IIS process runs on the same process. In case any website crashes it affects everyone.
Figure: - 7.3 LOW IIS process scenario
Medium (Pooled):- In Medium pooled scenario the IIS and web application run in different
process. So in this case there are two processes process1 and process2. In process1 the IIS
process is running and in process2 we have all Web application running.
Figure: - 7.4 Medium pooled scenario
High (Isolated):-In high isolated scenario every process is running is there own process. In
below figure there are five processes and every one handling individual application. This
consumes heavy memory but has highest reliability.
Figure: - 7.5 High isolation scenario
ISAPI
The Internet Server Application Programming Interface (ISAPI) is an N-tier API of Internet Information Services (IIS),
ISAPI consists of two components: Extensions and Filters.
Extensions
ISAPI Extensions are true applications that run on IIS. They have access to all of the functionality provided by IIS. ISAPI extensions are implemented as DLLs that are loaded into a process that is controlled by IIS. Clients can access ISAPI extensions in the same way they access a static HTML page.
ASP.NET is an ISAPI extension under the Web server.
Filters
ISAPI filters are used to modify or enhance the functionality provided by IIS. They always run on an IIS server and filter every request until they find one they need to process. Filters can be programmed to examine and modify both incoming and outgoing streams of data. Internally programmed and externally configured priorities determine in which order filters are called
Common tasks performed by ISAPI filters include:
Changing request data (URLs or headers) sent by the client
Controlling which physical file gets mapped to the URL
Controlling the user name and password used with anonymous or basic authentication
Modifying or analyzing a request after authentication is complete
Modifying a response going back to the client
Running custom processing on "access denied" responses
Running processing when a request is complete
Run processing when a connection with the client is closed
Performing special logging or traffic analysis.
Performing custom authentication.
Handling encryption and compression.
If a file name extension has not been mapped to ASP.NET, ASP.NET will not receive the request. This is important to understand for applications that use ASP.NET authentication. For example, because .htm files are typically not mapped to ASP.NET, ASP.NET will not perform authentication or authorization checks on requests for .htm files. Therefore, even if a file contains only static content, if you want ASP.NET to check authentication, create the file using a file name extension mapped to ASP.NET, such as .aspx.
Process
When we launch the Notepad program in Windows, the program executes inside of a container known as a process. We can launch multiple instances of Notepad, and each instance will run in a dedicated process. Using the Task Manager application, we can see a list of all processes currently executing in the system.
A process contains the executable code and data of a program inside memory it has reserved from the operating system. There will be at least one thread executing instructions inside of the process, and in most cases there are multiple threads. If the program opens any files or other resources, those resources will belong to the process.
A process is also boundary. Erroneous code inside of a process cannot corrupt areas outside of the current process. It is easy to communicate inside of a process, but special techniques are required to communicate from one process to another. Each process also runs under a specific security context which can dictate what the process can do on the machine and network.
A process is the smallest unit of isolation available on the Windows operating system. This could pose a problem for an ISP who wants to host hundreds of ASP.NET applications on a single server. The ISP will want to isolate each ASP.NET application to prevent one application from interfering with another company’s application on the same server, but the relative cost of launching and executing a process for hundreds of applications may be prohibitive.
A process is an isolated container where the resources needed to run a program are stored. Each process gets its own virtual address space and no process can access another processes memory. On a 32bit Windows system each process has access a maximum of 3GB of memory depending on how the application was built, the version of Windows and how much memory Windows is currently using. On a 64bit system this RAM limit is raised significantly and will be limited more by the software than the hardware for example Windows 7 will limit this to 192GB whereas Windows Server 2008 will go up to 2TB.
Application domains sit inside the process your .Net application is running in they can be created and destroyed at runtime and exist to put isolation boundaries around certain areas of your code. Code running in one application domain has no direct access to code running in another although they can still communicate via marshaling. If one application domain throws an unhandled exception then only that domain will go down and any other application domains in the process will carry on as they were.
App Domain
Before get into App domain let me ask a question,
You’ve created two ASP.NET applications on the same server, and have not done any special configuration.
What is happening?
A single ASP.NET worker process will host both of the ASP.NET applications. On Windows XP and Windows 2000 this process is named aspnet_wp.exe, and the process runs under the security context of the local ASPNET account. On Windows 2003 the worker process has the name w3wp.exe and runs under the NETWORK SERVICE account by default.
When 10 users browse a page (say, login.aspx) in a published website, ASP.Net Worker Process (w3wp.exe) creates 10 application domains to host the page assembly into it for each client, thus creates 10 AppDomains.
The AppDomain is managed by .net framework but process is managed by the operating system (which is slower)
Like a process, the AppDomain is both a container and a boundary. The .NET runtime uses an AppDomain as a container for code and data, just like the operating system uses a process as a container for code and data. As the operating system uses a process to isolate misbehaving code, the .NET runtime uses an AppDomain to isolate code inside of a secure boundary.
An AppDomain belongs to only a single process, but single process can hold multiple AppDomain. An AppDomain is relatively cheap to create (compared to a process), and has relatively less overhead to maintain than a process. For these reasons, an AppDomain is a great solution for the ISP who is hosting hundreds of applications. Each application can exist inside an isolated AppDomain, and many of these AppDomain can exist inside of a single process – a cost savings.
AppDomain and you
An object lives in one AppDomain. Each ASP.NET application will have its own set of global variables: Cache, Application, and Session objects are not shared. Even though the code for both of the applications resides inside the same process, the unit of isolation is the .NET AppDomain. If there are classes with shared or static members, and those classes exist in both applications, each AppDomain will have its own copy of the static fields – the data is not shared. The code and data for each application is safely isolated and inside of a boundary provided by the AppDomain
In order to communicate or pass objects between AppDomain, you’ll need to look at techniques in .NET for communication across boundaries, such as .NET Remoting or web services.
Note again: the one caveat to the idea of an AppDomain as a boundary is that ASP.NET applications will run with full trust by default. Fully trusted code can execute native code, and native code can essentially have access to anything inside the process. You’ll need to run applications with partial trust to restrict access to unmanaged code and verify all managed code to secure AppDomains.
Shadow Copies and Restarts
Once an assembly is loaded into an AppDomain, there is no way to remove the assembly from the AppDomain. It is possible, however, to remove an AppDomain from a process.
If you copy an updated dll into an application’s bin subdirectory, the ASP.NET runtime recognizes there is new code to execute. Since ASP.NET cannot swap the dll into the existing AppDomain, it starts a new AppDomain. The old application domain is “drain stopped”, that is, existing requests are allowed to finish executing, and once they are all finished the AppDomain can unload. The new AppDomain starts with the new code and begins taking all new requests.
Typically, when a dll loads into a process, the process locks the dll and you cannot overwrite the file on disk. However, AppDomains have a feature known as Shadow Copy that allows assemblies to remain unlocked and replaceable on disk.
The runtime initializes ASP.NET with Shadow Copy enabled for the bin directory. The AppDomain will copy any dll it needs from the bin directory to a temporary location before locking and loading the dll into memory. Shadow Copy allows us to overwrite any dll in the bin directory during an update without taking the web application offline.
Master Of Your Domain
Application domains replace the OS process as the unit of isolation for .NET code. An understanding of application domains will give you an idea of the work taking place behind the scenes of an ASP.NET application. Using the Current Domain property of the AppDomain class you can inspect properties about the AppDomain your code is executing in, including the Shadow Copy settings we discussed in this article.
Creating Application Domain:
A common language runtime host creates application domains automatically when they are needed. However, you can create your own application domains and load into them those assemblies that you want to manage personally. You can also create application domains from which you execute code.
You create a new application domain using one of the overloaded CreateDomain methods in the System.AppDomain class. You can give the application domain a name and reference it by that name.
The following example creates a new application domain, assigns it the name MyDomain, and then prints the name of the host domain and the newly created child application domain to the console.
using System;
using System.Reflection;
class AppDomain1
{
public static void Main()
{
Console.WriteLine("Creating new AppDomain.");
AppDomain domain = AppDomain.CreateDomain("MyDomain");
Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
Console.WriteLine("child domain: " + domain.FriendlyName);
}
}
How to: Unload an Application Domain
When you have finished using an application domain, unload it using the System.AppDomain.Unload method. The Unload method gracefully shuts down the specified application domain. During the unloading process, no new threads can access the application domain, and all application domain–specific data structures are freed.
Assemblies loaded into the application domain are removed and are no longer available. If an assembly in the application domain is domain-neutral, data for the assembly remains in memory until the entire process is shut down.
using System;
using System.Reflection;
class AppDomain2
{
public static void Main()
{
Console.WriteLine("Creating new AppDomain.");
AppDomain domain = AppDomain.CreateDomain("MyDomain", null);
Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
Console.WriteLine("child domain: " + domain.FriendlyName);
AppDomain.Unload(domain);
try
{
Console.WriteLine();
Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
// The following statement creates an exception because the domain no longer exists.
Console.WriteLine("child domain: " + domain.FriendlyName);
}
catch (AppDomainUnloadedException e)
{
Console.WriteLine(e.GetType().FullName);
Console.WriteLine("The appdomain MyDomain does not exist.");
}
}
}
How to: Configure an Application Domain
You can provide the common language runtime with configuration information for a new application domain using the AppDomainSetup class. When creating your own application domains, the most important property is ApplicationBase. The other AppDomainSetup properties are used mainly by runtime hosts to configure a particular application domain.
The Application Base property defines the root directory of the application. When the runtime needs to satisfy a type request, it probes for the assembly containing the type in the directory specified by the Application Base property.
using System;
using System. Reflection;
class AppDomain4
{
public static void Main()
{
// Create application domain setup information.
AppDomainSetup domaininfo = new AppDomainSetup ();
domaininfo.ApplicationBase = "f:\\work\\development\\latest";
// Create the application domain.
AppDomain domain = AppDomain.CreateDomain("MyDomain", null, domaininfo);
// Write application domain information to the console.
Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
Console.WriteLine("child domain: " + domain.FriendlyName);
Console.WriteLine("Application base is: " + domain.SetupInformation.ApplicationBase);
// Unload the application domain.
AppDomain.Unload(domain);
}
}
Retrieving Setup Information from an Application Domain
Each instance of an application domain consists of both properties and AppDomainSetup information. You can retrieve setup information from an application domain using the System.AppDomain class. This class provides several members that retrieve configuration information about an application domain.
You can also query the AppDomainSetup object for the application domain to obtain setup information that was passed to the domain when it was created.
The following example creates a new application domain and then prints several member values to the console.
class AppDomain3
{
Public static void Main ()
{
// create the new application domain.
AppDomain domain = AppDomain.CreateDomain("MyDomain", null);
// Output to the console
Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
Console.WriteLine("New domain: " + domain.FriendlyName);
Console.WriteLine("Application base is: " + domain.BaseDirectory);
Console.WriteLine("Relative search path is: " + domain.RelativeSearchPath);
Console.WriteLine("Shadow copy files is set to: " + domain.ShadowCopyFiles);
AppDomain.Unload(domain);
}
}
Load assemblies in App Domain
Using System;
Using System. Reflection;
Public class Asmload0
{
Public static void Main ()
{
// Use the file name to load the assembly into the current
// application domain.
Assembly a = Assembly. Load ("example");
// Get the type to use
Type myType = a.GetType ("Example");
// Get the method to call.
MethodInfo myMethod = myType.GetMethod ("MethodA");
// create an instance.
Object obj = Activator.CreateInstance (myType);
// execute the methods
myMethod.Invoke (obj, null);
}
}
Http Runtime
Http Application
Http Handler
HttpHandler - The Extension Based Preprocessor
Http Handlers and Http Modules are used by ASP.Net for handling requests. Whenever the IIS server receives a request it looks for an ISAPI filter that capable of handling request (aspnet_ISAPI.dll).
Same kind of process happens when an ASP.NET page is triggered. It looks for Http Handler in the Web.Config files for any request setting.
As in machine.config default setting, the .aspx files are mapped to PageHandlerFactory, and the .asmx files are mapped to the WebServiceHandlerFactory.
There are many requests processed by ASP.NET in this cycle, like BeginRequest, AuthenticateRequest, AuthorizeRequest, AcquireRequestState, ResolveRequestCache, Page Constructor, PreRequestHandlerExecute, Page.Init, Page.Load, PostRequestHandlerExecute, ReleaseRequestState, UpdateRequestCache, EndRequest, PreSendRequestHeaders, PreSendRequestContent.
Yes, the Http Handler may be used to upload files.
Http Modules
Http Modules are components of .NET that implement the System.Web.IHttpModule interface.
These components register for some events and are then invoked during the request processing. It
implements the Init and the Dispose methods. HttpModules has events like
<b>AcquireRequestState, AuthenticateRequest, AuthorizeRequest, BeginRequest, Disposed
, EndRequest, Error, PostRequestHandlerExecute, PreRequestHandlerExecute, PreSendRequestHeaders,
ReleaseRequestState, ResolveRequestCache, UpdateRequestCache
Http Context
Application Life cycle
Thanks
ReplyDelete