在这一节中,我们将使用PHP来编写一个基本的监视引擎。因为你不会事先知道怎样改变,所以你应该使它的实现既灵活又具可能性。
该记录程序应该能够支持任意的服务检查(例如,HTTP和FTP服务)并且能够以任意方式(通过电子邮件,输出到一个日志文件,等等)记录事件。你当然想让它以一个守护程序方式运行;所以,你应该请求它输出其完整的当前状态。
一个服务需要实现下列抽象类:
abstract class ServiceCheck { const FAILURE = 0; const SUCCESS = 1; protected $timeout = 30; protected $next_attempt; protected $current_status = ServiceCheck::SUCCESS; protected $previous_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->previous_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; } }