NodeBlockedDetection.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Components\Helpers;
  4. use App\Components\ServerChan;
  5. use App\Http\Models\SsNode;
  6. use App\Mail\nodeCrashWarning;
  7. use Cache;
  8. use Exception;
  9. use GuzzleHttp\Exception\GuzzleException;
  10. use Illuminate\Console\Command;
  11. use Log;
  12. use Mail;
  13. class NodeBlockedDetection extends Command
  14. {
  15. protected $signature = 'NodeBlockedDetection';
  16. protected $description = '节点阻断检测';
  17. protected static $systemConfig;
  18. public function __construct()
  19. {
  20. parent::__construct();
  21. self::$systemConfig = Helpers::systemConfig();
  22. }
  23. public function handle()
  24. {
  25. $jobStartTime = microtime(TRUE);
  26. if(self::$systemConfig['nodes_detection']){
  27. if(!Cache::has('LastCheckTime')){
  28. $this->checkNodes();
  29. }elseif(Cache::get('LastCheckTime') <= time()){
  30. $this->checkNodes();
  31. }else{
  32. Log::info('下次节点TCP阻断检测时间:'.date('Y-m-d H:i:s', Cache::get('LastCheckTime')));
  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('is_transit', 0)->where('status', 1)->where('detectionType', '>', 0)->get();
  44. foreach($nodeList as $node){
  45. // 使用DDNS的node先通过gethostbyname获取ipv4地址
  46. if($node->is_ddns){
  47. $ip = gethostbyname($node->server);
  48. if(strcmp($ip, $node->server) != 0){
  49. $node->ip = $ip;
  50. }else{
  51. Log::warning("【节点阻断检测】检测".$node->server."时,IP获取失败".$ip." | ".$node->server);
  52. $this->notifyMaster($title, "节点**{$node->name}**:** IP获取失败 **", $node->name, $node->server);
  53. }
  54. }
  55. $text = '| 协议 | 状态 |'.PHP_EOL.'| ------ | ------ |'.PHP_EOL;
  56. $sendText = FALSE;
  57. if($node->detectionType == 1 || $node->detectionType == 3){
  58. $tcpCheck = $this->tcpCheck($node->ip, $node->single? $node->port : NULL);
  59. if($tcpCheck != FALSE){
  60. $text .= '| TCP |';
  61. switch($tcpCheck){
  62. case 1:
  63. $text .= ' 海外阻断 |'.PHP_EOL;
  64. break;
  65. case 2:
  66. $text .= ' 国内阻断 |'.PHP_EOL;
  67. break;
  68. case 3:
  69. $text .= ' 机器宕机 |'.PHP_EOL;
  70. break;
  71. case 0:
  72. $text .= ' 检测正常 |'.PHP_EOL;
  73. break;
  74. default:
  75. $text .= ' 未知 |'.PHP_EOL;
  76. }
  77. if($tcpCheck > 0){
  78. $sendText = TRUE;
  79. }
  80. }
  81. }
  82. if($node->detectionType == 2 || $node->detectionType == 3){
  83. $icmpCheck = $this->icmpCheck($node->ip);
  84. if($icmpCheck != FALSE){
  85. $text .= '| ICMP |';
  86. switch($icmpCheck){
  87. case 1:
  88. $text .= ' 海外阻断 |'.PHP_EOL;
  89. break;
  90. case 2:
  91. $text .= ' 国内阻断 |'.PHP_EOL;
  92. break;
  93. case 3:
  94. $text .= ' 机器宕机 |'.PHP_EOL;
  95. break;
  96. case 0:
  97. $text .= ' 检测正常 |'.PHP_EOL;
  98. break;
  99. default:
  100. $text .= ' 未知 |'.PHP_EOL;
  101. }
  102. if($icmpCheck > 0){
  103. $sendText = TRUE;
  104. }
  105. }
  106. }
  107. // 异常才发通知消息
  108. if($sendText){
  109. if(self::$systemConfig['numberOfWarningTimes']){
  110. // 已通知次数
  111. $cacheKey = 'numberOfWarningTimes'.$node->id;
  112. if(Cache::has($cacheKey)){
  113. $times = Cache::get($cacheKey);
  114. }else{
  115. Cache::put($cacheKey, 1, 725); // 最多设置提醒12次,12*60=720分钟缓存时效,多5分钟防止异常
  116. $times = 1;
  117. }
  118. if($times < self::$systemConfig['numberOfWarningTimes']){
  119. Cache::increment($cacheKey);
  120. $this->notifyMaster($title, "**{$node->name} - 【{$node->ip}】**:".PHP_EOL.$text, $node->name, $node->server);
  121. }elseif($times >= self::$systemConfig['numberOfWarningTimes']){
  122. Cache::forget($cacheKey);
  123. SsNode::query()->where('id', $node->id)->update(['status' => 0]);
  124. $this->notifyMaster($title, "**{$node->name} - 【{$node->ip}】**:".PHP_EOL.$text."节点自动进入维护状态".PHP_EOL, $node->name, $node->server);
  125. }
  126. }else{
  127. $this->notifyMaster($title, "**{$node->name} - 【{$node->ip}】**:".PHP_EOL.$text, $node->name, $node->server);
  128. }
  129. Log::info("【节点阻断检测】{$node->name} - 【{$node->ip}】: ".PHP_EOL.$text);
  130. }
  131. }
  132. // 随机生成下次检测时间
  133. $nextCheckTime = time()+3600;
  134. Cache::put('LastCheckTime', $nextCheckTime, 60);
  135. }
  136. /**
  137. * 用api.50network.com进行节点阻断检测
  138. *
  139. * @param string $ip 被检测的IP
  140. * @param int $port 检测端口
  141. *
  142. * @return bool|int
  143. */
  144. private function tcpCheck($ip, $port)
  145. {
  146. try{
  147. if(isset($port)){
  148. $url = 'https://api.50network.com/china-firewall/check/ip/tcp_port/'.$ip.'/'.$port;
  149. }else{
  150. $url = 'https://api.50network.com/china-firewall/check/ip/tcp_ack/'.$ip;
  151. }
  152. $ret = json_decode($this->curlRequest($url), TRUE);
  153. if(!$ret){
  154. Log::warning("【TCP阻断检测】检测".$ip."时,接口返回异常访问链接:");
  155. return FALSE;
  156. }elseif(!$ret['success']){
  157. Log::warning("【TCP阻断检测】检测".$ip."时,返回".$ret->error);
  158. return FALSE;
  159. }
  160. } catch(Exception $e){
  161. Log::warning("【TCP阻断检测】检测".$ip."时,接口请求超时");
  162. return FALSE;
  163. }
  164. if($ret['firewall-enable'] && $ret['firewall-disable']){
  165. return 0; // 正常
  166. }elseif($ret['firewall-enable'] && !$ret['firewall-disable']){
  167. return 1; // 国外访问异常
  168. }elseif(!$ret['firewall-enable'] && $ret['firewall-disable']){
  169. return 2; // 被墙
  170. }else{
  171. return 3; // 服务器宕机
  172. }
  173. }
  174. /**
  175. * 用api.50network.com进行ICMP阻断检测
  176. *
  177. * @param string $ip 被检测的IP
  178. *
  179. * @return bool|int
  180. */
  181. private function icmpCheck($ip)
  182. {
  183. try{
  184. $url = 'https://api.50network.com/china-firewall/check/ip/icmp/'.$ip;
  185. $ret = json_decode($this->curlRequest($url), TRUE);
  186. if(!$ret){
  187. Log::warning("【ICMP阻断检测】检测".$ip."时,接口返回异常访问链接:");
  188. return FALSE;
  189. }elseif(!$ret['success']){
  190. Log::warning("【ICMP阻断检测】检测".$ip."时,返回".$ret->error);
  191. return FALSE;
  192. }
  193. } catch(Exception $e){
  194. Log::warning("【ICMP阻断检测】检测".$ip."时,接口请求超时");
  195. return FALSE;
  196. }
  197. if($ret['firewall-enable'] && $ret['firewall-disable']){
  198. return 0; // 正常
  199. }elseif($ret['firewall-enable'] && !$ret['firewall-disable']){
  200. return 1; // 国外访问异常
  201. }elseif(!$ret['firewall-enable'] && $ret['firewall-disable']){
  202. return 2; // 被墙
  203. }else{
  204. return 3; // 服务器宕机
  205. }
  206. }
  207. /**
  208. * 通知管理员
  209. *
  210. * @param string $title 消息标题
  211. * @param string $content 消息内容
  212. * @param string $nodeName 节点名称
  213. * @param string $nodeServer 节点域名
  214. *
  215. * @throws GuzzleException
  216. */
  217. private function notifyMaster($title, $content, $nodeName, $nodeServer)
  218. {
  219. $this->notifyMasterByEmail($title, $content, $nodeName, $nodeServer);
  220. ServerChan::send($title, $content);
  221. }
  222. /**
  223. * 发邮件通知管理员
  224. *
  225. * @param string $title 消息标题
  226. * @param string $content 消息内容
  227. * @param string $nodeName 节点名称
  228. * @param string $nodeServer 节点域名
  229. */
  230. private function notifyMasterByEmail($title, $content, $nodeName, $nodeServer)
  231. {
  232. if(self::$systemConfig['webmaster_email']){
  233. $logId = Helpers::addEmailLog(self::$systemConfig['webmaster_email'], $title, $content);
  234. Mail::to(self::$systemConfig['webmaster_email'])->send(new nodeCrashWarning($logId, $nodeName, $nodeServer));
  235. }
  236. }
  237. /**
  238. * 发起一个CURL请求
  239. *
  240. * @param string $url 请求地址
  241. * @param array $data POST数据,留空则为GET
  242. *
  243. * @return mixed
  244. */
  245. private function curlRequest($url)
  246. {
  247. $ch = curl_init();
  248. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  249. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  250. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  251. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  252. curl_setopt($ch, CURLOPT_URL, $url);
  253. $result = curl_exec($ch);
  254. curl_close($ch);
  255. return $result;
  256. }
  257. }