AutoCheckNodeStatus.php 7.9 KB

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