Create monitor server process

Source: Internet
Author: User
Tags config html page iis implement thread time limit tostring unique id| Create | server | Process Product Introduction
Have you ever seen a good coffee shop clerk send coffee? It's just coffee beans, steam and milk and coffee drinks in the dance of the wonderful ballet, jumping to the anxious waiting customers. However, even the best shop assistants occasionally have problems. For example, two of the list in the process of mixing, the results sent to you is a cup of Soy latte. It may be that the flamboyant scribbled on the glass is simply wrong, or that the clerk has misunderstood. Someone asked for a glass of "Kangochi" (Capchino), and the poor clerk struggled to understand what the customer was up to. If a similar problem occurs, you must stop processing and then start again. A good waiter may defer the existing requirements, but a good waiter can do it without anyone noticing it.

Microsoft® has made great strides in system reliability over any competitor. However, like the excellent clerk, occasionally has problems. Luckily, is a very good server. It can quickly generate new processes in the background, and then process requests. Typically, only a slight delay occurs when a page is requested that a user may not even notice.

The administrator of the system might need to know what happened. Again, they want to know what causes the process to fail. Fortunately, you can use the ProcessInfo and Processmodelinfo classes in the. NET Framework Class Library documentation to get the relevant information. In this article, we'll learn how to create HTTP handlers that use these objects to view the health and shutdown status of processes used by WEB sites. In addition, we will create a configuration section handler so that we can configure it after the handler is installed.

What are we going to see?
The process compiles and manages all requests made to the page. Ideally, this process should always exist on the server: actively receiving requests, compiling pages, and returning HTML. However, due to the many potential events that may affect the process, we have to face the real situation of WEB development. The developer may not be able to properly handle memory leaks or threading problems, the server may lose connectivity to the process, or even the idletimeout, web.config in the <processModel> Element section of the file. Requestlimit, memorylimit, and similar projects were incorrectly configured to cause problems. If any of these events occur, a new worker process is created and the new request is transferred to this process for processing.

Because the process is so important to page processing, it is equally important to monitor these processes. Use the ProcessInfo and Processmodelinfo classes to view the validity and health of current and previous processes. Figure 1 shows a list of the processes created in this article.

Figure 1:web Process History of the server

The ProcessInfo class stores data for a given process. You cannot create ProcessInfo classes on your own, but you can use Processmodelinfo class to retrieve ProcessInfo objects. Table 1 shows the important properties of the ProcessInfo class.

Table 1:processinfo Properties of Class

Attribute data type description
The total time that the age TimeSpan process runs (or has run). If this value exceeds the timeout setting in the ProcessModel section of the Web.config file, it can cause the process to restart.
peakmemoryused Integer The maximum amount of memory used by this process, in megabytes. If this value exceeds the MEMORYLIMIT level setting set in the ProcessModel section of the Web.config file, it can cause the process to restart.
The ProcessID Integer operating system uses this ID to identify the process. Each process has a unique ID (when the process is running).
RequestCount the number of page requests received by the Integer process. If this value exceeds the level setting requestlimit in the ProcessModel of the Web.config file, it can cause the process to restart.
ShutdownReason Processshutdownreason This enumeration to define the possible causes of a process reboot. Please refer to table 2 for possible values.
The time the StartTime DateTime process started.
Status Processstatus This enumeration defines the current state of the worker process. This value may be Alive (active), Shuttingdown (the process has received a shutdown request), ShutDown (the process has been shut down properly), or terminated (the process has been forced to close).

When a process closes, the shutdown reason is set to one of the values in the Processshutdownreason enumeration.

Table 2: Possible causes of process shutdown

Value Description
None This value indicates that the process is still running.
The Timeout process restarts because its lifetime exceeds the timeout value set in the ProcessModel section of the Web.config file. If this happens frequently, you might consider increasing the timeout value. However, it is generally acceptable to restart for this reason.
The reason for the idletimeout process reboot is the lack of a client. This type of reboot occurs if there is no client request within the time limit set by the IdleTimeout value in the ProcessModel section of the Web.config file. This is usually also the reason for an acceptable reboot.
The reason for the Requestslimit process reboot is that the number of requests received exceeds the value set in the ProcessModel section of the Web.config file (requestlimit). In general, the reason for this reboot is also acceptable, primarily for situations where you want the process to restart occasionally.
The reason for the memorylimitexceeded process reboot is that the memory limit set through the memorylimit value in the Web.config file is exceeded. This usually indicates a problem with some application part of the process (possibly a memory leak). If such a phenomenon occurs frequently, monitor the memory usage of each WEB application for normal use.
The reason for the requestQueueLimit process reboot is that the total number of requests waiting for a response exceeds the requestQueueLimit value of the Web.config file. This is usually the signal that some situations will cause the WEB server to delay. You may need to increase the memory or server, or increase the speed of the drive or processor.
The reason for the deadlocksuspected process reboot is that the request that is being processed may be stopped. Just like the name of the shutdown reason, the most likely cause is if two or more threads require another thread to complete before they can proceed (for example, a thread requires a B-thread to finish writing to a file before it can proceed, and b threads need A thread to complete the calculation before proceeding). We call this a situation where the thread is in the "deadlock" (deadlock) state. If this is possible, the process will be closed for this reason. In general, you certainly don't want to see this shutdown, and if you're unlucky to see it, look at all the threading or resource usage used in your application.
pingfailed when worker processes manage pages, you sometimes receive a ping from the IIS process to determine whether this process is still required. If the ping fails, the IIS process may shut down the process. This shutdown reason indicates that there may be a communication problem or that the worker process stopped working for some reason while the server was receiving the message.
Unexpected in general, you certainly do not want to see this message because it indicates that "some other reason" terminated the worker process. In addition to monitoring each process or performing code proofreading on all running code, there is little solution to this problem.

Create a Process View handler
In, there are two main ways to create an HTTP handler. The first is to create a file with a ASHX extension, and the other is to create a class that implements System.Web.IHttpHandler, see IHttpHandler Interface. This article will highlight the second form. To create an HTTP handler, you need to create an assembly (usually a code base project) and a class that implements System.Web.IHttpHandler. The class is then registered to the Web.config (or Machine.config) file, and then it can receive the request. If you view the Machine.config file (in the appropriate named httphandlers section), you will see a number of currently registered HTTP handlers, including System.Web.UI.PageHandlerFactory ( The master handler for the page). When you write an HTTP handler, you are defining a new way to process the request.

All HTTP handlers are created by implementing System.Web.IHttpHandler Interface. This interface needs to create a property and a method, as shown in table 3.

Table 3:ihttphandler members of the interface

Member Type description
The IsReusable property (Boolean) determines whether an instance of the handler can be reused. Typically, this property should return true, unless the handler requires exclusive access to a resource.
The "Master" method of the ProcessRequest method HTTP handler. All processing of the request will be added here. The class passes the current context. Request objects and response objects can be retrieved from this context.

Implement IHttpHandler
The bulk of the work of creating HTTP handlers is focused on implementing the processrequest of handlers. Typically, you need to store the request and response objects for the current context, and then create the output using the Write method of the Response object. The following is a Microsoft Visual basic®.net source for the ProcessRequest resource for the process view handler.

Public Sub ProcessRequest (ByVal context as HttpContext) _
Implements Ihttphandler.processrequest
_context = Context
_writer = New HtmlTextWriter (context. Response.Output)

' We ' want to does this if we ' re enabled
If _config. Enabled Then
_writer. WriteLine ("_writer. WriteLine ("_writer. WriteLine (Me.stylesheet)
_writer. WriteLine ("
_writer. WriteLine ("<body>")
_writer. WriteLine ("<span class=" "Content" ">")

' Write content here
' CREATE table
Dim T as New Table ()
With T
. Width = unit.percentage (100)
. cellpadding = 0
. cellspacing = 0
End With

' The meat of the routine
' Make certain ' a destination machine
If (Permittedhost (_context). request.userhostaddress)) Then
CreateHeader (t)
Addprocesses (t)
Createfooter (t)
Createerrorreport (t)
End If

' Write to the stream '
T.rendercontrol (_writer)

_writer. WriteLine ("</span>\r\n</body>\r\nEnd If
End Sub

The ProcessRequest implementation stores the current context and the creator. It then creates the new HTML page as output by rendering the page's starting HTML tag. Next, it creates a table for formatting the output. Finally, if the handler is enabled and the requesting client is one of the legitimate IP addresses, the output is created in the following three ways: CreateHeader, addprocesses, and Createfooter. These methods render the corresponding values in the cells of the table. Much of this code is duplicated, and for brevity, only addprocesses and its associated methods are given below.

Private Sub addprocesses (ByVal table as _
Dim procs as ProcessInfo () = _
Processmodelinfo.gethistory (_config. REQUESTLIMIT)
Dim Row as TableRow

_list = New processinfocollection
For each proc as ProcessInfo in procs
row = 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 ())
End Sub
Private Function Addcell (_
ByVal row as System.Web.UI.WebControls.TableRow, _
ByVal text as String) as System.Web.UI.WebControls.TableCell
Dim C as New TableCell ()
C.text = Text
Row. Cells.add©
Return C
End Function

Attentive (and technical) readers may have noticed that I can simply simplify this code by rendering the DataGrid and binding Processinfocollection to the DataGrid, but that would have lost the pleasure of writing programs.

Installing HTTP Handlers
After you create an HTTP handler, you must install it to use it. This includes making the class available and adding the appropriate information to the configuration file to activate the handler.

If you create a simple handler that is used only by a single vroot, you can copy the DLL to the VRoot bin directory to use the class. If you create an HTTP handler (similar to Processhandler) that is used by multiple vroot, this handler must be installed in the global Assembly cache (GAC). To install this handler into the GAC, the class must have a strict name. To have a strict name, it must have a strict name key associated with it. You must create a strict name key file Sn.exe using the command-line executable file. For more information about this program, see the Strong Name Tool (Sn.exe) section of the NET Framework Tools documentation.

Once the handler is available, the next step is to add the configuration so that it can process the request by adding an entry in the httphandlers section of the Web.config or machine.config file. This entry specifies the file name extension and operation that will be routed through the handler. The entry for the process view handler is shown below.

<add verb= "*" Path= "Process.axd"
Type= "Microsoft.Samples.Msdn.Web.ProcessHandler,
Msdnprocesshandler, version=, Culture=neutral,
Publickeytoken=f5f94c20bb90ce64 "/>

This entry means that when a request uses any HTTP command to look for a "file" Process.axd (which does not actually exist), it will be placed in an assembly Msdnprocesshandler The Microsoft.Samples.Msdn.Web.ProcessHandler class sends a request. The class implements IHttpHandler, and then the IHttpHandler is responsible for generating the output.

Add configuration
Many applications use the appsetting tag to add custom configurations. This is completely enough for most applications. However, sometimes applications can use more targeted solutions. In this case, you can create a new section for your application.

A new configuration section consists of two steps. First, you must create a configuration object. This object or structure has properties that represent the required configuration data. This object can have, but usually does not have, any methods. Second, you create a section handler. This section handler is responsible for reading the appropriate information from the Web.congfig file and converting it into a configuration object.

The ProcessViewer configuration object has four properties, as described in the following table.

Table 4:processviewer Properties of Configuration objects

Attribute data type description
Enabled Boolean True if ProcessViewer is available. This allows you to temporarily close the handler without removing it from the Web.config file.
Localonly Boolean True if ProcessViewer output can only be viewed from the local computer. This is the safest scenario to prevent others from viewing the process history of a WEB application.
Requestlimit Integer This property limits the maximum number of items to display. Processmodelinfo.gethistory returns a maximum of 100 items. This property is used to reduce this number when needed.
Permittedhosts String Array If localonly is false, any computer can access the Process.axd handler to view the process history of the application. This can be a security risk. Therefore, you can assign a list of IP addresses that allow access to handlers. This property can be used to restrict access to the administrator workstation.

The second step in creating a custom configuration is to create a class that interprets the XML for the configuration file and use that information to populate the Configuration object. This class must implement the System.Configuration.IConfigurationSectionHandler interface. This interface has only one method, called Create. The following is a Visual Basic. NET Source for Processviewersectionhandler (see C # source downloads).

Public Function Create (ByVal parent as Object, _
ByVal Configcontext as Object, _
ByVal section as System.Xml.XmlNode) as Object _
Implements Configuration.IConfigurationSectionHandler.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 Integer
Dim hosts as String
Const delimiter as String = ","
Const Maximumreturncount as Integer = 100
' Confirm settings, and set
Result. Enabled = config. Getbooleanattribute ("Enabled")
Result. localonly = config. Getbooleanattribute ("localonly")

max = config. Getintegerattribute ("Requestlimit")
If Max <= Maximumreturncount Then
Result.requestlimit = max
End If

hosts = config. Getstringattribute ("Permittedhosts")
Result. Permittedhosts = hosts. Split (delimiter. ToCharArray ())
return result
End Function

The Create method passed three objects:

Parent-Represents the Parental configuration section (if available).
Configcontext-Represents the Httpconfigurationcontext object, the remainder of the Web configuration. You can use this object to retrieve values from the current Web.config file.
Section-The most important parameters, the actual configuration sections. Use this object to populate the Configuration object.
The above code uses the Configurationhelper object. This object is a simple object that retrieves a specific data type from a section. The code for this class is shown below.

Friend Class Configurationhelper
Dim _section as XmlNode
Public Sub New (ByVal configsection as XmlNode)
_section = configsection
End Sub
' Accept True/false, yes/no
Public Function Getbooleanattribute (ByVal name as String) as Boolean
Dim value as String
Dim result as Boolean

Value = Getstringattribute (name). ToLower ()
If ((Boolean.TrueString.ToLower () = value) _
OrElse (value = "yes") Then
result = True
result = False
End If

return result
End Function

Public Function Getintegerattribute (ByVal name as String) as Integer
Dim value as String
Dim result as Integer

Value = Getstringattribute (name)
result = Int32.Parse (value)

return result
End Function

Public Function Getstringattribute (ByVal name as String) as String
Dim Theattribute as XmlAttribute
Dim result as String

Theattribute = _section. Attributes (name)
If not Theattribute are nothing Then
result = Theattribute.value
End If
return result
End Function

End Class

To use this section handler and configuration object, you must register it in the appropriate configuration file. Because the class can be invoked in any process, it is best to add it to the Machine.config file. Register the section handler at the appropriate location in the Configsection section 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=,
Publickeytoken=f5f94c20bb90ce64 "/>

After registering, you can add a section to the Machine.config file, and the class becomes a configurable class.

Creating an HTTP handler can provide an exceeding Powerful mechanism that allows developers to bypass the page model and create, modify, or extend the content of the Web site. By adding an HTTP handler that is used to view the process history of, you can diagnose the code or the problem in the server that is causing the customer to complain, such as a memory leak or unhandled exception in your code, or a server with insufficient memory.

After you create and install an HTTP handler, you will be more acutely aware of what is happening in this important process. You'll have time to get a cup of coffee instead of chasing the cause of the Web site process reboot.

Related Article

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: 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.