AutoCheckNodeStatus.php 8.5 KB

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