Monitor.php
3.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<?php
/**
* Created by JetBrains PhpStorm.
* User: liuziyang
* Date: 12-5-8
* Time: 上午11:23
* To change this template use File | Settings | File Templates.
*/
class Q_Server_Monitor
{
/** 发短信 **/
const SEND_SMS = 'sms';
/** 邮件 **/
const SEND_MAIL = 'mail';
/** 加入队列 **/
const SEND_QUEUE = 'queue';
/** 空 **/
const SEND_NULL = NULL;
/**
* 选择
* @var array
*/
private $options = array();
/**
* 发送类型
* @var null
*/
private $sendType = null;
/**
* @param null $sendType
* @param array $options
* $options = array('phones'=>'138xxxxxxxx,139xxxxxxxx');
*/
public function __construct($sendType = Q_Server_Monitor::SEND_NULL, $options = array())
{
$this->sendType = $sendType;
$this->options = $options;
}
/**
* 检验Server
* @param String $hostname
* @param Integer string $port
* @return bool
*/
public function check($hostname, $port = '3306', $intervalTime = 180)
{
$statusKeyName = 'check://' . $hostname . '_' . $port . '_status';
if (apc_exists($statusKeyName)) {
return false;
}
$status = true;
$fs = @fsockopen($hostname, $port, $errno, $errstr, 3);
if ( $fs == false ) {
$status = false;
#如果服务器链接失败记录并标记
$checkData = array(
'status' => $status,
'lastModified' => time()
);
apc_store($statusKeyName, $checkData, $intervalTime);
self::statusAlarm($hostname . ':' . $port . ':status=0:' . $intervalTime);
}
@fclose($fs);
return $status;
}
/**
* $checkData = '127.0.0.1:3306:status<false>:30'
*
* 异常报警队列
* @static
* @param $checkData
*/
public function statusAlarm($checkData)
{
try {
switch ($this->sendType) {
case 'sms':
if (!empty($this->options['phones'])) {
break;
}
$sms = Q_Utils_Sms_Factory::factory();
$phoneList = explode(',', $this->options['phones']);
$sms->sendSms($phoneList, $checkData);
break;
case 'mail':
if (!empty($this->options['mail'])) {
@error_log($checkData, 3, '/tmp/QIN_Check_Exception.log');
break;
}
$mailList = explode(',', $this->options['mail']);
foreach ($mailList as $mail) {
@error_log($checkData, 1, $mail);
}
break;
case 'queue':
Q_Cache::factory('redis', array('select' => Q_Server_Core::SERVER_SELECT_MODE_STATIC_ROW))->rPush('QIN.Check.Exception', $checkData);
break;
}
} catch (Exception $e) {
}
}
/**
* @static
* @return Q_Server_Monitor
*/
static public function run()
{
return new Q_Server_Monitor();
}
}