Monitor server processes

Source: Internet
Author: User
Monitor server processes

Kent Sharkey
Microsoft Corporation

 

Applicable:
Microsoft ASP. NET

Abstract:Learn how to create an ASP. Net HTTP handler to view the running and closing status of the processes used by the web site. In addition, you will learn how to create a configuration section handler (this article contains links to an English site ).

Download the Visual C # version of processhandlercs. MSI.

Download the Visual Basic version of processhandlervbsample. MSI. (Note that in the example file, the comments of programmers are in English. In this document, the comments are translated into Chinese to facilitate your understanding .)

Directory

Introduction
What do we see?
Create process view Handler
Implement ihttphandler
Install the HTTP handler
Add Configuration
Summary

Product Introduction

Have you ever seen a good coffee shop assistant deliver coffee? The coffee beans, steam, milk, and coffee drinks are dancing in the wonderful ballet, jumping to the anxious customers. However, even the best salesclerk occasionally has problems. For example, if the two lists are mixed during processing, the result is a soy latte before you. It may also be that the sloppy handwriting on the cup is wrong, or the clerk understands it wrong. Someone asked for a cup of "Ke gaoqiuo", and the poor clerk racked his brains and wondered what the customer really wanted. If a similar problem occurs, stop the processing and start again. A good waiter may postpone the existing requirements, but a good waiter can do this without notice.

Microsoft ASP. NET has made great improvements over any of its competitors in terms of system reliability. However, like the good clerk, ASP. NET occasionally suffers problems. Fortunately, ASP. NET is a very good server. It can quickly generate new processes in the background and then process requests. Generally, only a slight latency that the user may not even notice will occur when requesting the page.

The administrator of ASP. NET may need to know what happened. They also want to know why the process failed. Fortunately, you can use the processinfo and processmodelinfo classes in the. NET Framework class library documentation to obtain relevant information. In this article, we will learn how to create an ASP. Net HTTP handler to use these objects to view the running and closing status of the processes used by the web site. In addition, we will create a configuration section handler so that we can configure the handler after installing it.

What do we see?

ASP. NET processes compile and manage all requests made to ASP. NET pages. Ideally, this process should always exist on the server: actively receiving requests, compiling pages, and returning HTML. However, because there are many potential events that may affect the process, we have to face the real situation of web development. Developers may fail to properly handle memory leaks or thread issues, the server may lose connection to the process, or even cause problems in the web. in the <processmodel> element section of the config file, the idletimeout, requestlimit, memorylimit, and similar projects are incorrectly configured, resulting in problems. If any of the above events occurs, a new ASP. NET auxiliary process will be created, and a new request will be handed over to this process for processing.

As ASP. NET processes are so important to page processing, it is equally important to monitor these processes. You can use the processinfo and processmodelinfo classes to view the validity period and running status of the current and previous processes. Figure 1 shows the list of processes created in this document.

Figure 1: Web server process history

Processinfo class stores the data of a given process. You cannot create a processinfo class on your own, but you can use processmodelinfo class to retrieve processinfo objects. Table 1 shows the important attributes of the processinfo class.

Table 1: attributes of the processinfo class

Attribute Data Type Description
Age Timespan The total time of the process running (or running. If the value exceeds the timeout setting in the processmodel section of the web. config file, the process can be restarted.
Peakmemoryused Integer Maximum memory used by the process (in MB ). If the value exceeds the memorylimit level set in the processmodel section of the web. config file, the process can be restarted.
Processid Integer The operating system uses this ID to identify the process. Each process has a unique ID (when running ).
Requestcount Integer The number of page requests received by the process. If the value exceeds the requestlimit level setting in the processmodel of the web. config file, the process can be restarted.
Shutdownreason Processshutdownreason This enumeration defines the possible causes of process restart. For possible values, see table 2.
Starttime Datetime The time when the process was started.
Status Processstatus This enumeration defines the current status of the ASP. NET auxiliary process. This value may be alive (active), shuttingdown (the process has received the close request), shutdown (the process has been properly closed), or terminated (the process has been forced to close ).

After a process is disabled, the reason for closing is set to a value in processshutdownreason enumeration.

Table 2: possible causes of process Shutdown

Value Description
None This value indicates that the process is still running.
Timeout The process restarts because its lifetime exceeds the timeout value set in the processmodel section of the web. config file. If this happens frequently, you may consider increasing the timeout value. However, it is generally acceptable to restart for this reason.
Idletimeout The reason for the process to restart is that the client is missing. If there is no client request in the idletimeout value set in the processmodel section of the web. config file, this type of restart will occur. This is usually the reason for acceptable restart.
Requestslimit The process restarts because the number of requests received exceeds the value set in the processmodel section of the web. config file (requestlimit ). Generally, the reason for this restart is acceptable, mainly when you want the process to restart occasionally.
Memorylimitexceeded The reason for process restart is that the memory limit set by the memorylimit value in the web. config file is exceeded. This usually indicates that some ASP. NET application of the process has a problem (possibly Memory leakage ). If this happens frequently, check whether the memory usage of each web application is normal.
Requestqueuelimit The process restarts because the total number of requests waiting for response exceeds the requestqueuelimit value in the web. config file. This is usually a signal that may cause Web Server latency in some cases. You may need to increase the memory or server, or speed up the drive or processor.
Deadlocksuspected The reason for the process to restart is that the request being processed may be stopped. As with the name of the reason for closing, the most likely cause of this situation is: if two or more threads need to be completed by another thread (for example, thread a needs thread B to write data to a file before continuing, at the same time, thread B needs thread a to complete the computation before continuing). We call this situation that the thread is in the "deadlock" status. If this is possible, the process will be shut down. In general, you certainly do not want to see the reason for this shutdown. If you unfortunately see it, please check all the thread processing or resource usage in the application.
Pingfailed When the ASP. NET auxiliary Process Management page is displayed, sometimes the ping sent from the IIS process is received to determine whether the process is still required. If Ping fails, the IIS process may shut down the ASP. NET process. The reason for this shutdown is that there may be communication problems in the process of receiving messages from the server or the ASP. NET auxiliary process stops working for some reason.
Unexpected In general, you certainly do not want to see this message because it indicates that the ASP. NET auxiliary process was terminated for "some other reason. In addition to monitoring every process or performing code verification on all running code, there is almost no way to solve this problem.
Create process view Handler

ASP. NET mainly uses two methods to create an HTTP handler. The first is to create a file with the ashx extension, and the other is to create a class that implements system. Web. ihttphandler. See ihttphandler interface. This article focuses on the second form. To create an HTTP handler, you need to create an assembly (usually a code library project) and a class that implements system. Web. ihttphandler. Register the class to the Web. config (or machine. config) file, and then it can receive the request. If you want to view the machine. config File (in the httphandlers section of the corresponding name), you will see many registered HTTP handlers, including system. web. UI. pagehandlerfactory (Asp. NET page ). When writing an HTTP processing program, it is actually defining a new method for processing requests.

All HTTP handlers are created by implementing the system. Web. ihttphandler interface. This interface needs to create an attribute and a method, as shown in table 3.

Table 3: ihttphandler interface member

Member Type Description
Isreusable Attribute (Boolean) Determine whether the instance of the processing program can be reused. Generally, this attribute should return true unless the handler needs to exclusively access a resource.
Processrequest Method The "Main" method of the HTTP handler. All requests are processed here. This class passes the current ASP. NET context. You can retrieve the request object and response object from this context.
Implement ihttphandler

A large number of HTTP processing programs are being created to implement processrequest of the processing program. Generally, you need to store the request and response objects in the current context, and then use the response object writing method to create the output. The following section describesProcessrequestThe Microsoft Visual Basic. net source of the resource.

    Public Sub ProcessRequest(ByVal context As HttpContext) _Implements IHttpHandler.ProcessRequest_context = context_writer = New HtmlTextWriter(context.Response.Output)'we only want to do this if we're enabledIf _config.Enabled Then_writer.WriteLine("

ProcessrequestWill store the current context and writer. Then, it creates a new HTML page as output by rendering the starting HTML tag of the page. Next, it will create a table for formatting the output. Finally, if the processing program is enabled and the client sending the request is one of the valid IP addresses, you can use the following three methods to create the output:Createheader,AddprocessesAndCreatefooter. These methods present the values in the cells of the table. A large part of the code is repeated. For the sake of simplicityAddprocessesAnd related methods.

    Private Sub AddProcesses(ByVal table As _System.Web.UI.WebControls.Table)Dim procs As ProcessInfo() = _ProcessModelInfo.GetHistory(_config.RequestLimit)Dim row As TableRow_list = New ProcessInfoCollectionFor Each proc As ProcessInfo In procsrow = AddRow(table)_list.Add(proc)AddCell(row, proc.ProcessID.ToString())AddCell(row, proc.Status.ToString())AddCell(row, proc.StartTime.ToString("g"))AddCell(row, FormatAge(proc.Age))AddCell(row, proc.PeakMemoryUsed.ToString("N0") + " MB")AddCell(row, proc.RequestCount.ToString("N0"))AddCell(row, proc.ShutdownReason.ToString())NextEnd SubPrivate Function AddCell( _ByVal row As System.Web.UI.WebControls.TableRow, _ByVal text As String) As System.Web.UI.WebControls.TableCellDim c As New TableCell()c.Text = textrow.Cells.AddReturn cEnd Function

Careful (with technical background) readers may have noticed that I can simplify this code by rendering the DataGrid and binding processinfocollection TO THE DataGrid, but it will lose the pleasure of programming.

Install the HTTP handler

After the HTTP processing program is created, it must be installed before it can be used. This includes making the class available and adding relevant information to the configuration file to activate the handler.

If you create a simple handler that is only used by a single vroot, you can copy the DLL to the bin directory of the vroot to use this class. If an HTTP handler (similar to processhandler) is created for multiple vroot users, the handler must be installed in the Global Assembly Cache (GAC. To install this handler into GAC, the class must have a strict name. To have a strict name, it must have an associated strict name key. You must use the command line Executable File sn.exe to create a strict name key file. For more information about this program, see the strong name tool (sn.exe) section in the net framework tools documentation.

After the processing program is available, the next step is to add the configuration so that it can process the request by adding entries in the httphandlers section of the web. config or machine. config file. This entry specifies the file extension and operations that will be routed through the handler. The process view handler entries are as follows.

<add verb="*" path="process.axd"type="Microsoft.Samples.Msdn.Web.ProcessHandler,MsdnProcessHandler, Version=1.0.0.0, Culture=neutral,PublicKeyToken=f5f94c20bb90ce64" />

This entry means to use any HTTP command in a request to find the "file" process. when the axd (which does not actually exist) is located in the Microsoft. samples. msdn. web. the processhandler class sends the request. This class implements ihttphandler, and then the ihttphandler is responsible for generating the output.

Add Configuration

Many ASP. NET applications use the deleetting label to add custom configurations. This is sufficient for most applications. However, sometimes applications can use more targeted solutions. In this case, you can create a new section for the application.

The create configuration section consists of two steps. First, you must create a configuration object. This object or structure has attributes that indicate the required configuration data. This object can have but generally does not have any method. Create a section handler. In this section, the handler reads the corresponding information from the Web. congfig file and converts it into a configuration object.

The configuration object of processviewer has four attributes, as described in the following table.

Table 4: properties of the processviewer configuration object

Attribute Data Type Description
Enabled Boolean True if processviewer is available. In this way, you can temporarily close the handler without deleting it from the Web. config file.
Localonly Boolean True if the output of processviewer can only be viewed from the local computer. This is the safest solution to prevent others from viewing the process history of Web applications.
Requestlimit Integer This attribute limits the maximum number of displayed items. Processmodelinfo. gethistory can return a maximum of 100 items. This attribute is used to reduce this quantity as needed.
Permittedhosts String Array IfLocalonlyIf the value is false, any computer can access process. axd handler to view the process history of the application. This may cause security risks. Therefore, you can assign a list of IP addresses that are allowed to access the processing program. This attribute can be used to restrict access to the Administrator workstation.

The second step of creating a custom configuration is to create a class that interprets the XML of the configuration file and fill in the configuration object with this information. This class must implement the system. configuration. iconfigurationsectionhandler interface. This interface has only one method calledCreate. The following describes the Visual Basic. net source of processviewersectionhandler (see download C # source ).

Public Function create (byval parent as object, _ byval configcontext as object, _ byval section as system. XML. xmlnode) as object _ implements configuration. iconfigurationsectionhandler. the create 'section has the following format: '<processview' localonly = "True | false" 'requestlimit = "<= 100" 'enabled = "True | false" 'permittedhosts = "comma-delimited list of IP addresses "/> dim result new processviewerconfiguration () dim config as new configurationhelper (section) dim Max as integerdim hosts as stringconst delimiter as string = "," const maximumreturncount as integer = 100 'confirm the settings and set the result. enabled = config. getbooleanattribute ("enabled") result. localonly = config. getbooleanattribute ("localonly") max = config. getintegerattribute ("requestlimit") if max <= maximumreturncount thenresult. requestlimit = maxend ifhosts = config. getstringattribute ("permittedhosts") result. permittedhosts = hosts. split (delimiter. tochararray () return resultend Function

CreateThe method passes three objects:

  • Parent-indicates the parent configuration section (if available ).
  • Configcontext-indicates the httpconfigurationcontext object, that is, the rest of the Web configuration. You can use this object to retrieve values from the current web. config file.
  • Section-the most important parameter is the actual configuration section. Fill in the configuration object with this object.

The above Code uses the configurationhelper object. This object is a simple object used to retrieve a specific data type from the Section. The code for this class is as follows.

Friend class configurationhelperdim _ Section as xmlnodepublic sub new (byval configsection as xmlnode) _ SECTION = configsectionend sub 'Accept true/false, yes/nopublic function getbooleanattribute (byval name as string) as booleandim value as stringdim result as booleanvalue = getstringattribute (name ). tolower () if (Boolean. truestring. tolower () = value) _ orelse (value = "yes") thenresult = trueelseresult = falseend ifreturn resultend functionpublic function getintegerattribute (byval name as string) as integerdim value as stringdim result as integervalue = getstringattribute (name) Result = int32.parse (value) return resultend functionpublic function getstringattribute (byval name as string) as stringdim theattribute as xmlattributedim result as stringtheattribute = _ Section. attributes (name) if not theattribute is nothing thenresult = theattribute. valueend ifreturn resultend functionend class

To use this processing program and configuration object, you must register it in the corresponding ASP. NET configuration file. Because this class can be called in any process, it is best to add it to the machine. config file. Register the node handler at the corresponding location in the configsection of the machine. config class (I added it to the system. Web Section)

    <sectionGroup name="system.web">... other sections<section name="processView"type="Microsoft.Samples.Msdn.Web.ProcessViewerSectionHandler,MsdnProcessHandler, Version=1.0.0.0,Culture=neutral,PublicKeyToken=f5f94c20bb90ce64" /></sectionGroup>

After registration, you can add a section to the machine. config file, and the class will become a configurable class.

Summary

Creating an HTTP processing program provides a powerful mechanism beyond ASP. NET. functionality, allowing developers to avoid page models and create, modify, or expand web site content. View ASP.. Net Process history HTTP processing programs can diagnose problems that cause customer complaints in code or servers, such as memory leakage or unhandled exceptions in the Code, or insufficient memory on the server.

After creating and installing an HTTP handler, you will be more keenly aware of what happens in this important process. At that time, you will have time to have a cup of coffee, rather than being busy investigating the reasons for restarting the web site process.

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.