Build a simple monitoring engine with PHP _ PHP Tutorial

Source: Internet
Author: User
Build a simple monitoring engine using PHP. Abstract: In this article, let's discuss a lot of tips and precautions for building a basic server monitoring engine based on the PHP language, and provide a complete source code implementation. I. changes Abstract:In this article, let's discuss a lot of tips and precautions for building a basic server monitoring engine based on the PHP language, and provide the complete source code implementation.

  I. change the working directory

When you write a monitoring program, it is usually better to set your working directory. In this way, if you use a relative path to read and write files, it will automatically process the location where the user expects to store the files as needed. It is always a good practice to restrict the paths used in the program, but it loses the necessary flexibility. Therefore, the safest way to change your working directory is to use both chdir () and chroot ().

Chroot () can be used in CLI and CGI versions of PHP, but requires the program to run with root permissions. Chroot () actually changes the path of the current process from the root directory to the specified directory. This allows the current process to only execute files in this directory. Usually, chroot () is used by the server as a "security device" to ensure that malicious code does not modify files outside a specific directory. Keep in mind that although chroot () can prevent you from accessing any files outside your new directory, any currently opened file resources can still be accessed. For example, the following code can open a log file, call chroot (), and switch to a data directory. then, you can log on successfully and then open the file resources:

<? Php

$ Logfile = fopen ("/var/log/chroot. log", "w ");

Chroot ("/Users/george ");

Fputs ($ logfile, "Hello From Inside The Chroot ");

?>

If an application cannot use chroot (), you can call chdir () to set the working directory. For example, it is useful to load specific code (which can be located anywhere in the system. Note that chdir () does not provide a security mechanism to prevent unauthorized files from being opened.

  2. give up privileges

When writing Unix daemon, a classic security precaution is to give up all unnecessary privileges; otherwise, having unnecessary privileges is easy to cause unnecessary trouble. When the code (or PHP itself) contains vulnerabilities, you can minimize the loss by ensuring that a daemon runs as a minimum-privilege user.

One way to achieve this is to execute the daemon as a non-privileged user. However, if the program needs to open resources (such as log files, data files, sockets, and so on) that are not authorized by the non-privileged user at the beginning, this is usually not enough.

If you run as the root user, you can discard your privileges by using the posix_setuid () and posiz_setgid () functions. The following example changes the privileges of the current running program to those permissions owned by the user nobody:

$ Pw = posix_getpwnam ('nobody ');

Posix_setuid ($ pw ['uid']);

Posix_setgid ($ pw ['gid']);

Like chroot (), any privileged resource opened before giving up the privilege will remain open, but cannot be created.

  3. ensure exclusion

You may often want to achieve this: a script runs only one instance at any time. This is especially important to protect scripts because multiple instances can be called by chance when running in the background.

The standard technique to ensure this exclusion is to use flock () to lock the script to a specific file (often a locked file and used in the layout ). If the lock fails, the script should output an error and exit. The following is an example:

$ Fp = fopen ("/tmp/. lockfile", "");

If (! $ Fp |! Flock ($ fp, LOCK_EX | LOCK_NB )){

Fputs (STDERR, "Failed to acquire lock ");

Exit;

}

/* The task is locked to perform the task safely */

Note that the discussion about the lock mechanism involves a lot of content, so we will not explain it here.

4. build a monitoring service

In this section, we will use PHP to compile a basic monitoring engine. Because you don't know how to change it in advance, you should make its implementation flexible and possible.

This record program should be able to support any service check (for example, HTTP and FTP services) and be able to record events in any way (via email, output to a log file, and so on. Of course you want it to run as a daemon; therefore, you should request it to output its complete current state.

A service must implement the following abstract classes:

Abstract class ServiceCheck {

Const FAILURE = 0;

Const SUCCESS = 1;

Protected $ timeout = 30;

Protected $ next_attempt;

Protected $ current_status = ServiceCheck: SUCCESS;

Protected $ previus_status = ServiceCheck: SUCCESS;

Protected $ frequency = 30;

Protected $ description;

Protected $ consecutive_failures = 0;

Protected $ status_time;

Protected $ failure_time;

Protected $ loggers = array ();

Abstract public function _ construct ($ params );

Public function _ call ($ name, $ args)

{

If (isset ($ this-> $ name )){

Return $ this-> $ name;

}

}

Public function set_next_attempt ()

{

$ This-> next_attempt = time () + $ this-> frequency;

}

Public abstract function run ();

Public function post_run ($ status)

{

If ($ status! ==$ This-> current_status ){

$ This-> previus_status = $ this-> current_status;

}

If ($ status = self: FAILURE ){

If ($ this-> current_status === self: FAILURE ){

$ This-> consecutive_failures ++;

}

Else {

$ This-> failure_time = time ();

}

}

Else {

$ This-> consecutive_failures = 0;

}

$ This-> status_time = time ();

$ This-> current_status = $ status;

$ This-> log_service_event ();

}

Public function log_current_status ()

{

Foreach ($ this-> loggers as $ logger ){

$ Logger-> log_current_status ($ this );

}

}

Private function log_service_event ()

{

Foreach ($ this-> loggers as $ logger ){

$ Logger-> log_service_event ($ this );

}

}

Public function register_logger (ServiceLogger $ logger)

{

$ This-> loggers [] = $ logger;

}

}

The above _ call () overload method provides read-only access to the parameters of a ServiceCheck object:

· Timeout-how long the check can be suspended before the engine termination check.

· Next_attempt-the next attempt to connect to the server.

· Current_status-Current Status of the service: SUCCESS or FAILURE.

· Previus_status-the status before the current status.

· Frequency-check the service at intervals.

· Description-service description.

· Consecutive_failures-the number of consecutive failed service checks since the previous success.

· Status_time-the last time when the service is checked.

· Failure_time-if the status is FAILED, it indicates the time when the failure occurred.

This class also implements the observer mode, allowing the ServiceLogger type objects to register themselves, and then calls it when calling log_current_status () or log_service_event.

The key function implemented here is run (), which defines how to perform the check. If the check succeeds, it should return SUCCESS; otherwise, return FAILURE.


In this article, we will discuss a lot of tips and precautions for building a basic server monitoring engine based on the PHP language, and provide the complete source code implementation. I. change...

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.