AutoCheckNodeStatus.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Components\Helpers;
  4. use Illuminate\Console\Command;
  5. use App\Components\ServerChan;
  6. use App\Http\Models\SsNode;
  7. use App\Http\Models\SsNodeInfo;
  8. use App\Mail\nodeCrashWarning;
  9. use Cache;
  10. use Mail;
  11. use Log;
  12. class AutoCheckNodeStatus extends Command
  13. {
  14. protected $signature = 'autoCheckNodeStatus';
  15. protected $description = '自动检测节点状态';
  16. protected static $systemConfig;
  17. public function __construct()
  18. {
  19. parent::__construct();
  20. self::$systemConfig = Helpers::systemConfig();
  21. }
  22. public function handle()
  23. {
  24. $jobStartTime = microtime(true);
  25. // 监测节点状态
  26. if (self::$systemConfig['is_tcp_check']) {
  27. $this->checkNodes();
  28. }
  29. $jobEndTime = microtime(true);
  30. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  31. Log::info('执行定时任务【' . $this->description . '】,耗时' . $jobUsedTime . '秒');
  32. }
  33. // 监测节点状态
  34. private function checkNodes()
  35. {
  36. $title = "节点异常警告";
  37. $nodeList = SsNode::query()->where('status', 1)->where('is_tcp_check', 1)->get();
  38. foreach ($nodeList as $node) {
  39. $tcpCheck = $this->tcpCheck($node->ip);
  40. if (false !== $tcpCheck) {
  41. switch ($tcpCheck) {
  42. case 1:
  43. $text = '服务器宕机';
  44. break;
  45. case 2:
  46. $text = '海外不通';
  47. break;
  48. case 3:
  49. $text = 'TCP阻断';
  50. break;
  51. case 0:
  52. default:
  53. $text = '正常';
  54. }
  55. // 异常才发通知消息
  56. if ($tcpCheck) {
  57. if (self::$systemConfig['tcp_check_warning_times']) {
  58. // 已通知次数
  59. $cacheKey = 'tcp_check_warning_times_' . $node->id;
  60. if (Cache::has($cacheKey)) {
  61. $times = Cache::get($cacheKey);
  62. } else {
  63. Cache::put($cacheKey, 1, 725); // 因为每小时检测一次,最多设置提醒12次,12*60=720分钟缓存时效,多5分钟防止异常
  64. $times = 1;
  65. }
  66. if ($times < self::$systemConfig['tcp_check_warning_times']) {
  67. Cache::increment('tcp_check_warning_times_' . $node->id);
  68. $this->notifyMaster($title, "节点**{$node->name}【{$node->ip}】**:**" . $text . "**", $node->name, $node->server);
  69. } elseif ($times >= self::$systemConfig['tcp_check_warning_times']) {
  70. Cache::forget('tcp_check_warning_times_' . $node->id);
  71. SsNode::query()->where('id', $node->id)->update(['status' => 0]);
  72. $this->notifyMaster($title, "节点**{$node->name}【{$node->ip}】**:**" . $text . "**,节点自动进入维护状态", $node->name, $node->server);
  73. }
  74. } else {
  75. $this->notifyMaster($title, "节点**{$node->name}【{$node->ip}】**:**" . $text . "**", $node->name, $node->server);
  76. }
  77. }
  78. Log::info("【TCP阻断检测】" . $node->name . ' - ' . $node->ip . ' - ' . $text);
  79. }
  80. // 10分钟内无节点负载信息且TCP检测认为不是宕机则认为是SSR(R)后端炸了
  81. $nodeTTL = SsNodeInfo::query()->where('node_id', $node->id)->where('log_time', '>=', strtotime("-10 minutes"))->orderBy('id', 'desc')->first();
  82. if ($tcpCheck !== 1 && !$nodeTTL) {
  83. $this->notifyMaster($title, "节点**{$node->name}【{$node->ip}】**异常:**心跳异常**", $node->name, $node->server);
  84. }
  85. // 天若有情天亦老,我为长者续一秒
  86. sleep(1);
  87. }
  88. }
  89. /**
  90. * 用ipcheck.need.sh进行TCP阻断检测
  91. *
  92. * @param string $ip 被检测的IP
  93. *
  94. * @return bool|int
  95. */
  96. private function tcpCheck($ip)
  97. {
  98. $url = 'https://ipcheck.need.sh/api_v2.php?ip=' . $ip;
  99. $ret = $this->curlRequest($url);
  100. $ret = json_decode($ret);
  101. if (!$ret || $ret->result != 'success') {
  102. Log::warning("【TCP阻断检测】ipcheck.need.sh的TCP阻断检测接口挂了");
  103. return false;
  104. }
  105. if (!$ret->data->inside_gfw->tcp->alive && !$ret->data->outside_gfw->tcp->alive) {
  106. return 1; // 服务器宕机或者检测接口挂了
  107. } elseif ($ret->data->inside_gfw->tcp->alive && !$ret->data->outside_gfw->tcp->alive) {
  108. return 2; // 国外访问异常
  109. } elseif (!$ret->data->inside_gfw->tcp->alive && $ret->data->outside_gfw->tcp->alive) {
  110. return 3; // 被墙
  111. } else {
  112. return 0; // 正常
  113. }
  114. }
  115. /**
  116. * 通知管理员
  117. *
  118. * @param string $title 消息标题
  119. * @param string $content 消息内容
  120. * @param string $nodeName 节点名称
  121. * @param string $nodeServer 节点域名
  122. *
  123. * @throws \GuzzleHttp\Exception\GuzzleException
  124. */
  125. private function notifyMaster($title, $content, $nodeName, $nodeServer)
  126. {
  127. $this->notifyMasterByEmail($title, $content, $nodeName, $nodeServer);
  128. $this->notifyMasterByServerchan($title, $content);
  129. }
  130. /**
  131. * 发邮件通知管理员
  132. *
  133. * @param string $title 消息标题
  134. * @param string $content 消息内容
  135. * @param string $nodeName 节点名称
  136. * @param string $nodeServer 节点域名
  137. */
  138. private function notifyMasterByEmail($title, $content, $nodeName, $nodeServer)
  139. {
  140. if (self::$systemConfig['is_node_crash_warning'] && self::$systemConfig['crash_warning_email']) {
  141. try {
  142. Mail::to(self::$systemConfig['crash_warning_email'])->send(new nodeCrashWarning(self::$systemConfig['website_name'], $nodeName, $nodeServer));
  143. Helpers::addEmailLog(1, $title, $content);
  144. } catch (\Exception $e) {
  145. Helpers::addEmailLog(1, $title, $content, 0, $e->getMessage());
  146. }
  147. }
  148. }
  149. /**
  150. * 通过ServerChan发微信消息提醒管理员
  151. *
  152. * @param string $title 消息标题
  153. * @param string $content 消息内容
  154. *
  155. * @throws \GuzzleHttp\Exception\GuzzleException
  156. */
  157. private function notifyMasterByServerchan($title, $content)
  158. {
  159. if (self::$systemConfig['is_server_chan'] && self::$systemConfig['server_chan_key']) {
  160. $serverChan = new ServerChan();
  161. $serverChan->send($title, $content);
  162. }
  163. }
  164. /**
  165. * 发起一个CURL请求
  166. *
  167. * @param string $url 请求地址
  168. * @param array $data POST数据,留空则为GET
  169. *
  170. * @return mixed
  171. */
  172. private function curlRequest($url, $data = [])
  173. {
  174. $data = json_encode($data, JSON_UNESCAPED_UNICODE);
  175. $ch = curl_init();
  176. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  177. curl_setopt($ch, CURLOPT_TIMEOUT, 500);
  178. // 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。
  179. // 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
  180. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  181. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  182. curl_setopt($ch, CURLOPT_URL, $url);
  183. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  184. 'Accept: application/json', // 请求报头
  185. 'Content-Type: application/json', // 实体报头
  186. 'Content-Length: ' . strlen($data)
  187. ]);
  188. // 如果data有数据,则用POST请求
  189. if ($data) {
  190. curl_setopt($ch, CURLOPT_POST, 1);
  191. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  192. }
  193. $result = curl_exec($ch);
  194. curl_close($ch);
  195. return $result;
  196. }
  197. }