Compile a software for service monitoring and management

Source: Internet
Author: User

If a service is deployed on dozens of machines, we usually need to spend a lot of time every day to check the running status of the service on each machine, although Microsoft has Microsoft's mom (Microsoft Operations Manager) and SMS (Systems Management Server), we are still unable to use these things for cost and other considerations, in fact, Microsoft has published many management and monitoring APIs and tools, such as WMIC and system. managerment, etc. By integrating these scattered APIs and tools, you can develop small software that meets custom requirements.
We need to implement the following tasks:
1. confirm that the specified process has started.
2. Obtain the CPU, memory, and thread usage of the specified Machine and Process
3. confirm that the specified port of the specified Machine is listening
4. Obtain the counter specified by the specified Machine
5. Obtain system logs/application logs on the specified Machine
6. Obtain the trace related to the specified service
7. confirm that the function Dial Test of the specified service can pass
8. Capture dump of a specified process on a specified Machine
9. network packet capture on the specified Machine
10. restart a service on a specified Machine and an application process pool.

Let's take a look at them one by one.
1. confirm that the specified process has started.
You can use the WMI interface to obtain the process list of the remote machine and traverse the list to check whether the process name of the specified service is in this list. The core code (from the Network) is as follows:
 

Public static datatable runningprocesses ()
{

// The second way of constructing a query
String querystring =
"Select name, processid, caption, executablepath" +
"From win32_process ";

Selectquery query = new selectquery (querystring );
Connectionoptions Options = new connectionoptions ();
Options. Username = @ "Administrator ";
Options. Password = "";
 

Managementscope scope = new system. Management. managementscope (@ "//./root/cimv2 ");
Scope. Connect ();

Managementobjectsearcher searcher = new managementobjectsearcher (scope, query );
Managementobjectcollection processes = searcher. Get ();

Datatable result = new datatable ();
Result. Columns. Add ("name", type. GetType ("system. String "));
Result. Columns. Add ("processid", type. GetType ("system. int32 "));
Result. Columns. Add ("caption", type. GetType ("system. String "));
Result. Columns. Add ("path", type. GetType ("system. String "));

Foreach (managementobject Mo in processes)
{
Datarow ROW = result. newrow ();
Row ["name"] = Mo ["name"]. tostring ();
Row ["processid"] = convert. toint32 (Mo ["processid"]);
If (Mo ["caption"]! = NULL)
Row ["caption"] = Mo ["caption"]. tostring ();
If (Mo ["executablepath"]! = NULL)
Row ["path"] = Mo ["executablepath"]. tostring ();
Result. Rows. Add (ROW );
}
Return result;
}
2. Obtain the CPU, memory, and thread usage of the specified Machine and Process
We use counters to obtain the data. The specific table is as follows:
CPU usage of a process: % processor time in the process type. The instance name is the name of the process in your service (without a suffix)
Memory usage of a process: Private bytes in the process type. The instance name is the name of the process you serve (without the suffix)
Memory usage of a process: the thread count in the process type. The instance name is the name of the process you serve (without a suffix)
For descriptions of other counters, open the perfmon tool to view the instructions of each counter one by one.
The code for getting a counter value of a machine is as follows:
 

Public class perfcounter
{
Public perfcounter (string categoryname,
String countername,
String InstanceName,
String machinename
)
{
This. categoryname = categoryname;
This. countername = countername;
This. InstanceName = InstanceName;
This. machinename = machinename;
}

Public String categoryname;
Public String countername;
Public String InstanceName;
Public String machinename;
}
Public class perfcounterhelper
{
Public static string getperfcount (list <perfcounter> counters)
{
List <performancecounter> PCs = new list <performancecounter> ();
Foreach (perfcounter counter in counters)
{
PCS. Add (New performancecounter (counter. categoryname,
Counter. countername,
Counter. InstanceName,
Counter. machinename ));
}
Stringbuilder text = new stringbuilder ();
Try
{
Int I = 0;
While (true)
{
Thread. Sleep (1000 );
I ++;
Text. appendformat ("times of {0} sampling/R/N", I );
Foreach (performancecounter PC in PCs)
{
Text. appendformat ("{0}/t {1}/t {2}/R/N", PC. countername, PC. InstanceName, PC. nextvalue ());
}
If (I> 3) break;
}
}
Catch (exception ex)
{
Trace. writeline (Ex );
}
Finally
{
Foreach (performancecounter PC in PCs)
{
PC. Close ();
}
}

Return text. tostring ();
}
}
Use the following
 

List <perfcounter> counters = new list <perfcounter> ();
Counters. Add (New perfcounter ("processor", "% processor time", "_ total ","."));
Counters. Add (New perfcounter ("Memory", "pages/sec ","","."));
Console. writeline (perfcounterhelper. getperfcount (counters ));
 

In fact, you can obtain the memory, thread, CPU, and other information of each process. You can also use WMI to query win32_process. However, you still need to calculate the information such as CPU, so the simple method is to obtain the information through the counter.

3. confirm that the specified port of the specified Machine is listening
Generally, services that provide network interfaces must listen to one or more ports, when we manually confirm whether the port is listening, we usually log on to the machine and run netstat-Na | find "listening" to check the output, you can also use Telnet 192.168.0.1 80 on the local machine to check whether it can be opened. In fact, we can also use two commands in the program. However, you generally cannot obtain the output of the netstat command on the remote machine, the general method is to redirect the output results to a file using the named pipe, and then access the network path to obtain the text file and read the text in a programmatic way. This method is too troublesome. It is troublesome to call Telnet programmatically. Therefore, we use socket to establish a connection to test whether the remote port is listening.

 

Public static bool islistenport (string remotehost, int port)
{
Socket S = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
Try
{
S. Connect (DNS. gethostaddresses (remotehost) [0], Port );
}
Catch (exception ex)
{
Return false;
}
Finally
{
S. Close ();
}
Return true;
}
The code for calling Ping and telnet is roughly as follows. telnet may be of no value. To simulate telnet, you can download an open-source Telnet client. Net implementation.
 

Public static string Ping (string remotehost)
{
Process proc = new process ();
Proc. startinfo. filename = "ping.exe ";
Proc. startinfo. Arguments = remotehost;
Proc. startinfo. useshellexecute = false;
Proc. startinfo. redirectstandardoutput = true;
Proc. Start ();
Return Proc. standardoutput. readtoend ();
}
Public static string telnet (string remotehost, int port)
{
Process proc = new process ();
Proc. startinfo. filename = "telnet.exe ";
Proc. startinfo. Arguments = string. Format ("{0} {1}", remotehost, Port );
Proc. startinfo. useshellexecute = false;
Proc. startinfo. redirectstandardoutput = true;
Proc. Start ();
Return Proc. standardoutput. readtoend ();
}
 

If you want to obtain the network connection information on a machine, you can call the Win32 API of gettcptable, because we generally use the netstat command to execute this task, in addition, I have not found an interface that uses WMI to obtain output similar to netstat. Of course, gettcptable cannot be executed remotely. If anyone finds out how to execute the command line program on machine B and obtain the standard output on machine A, please let me know.

4. Obtain the counter specified by the specified Machine
The specific method has already been released, but sometimes we want to view some service business logic counters. For details about how to create a custom counter, refer to the following link.
Http://www.cnblogs.com/onlytiancai/archive/2007/09/24/902310.html

5. Obtain system logs/application logs on the specified Machine
We generally obtain logs from the past period to see if they are normal. The Code is as follows (you can also use Wmi)

 

Public class eventloghelper
{
Public String geteventlog (list <string> machines)
{
Stringbuilder sb = new stringbuilder ();

Foreach (string mache in machines)
{
Try
{
Getlog (SB, mache );
Console. writeline ("process {0} finished", mache );
}
Catch (exception ex)
{
Console. writeline (Ex );
}
}

Return sb. tostring ();
}

Private void getlog (stringbuilder Sb, string machine)
{
SB. appendformat ("EventLog mylog = new EventLog ("application", machine );

For (INT x = mylog. Entries. Count-1; x> = 0; X --)
{
Eventlogentry entry = mylog. Entries [x];

If (entry. timegenerated <datetime. Now. adddays (-1 ))
{
Break;
}
Switch (entry. entrytype)
{
Case eventlogentrytype. Error:
SB. appendformat ("<p> <font color = 'red'> {0}-{1} </font> </P>", entry. timegenerated, entry. message );
Break;
Case eventlogentrytype. Warning:
SB. appendformat ("<p> <font color = 'yellow'> {0}-{1} </font> </P>", entry. timegenerated, entry. message );
Break;
Default:
SB. appendformat ("<p> <font color = 'black'> {0}-{1} </font> </P>", entry. timegenerated, entry. message );
Break;
}
}
}
}
 

6. Obtain the trace related to the specified service
Trace is generally written to some local text files or a trace database written in a centralized manner. Trace generally has machine names, service names, etc, find the path of the text trace based on these conditions and read it using streamreader, or use sqldataadapter to obtain trace records in the database. The specific code will not be written.

7. confirm that the function test of the specified service is successful
We can encapsulate the code for functional testing into a console program, then execute the code in programming mode, and then obtain the output. The output result should be similar to: "A case passes, case B error... ", For execution of external programs, refer to the ping code above. If your service can only be tested on the local machine, deploy it on a remote machine and then run it remotely Using WMI, and send the test results to you using network APIs.

8. Capture dump of a specified process on a specified Machine
In this case, you need to execute the program on the remote machine to install windbg on all servers, specify the path, and install Wireshark when capturing network packets. The code for executing a Program Using WMI is as follows. The following Code does not have a write management scope. If you want to add it, refer to the code above.

 

Public static void execute (string command)
{
// Get the object on which the method will be invoked
Managementclass processclass = new managementclass ("win32_process ");

// Get an input parameters object for this method
Managementbaseobject inparams = processclass. getmethodparameters ("CREATE ");

// Fill in input parameter values
Inparams ["CommandLine"] = command;

// Execute the Method
Managementbaseobject outparams = processclass. invokemethod ("CREATE", inparams, null );

Console. writeline (outparams. gettext (textformat. MOF ));
// Display Results
// Note: The return code of the method is provided in the "returnvalue" property of the outparams object
Console. writeline ("creation of calculator process returned:" + outparams ["returnvalue"]);
Console. writeline ("process ID:" + outparams ["processid"]);
}
 

You can first Use WMI to obtain the service PID on the remote machine, and then remotely execute "adplus-Hang-P 2233-quiet-o d:/dumps ", then, the dump can be copied to the local device through network sharing through programming.

9. network packet capture on the specified Machine
The specific method is similar to capturing dump. Wireshark must be installed on a remote machine. The command line mode is roughly as follows:
At "C:/program files/Wireshark/dumpcap.exe"-I 2-A duration: 604800-B files: 1000-F "host 10.0.0.1 and port 8081"-B filesize: 10240-w d:/network_dump/1.cap

For details about the parameters, refer to wireshare's help. This is a task to capture. You can run the AT command. Maybe your server has multiple NICs, so you must specify the NIC to capture packets, the vbs code for obtaining the NIC information of a remote machine is as follows. Change it to C #

On Error resume next

Strcomputer = "."
Set ob1_miservice = GetObject ("winmgmts :"_
& "{Impersonationlevel = impersonate }! // "& Strcomputer &"/root/cimv2 ")

Set colitems = obw.miservice. execquery ("select * From win32_networkadapter where netconnectionstatus = 2 ")

For each objitem in colitems
Wscript. Echo "name:" & objitem. Name
Next
The-I parameter of dumpcap.exe is explained as follows. With the name or index of the network adapter, you can capture packets.
-I <interface> name or idx of Interface (DEF: First none loopback)

10. restart a service on a specified Machine and an application process pool.
To restart the service, you can stop it first and then start it. The WMIC command is as follows, which can be executed by a program.
: Stop the Spooler Service.
WMIC service where name = "Spooler" Call stopservice
: Run the Spooler Service
WMIC service where name = "Spooler" Call startservice
The following code retrieves the application pool of a Web application:

Strcomputer = "."
Set ob1_miservice = GetObject ("winmgmts: //" & strcomputer & "/root/microsoftiisv2 ")
Set colitems = obw.miservice. execquery (_
"Select * From iiswebvirtualdirsetting", 48)
For each objitem in colitems
Wscript. Echo "name:" & objitem. Name & "-> pool:" & objitem. apppoolid
Next
After obtaining it, You can recycle the specified application pool. The code of the recycle application process pool is about as follows, from the network, not tested.
 

Internal class recycleapppool
{
Private Static void main (string [] ARGs)
{
Managementscope scope = new managementscope ("root // microsoftiisv2 ");
Scope. Connect ();
Managementobject apppool =
New managementobject (scope,
New managementpath ("iisapplicationpool. Name = 'w3svc/apppools/defaultapppool '"), null );
Apppool. invokemethod ("recycle", null, null );
Console. writeline ("recycled defaultapppool ");
}
}
 

For more IIS management operations, you can use adsutil. vbs.

All of the above is for centralized management, instead of logging on to a remote machine one by one. Based on the above, you can write a comprehensive management tool to manage dozens of machines on one machine and obtain the running status reports of several machines, remotely restart a service of multiple servers.

WMIC: Full Windows Management from the command line
Http://www.yesky.com/20030424/1665552.shtml
WMIC process call create
Http://wmug.co.uk/blogs/r0b/archive/2007/10/12/wmic-process-call-create.aspx
WMIC's new super command line management tool
Http://tech.sina.com.cn/other/2003-05-20/1702189076.shtml
Some WMIC examples
Http://blog.vkill.net/read.php? 41
Can one Recycle an application from a script in IIS 6.0?
Http://blogs.iis.net/chrisad/archive/2006/08/30/Recycling-Application-Pools-using-WMI-in-IIS-6.0.aspx
Usage of WMIC
Http://bbs.hackerxfiles.net/viewthread.php? Tid = 91580

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