其它就是一个轮询,啥也不是,不过至少实现了我需要的功能。

protected $reverse_api = 'http://************';
protected $api = [
['服务器1','http://************'],
['服务器2','http://************'],
['服务器3','http://************']
];
public function run_api()
{
$data = [];
$m['errcode'] = 0;
$m['errmsg'] = '查询成功!';
$m['is_error'] = false;
$m['is_push'] = false;
$time = date("Y-m-d H:i:s");
$api_callback = false;
$text = "## **服务器状态提醒**";
for ($i = 0; $i < count($this->api); $i++) {
$name = $this->api[$i][0];
$url = $this->api[$i][1];
$res = $this->check_url($url);
if($res == false){
$res = '{}';
$code = 9;
$msg = '网络链接失败!';
}else{
$query = json_decode($res, true);
$code = abs(isset($query['errcode']) ? $query['errcode'] : $query['code']);
$msg = isset($query['errmsg']) ? $query['errmsg'] : $query['msg'];
}
$data[$i] = ['api_callback' => $res, 'code' => $code, 'name' => $name, 'create_time' => $time, 'msg' => $msg, 'is_read' => 0];
$text.= "\n\r> #### **" . $name . "**";
//如果有错误,则发送消息
if($code > 0){
$api_callback = true;
$m['is_error'] = true;
$text.= "\n\r##### *状态:## " . $msg . "*";
}else{
$text.= "\n\r##### *状态:" . $msg . "*";
}
}
//如果停止,则不发送消息
if(cache('is_stop')){
$api_callback = false;
}
//如果整8点左右,则发送消息
$callback_time = date("H:i:s");
if($callback_time > "07:55" && $callback_time < "08:05"){
$api_callback = true;
}
//如果测试,则发送消息
if($_GET['test'] == 1){
$api_callback = true;
}
//$m['text'] = $text;
if($api_callback){
$m['is_push'] = true;
$msg = ["actionCard"=> [
"title" => "服务器告警提示" . ($code ? '【异常】' : ''),
"text" => ($code ? '【异常】' : '') . $text."\n\r#### " . $time,
"singleTitle" =>"查看详情",
"singleURL" =>"http://************"
],
"msgtype"=>"actionCard"
];
$data[$i] = ['api_callback' => '{}', 'code' => 0, 'name' => '钉钉推送记录', 'create_time' => $time, 'msg' => '', 'is_read' => 1];
$data[$i]['api_callback'] = $this->curl('https://oapi.dingtalk.com/robot/send?access_token=************', $msg);
$query = json_decode($data[$i]['api_callback'], true);
$data[$i]['code'] = $query['errcode'];
$data[$i]['msg'] = $query['errmsg'];
if($query['errcode'] == 0){
$data[$i]['msg'] = '推送成功!';
$m['msg'] = '推送成功!';
$m['code'] = 0;
}else{
$m['msg'] = $query['errmsg'];
$m['code'] = $query['errcode'];
}
}
db('agent')->insertAll($data);
return json($m);
}
public function check_url($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$http_response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($http_response_code == 200){
if ($response === false) {
return '{"code":9,"msg":"异常状态[' . $http_response_code . ' ' . curl_error($ch) . ']!"}';
} else {
return $response;
}
}else{
return '{"code":8,"msg":"网络链接失败!!"}';
}
}
发表回复
要发表评论,您必须先登录。