Monitor.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. <?php
  2. require_once WORKERMAN_ROOT_DIR . 'man/Core/SocketWorker.php';
  3. /**
  4. *
  5. * 1、提供telnet接口,查看服务状态
  6. * 2、监控主进程是否挂掉
  7. * 3、监控worker进程是否频繁退出
  8. * 4、定时清理log文件
  9. * 5、定时监控worker内存泄漏
  10. *
  11. * @author walkor <worker-man@qq.com>
  12. */
  13. class Monitor extends Man\Core\SocketWorker
  14. {
  15. /**
  16. * 一天有多少秒
  17. * @var integer
  18. */
  19. const SECONDS_ONE_DAY = 86400;
  20. /**
  21. * 多长时间清理一次磁盘日志文件
  22. * @var integer
  23. */
  24. const CLEAR_LOGS_TIME_LONG = 86400;
  25. /**
  26. * 多长时间检测一次master进程是否存在
  27. * @var integer
  28. */
  29. const CHECK_MASTER_PROCESS_TIME_LONG = 5;
  30. /**
  31. * 多长时间检查一次主进程状态
  32. * @var integer
  33. */
  34. const CHECK_MASTER_STATUS_TIME_LONG = 60;
  35. /**
  36. * 多长时间检查一次内存占用情况
  37. * @var integer
  38. */
  39. const CHECK_WORKER_MEM_TIME_LONG = 60;
  40. /**
  41. * 清理多少天前的日志文件
  42. * @var integer
  43. */
  44. const CLEAR_BEFORE_DAYS = 14;
  45. /**
  46. * 告警发送时间间隔
  47. * @var integer
  48. */
  49. const WARING_SEND_TIME_LONG = 300;
  50. /**
  51. * 大量worker进程退出
  52. * @var integer
  53. */
  54. const WARNING_TOO_MANY_WORKERS_EXIT = 1;
  55. /**
  56. * 主进程死掉
  57. * @var integer
  58. */
  59. const WARNING_MASTER_DEAD = 8;
  60. /**
  61. * worker占用内存限制 单位KB
  62. * @var integer
  63. */
  64. const DEFAULT_MEM_LIMIT = 83886;
  65. /**
  66. * 上次获得的主进程信息
  67. * [worker_name=>[0=>xx, 9=>xxx], worker_name=>[0=>xx]]
  68. * @var array
  69. */
  70. protected $lastMasterStatus = null;
  71. /**
  72. * 管理员认证信息
  73. * @var array
  74. */
  75. protected $adminAuth = array();
  76. /**
  77. * 最长的workerName
  78. * @var integer
  79. */
  80. protected $maxWorkerNameLength = 10;
  81. /**
  82. * 最长的Address
  83. * @var integer
  84. */
  85. protected $maxAddressLength = 20;
  86. /**
  87. * 上次发送告警的时间
  88. * @var array
  89. */
  90. protected static $lastWarningTimeMap = array(
  91. self::WARNING_TOO_MANY_WORKERS_EXIT => 0,
  92. self::WARNING_MASTER_DEAD => 0,
  93. );
  94. /**
  95. * 该进程开始服务
  96. * @see SocketWorker::start()
  97. */
  98. public function start()
  99. {
  100. // 安装信号
  101. $this->installSignal();
  102. if(!is_dir(WORKERMAN_LOG_DIR . 'statistic'))
  103. {
  104. @mkdir(WORKERMAN_LOG_DIR . 'statistic', 0777);
  105. }
  106. // 初始化任务
  107. \Man\Core\Lib\Task::init($this->event);
  108. \Man\Core\Lib\Task::add(self::CLEAR_LOGS_TIME_LONG, array($this, 'clearLogs'), array(WORKERMAN_LOG_DIR));
  109. \Man\Core\Lib\Task::add(self::CHECK_MASTER_PROCESS_TIME_LONG, array($this, 'checkMasterProcess'));
  110. \Man\Core\Lib\Task::add(self::CHECK_MASTER_STATUS_TIME_LONG, array($this, 'checkMasterStatus'));
  111. \Man\Core\Lib\Task::add(self::CHECK_MASTER_STATUS_TIME_LONG, array($this, 'checkMemUsage'));
  112. // 添加accept事件
  113. $this->event->add($this->mainSocket, \Man\Core\Events\BaseEvent::EV_READ, array($this, 'onAccept'));
  114. // 主体循环
  115. $ret = $this->event->loop();
  116. }
  117. /**
  118. * 当有链接事件时触发
  119. * @param resource $socket
  120. * @param null $null_one
  121. * @param null $null_two
  122. * @return void
  123. */
  124. public function onAccept($socket, $null_one = null, $null_two = null)
  125. {
  126. $fd = $this->accept($socket, $null_one , $null_two);
  127. if($fd)
  128. {
  129. $this->currentDealFd = (int)$fd;
  130. if($this->getRemoteIp() != '127.0.0.1')
  131. {
  132. $this->sendToClient("Password\n");
  133. }
  134. else
  135. {
  136. $this->adminAuth[$this->currentDealFd] = time();
  137. $this->sendToClient("Hello admin\n");
  138. }
  139. }
  140. }
  141. /**
  142. * 确定包是否完整
  143. * @see Worker::dealInput()
  144. */
  145. public function dealInput($recv_str)
  146. {
  147. return 0;
  148. }
  149. /**
  150. * 处理业务
  151. * @see Worker::dealProcess()
  152. */
  153. public function dealProcess($buffer)
  154. {
  155. $buffer = trim($buffer);
  156. $ip = $this->getRemoteIp();
  157. if($ip != '127.0.0.1' && $buffer == 'status')
  158. {
  159. \Man\Core\Lib\Log::add("IP:$ip $buffer");
  160. }
  161. // 判断是否认证过
  162. $this->adminAuth[$this->currentDealFd] = !isset($this->adminAuth[$this->currentDealFd]) ? 0 : $this->adminAuth[$this->currentDealFd];
  163. if($this->adminAuth[$this->currentDealFd] < 3)
  164. {
  165. if($buffer != 'P@ssword')
  166. {
  167. if(++$this->adminAuth[$this->currentDealFd] >= 3)
  168. {
  169. $this->sendToClient("Password Incorrect \n");
  170. $this->closeClient();
  171. }
  172. $this->sendToClient("Please Try Again\n");
  173. return;
  174. }
  175. else
  176. {
  177. $this->adminAuth[$this->currentDealFd] = time();
  178. $this->sendToClient("Hello Admin \n");
  179. return;
  180. }
  181. }
  182. // 单独停止某个worker进程
  183. if(preg_match("/kill (\d+)/", $buffer, $match))
  184. {
  185. $pid = $match[1];
  186. $this->sendToClient("Kill Pid $pid\n");
  187. if(!posix_kill($pid, SIGHUP))
  188. {
  189. $this->sendToClient("Pid Not Exsits\n");
  190. }
  191. return;
  192. }
  193. $master_pid = file_get_contents(WORKERMAN_PID_FILE);
  194. switch($buffer)
  195. {
  196. // 展示统计信息
  197. case 'status':
  198. $status = $this->getMasterStatus();
  199. if(empty($status))
  200. {
  201. $this->sendToClient("Can not get Master status, Extension sysvshm or sysvmsg may not enabled\n");
  202. return;
  203. }
  204. $worker_pids = $this->getWorkerPidMap();
  205. $pid_worker_name_map = $this->getPidWorkerMap();
  206. foreach($worker_pids as $worker_name=>$pid_array)
  207. {
  208. if($this->maxWorkerNameLength < strlen($worker_name))
  209. {
  210. $this->maxWorkerNameLength = strlen($worker_name);
  211. }
  212. }
  213. foreach(\Man\Core\Lib\Config::getAllWorkers() as $worker_name=>$config)
  214. {
  215. if(!isset($config['listen']))
  216. {
  217. continue;
  218. }
  219. if($this->maxAddressLength < strlen($config['listen']))
  220. {
  221. $this->maxAddressLength = strlen($config['listen']);
  222. }
  223. }
  224. $msg_type = $message = 0;
  225. // 将过期的消息读出来,清理掉
  226. if(\Man\Core\Master::getQueueId())
  227. {
  228. while(msg_receive(\Man\Core\Master::getQueueId(), self::MSG_TYPE_STATUS, $msg_type, 1000, $message, true, MSG_IPC_NOWAIT))
  229. {
  230. }
  231. }
  232. $loadavg = sys_getloadavg();
  233. $this->sendToClient("---------------------------------------GLOBAL STATUS--------------------------------------------\n");
  234. $this->sendToClient(\Man\Core\Master::NAME.' version:' . \Man\Core\Master::VERSION . "\n");
  235. $this->sendToClient('start time:'. date('Y-m-d H:i:s', $status['start_time']).' run ' . floor((time()-$status['start_time'])/(24*60*60)). ' days ' . floor(((time()-$status['start_time'])%(24*60*60))/(60*60)) . " hours \n");
  236. $this->sendToClient('load average: ' . implode(", ", $loadavg) . "\n");
  237. $this->sendToClient(count($this->connections) . ' users ' . count($worker_pids) . ' workers ' . count($pid_worker_name_map)." processes\n");
  238. $this->sendToClient(str_pad('worker_name', $this->maxWorkerNameLength) . " exit_status exit_count\n");
  239. foreach($worker_pids as $worker_name=>$pid_array)
  240. {
  241. if(isset($status['worker_exit_code'][$worker_name]))
  242. {
  243. foreach($status['worker_exit_code'][$worker_name] as $exit_status=>$exit_count)
  244. {
  245. $this->sendToClient(str_pad($worker_name, $this->maxWorkerNameLength) . " " . str_pad($exit_status, 16). " $exit_count\n");
  246. }
  247. }
  248. else
  249. {
  250. $this->sendToClient(str_pad($worker_name, $this->maxWorkerNameLength) . " " . str_pad(0, 16). " 0\n");
  251. }
  252. }
  253. $this->sendToClient("---------------------------------------PROCESS STATUS-------------------------------------------\n");
  254. $this->sendToClient("pid\tmemory ".str_pad(' listening', $this->maxAddressLength)." timestamp ".str_pad('worker_name', $this->maxWorkerNameLength)." ".str_pad('total_request', 13)." ".str_pad('recv_timeout', 12)." ".str_pad('proc_timeout',12)." ".str_pad('packet_err', 10)." ".str_pad('thunder_herd', 12)." ".str_pad('client_close', 12)." ".str_pad('send_fail', 9)." ".str_pad('throw_exception', 15)." suc/total\n");
  255. if(!\Man\Core\Master::getQueueId())
  256. {
  257. return;
  258. }
  259. $time_start = time();
  260. unset($pid_worker_name_map[posix_getpid()]);
  261. $total_worker_count = count($pid_worker_name_map);
  262. foreach($pid_worker_name_map as $pid=>$worker_name)
  263. {
  264. posix_kill($pid, SIGUSR1);
  265. if($this->getStatusFromQueue())
  266. {
  267. $total_worker_count--;
  268. }
  269. }
  270. while($total_worker_count > 0)
  271. {
  272. if($this->getStatusFromQueue())
  273. {
  274. $total_worker_count--;
  275. }
  276. if(time() - $time_start > 1)
  277. {
  278. break;
  279. }
  280. }
  281. break;
  282. // 停止server
  283. case 'stop':
  284. if($master_pid)
  285. {
  286. $this->sendToClient("stoping....\n");
  287. posix_kill($master_pid, SIGINT);
  288. }
  289. else
  290. {
  291. $this->sendToClient("Can not get master pid\n");
  292. }
  293. break;
  294. // 平滑重启server
  295. case 'reload':
  296. $pid_worker_name_map = $this->getPidWorkerMap();
  297. unset($pid_worker_name_map[posix_getpid()]);
  298. if($pid_worker_name_map)
  299. {
  300. foreach($pid_worker_name_map as $pid=>$item)
  301. {
  302. posix_kill($pid, SIGHUP);
  303. }
  304. }
  305. else
  306. {
  307. if($master_pid)
  308. {
  309. posix_kill($master_pid, SIGHUP);
  310. $this->sendToClient("Restart Workers\n");
  311. }
  312. else
  313. {
  314. $this->sendToClient("Can not get master pid\n");
  315. }
  316. }
  317. break;
  318. // admin管理员退出
  319. case 'quit':
  320. $this->sendToClient("Admin Quit\n");
  321. $this->closeClient($this->currentDealFd);
  322. break;
  323. case '':
  324. break;
  325. default:
  326. $this->sendToClient("Unkonw CMD \nAvailable CMD:\n status show server status\n stop stop server\n reload graceful restart server\n quit quit and close connection\n kill pid kill the worker process of the pid\n");
  327. }
  328. }
  329. /**
  330. * 从消息队列中获取主进程状态
  331. * @return void
  332. */
  333. protected function getStatusFromQueue()
  334. {
  335. if(msg_receive(\Man\Core\Master::getQueueId(), self::MSG_TYPE_STATUS, $msg_type, 10000, $message, true, MSG_IPC_NOWAIT))
  336. {
  337. $pid = $message['pid'];
  338. $worker_name = $message['worker_name'];
  339. $address = \Man\Core\Lib\Config::get($worker_name . '.listen');
  340. if(!$address)
  341. {
  342. $address = '';
  343. }
  344. $str = "$pid\t".str_pad(round($message['memory']/(1024*1024),2)."M", 7)." " .str_pad($address,$this->maxAddressLength) ." ". $message['start_time'] ." ".str_pad($worker_name, $this->maxWorkerNameLength)." ";
  345. if($message)
  346. {
  347. $str = $str . str_pad($message['total_request'], 14)." ".str_pad($message['recv_timeout'], 12)." ".str_pad($message['proc_timeout'],12)." ".str_pad($message['packet_err'],10)." ".str_pad($message['thunder_herd'],12)." ".str_pad($message['client_close'], 12)." ".str_pad($message['send_fail'],9)." ".str_pad($message['throw_exception'],15)." ".($message['total_request'] == 0 ? 100 : (round(($message['total_request']-($message['proc_timeout']+$message['packet_err']+$message['send_fail']))/$message['total_request'], 6)*100))."%";
  348. }
  349. else
  350. {
  351. $str .= var_export($message, true);
  352. }
  353. $this->sendToClient($str."\n");
  354. return true;
  355. }
  356. return false;
  357. }
  358. /**
  359. * 清理日志目录
  360. * @param string $dir
  361. * @return void
  362. */
  363. public function clearLogs($dir)
  364. {
  365. $time_now = time();
  366. foreach(glob($dir."/20*-*-*") as $file)
  367. {
  368. if(!is_dir($file)) continue;
  369. $base_name = basename($file);
  370. $log_time = strtotime($base_name);
  371. if($log_time === false) continue;
  372. if(($time_now - $log_time)/self::SECONDS_ONE_DAY >= self::CLEAR_BEFORE_DAYS)
  373. {
  374. $this->recursiveDelete($file);
  375. }
  376. }
  377. }
  378. /**
  379. * 检测主进程是否存在
  380. * @return void
  381. */
  382. public function checkMasterProcess()
  383. {
  384. $master_pid = \Man\Core\Master::getMasterPid();
  385. if(!posix_kill($master_pid, 0))
  386. {
  387. $this->onMasterDead();
  388. }
  389. }
  390. /**
  391. * 主进程挂掉会触发
  392. * @return void
  393. */
  394. protected function onMasterDead()
  395. {
  396. // 不要频繁告警,5分钟告警一次
  397. $time_now = time();
  398. if($time_now - self::$lastWarningTimeMap[self::WARNING_MASTER_DEAD] < self::WARING_SEND_TIME_LONG)
  399. {
  400. return;
  401. }
  402. // 延迟告警,启动脚本kill掉主进程不告警,该进程也会随之kill掉
  403. sleep(5);
  404. $ip = $this->getIp();
  405. $this->sendSms('告警消息 PHPServer框架监控 ip:'.$ip.' 主进程意外退出');
  406. // 记录这次告警时间
  407. self::$lastWarningTimeMap[self::WARNING_MASTER_DEAD] = $time_now;
  408. }
  409. /**
  410. * 检查主进程状态统计信息
  411. * @return void
  412. */
  413. public function checkMasterStatus()
  414. {
  415. $status = $this->getMasterStatus();
  416. if(empty($status))
  417. {
  418. $this->notice("can not get master status");
  419. return;
  420. }
  421. $status = $status['worker_exit_code'];
  422. if(null === $this->lastMasterStatus)
  423. {
  424. $this->lastMasterStatus = $status;
  425. return;
  426. }
  427. $max_worker_exit_count = (int)\Man\Core\Lib\Config::get($this->workerName.".max_worker_exit_count");
  428. if($max_worker_exit_count <= 0)
  429. {
  430. $max_worker_exit_count = 2000;
  431. }
  432. foreach($status as $worker_name => $code_count_info)
  433. {
  434. foreach($code_count_info as $code=>$count)
  435. {
  436. $last_count = isset($this->lastMasterStatus[$worker_name][$code]) ? $this->lastMasterStatus[$worker_name][$code] : 0;
  437. $inc_count = $count - $last_count;
  438. if($inc_count >= $max_worker_exit_count)
  439. {
  440. $this->onTooManyWorkersExits($worker_name, $code, $inc_count);
  441. }
  442. }
  443. }
  444. $this->lastMasterStatus = $status;
  445. }
  446. /**
  447. * 检查worker进程是否有严重的内存泄漏
  448. * @return void
  449. */
  450. public function checkMemUsage()
  451. {
  452. foreach($this->getPidWorkerMap() as $pid=>$worker_name)
  453. {
  454. $this->checkWorkerMemByPid($pid, $worker_name);
  455. }
  456. }
  457. /**
  458. * 根据进程id收集进程内存占用情况
  459. * @param int $pid
  460. * @return void
  461. */
  462. protected function checkWorkerMemByPid($pid, $worker_name)
  463. {
  464. $mem_limit = \Man\Core\Lib\Config::get($this->workerName.'.max_mem_limit');
  465. if(!$mem_limit)
  466. {
  467. $mem_limit = self::DEFAULT_MEM_LIMIT;
  468. }
  469. // 读取系统对该进程统计的信息
  470. $status_file = "/proc/$pid/status";
  471. if(is_file($status_file))
  472. {
  473. // 获取信息
  474. $status = file_get_contents($status_file);
  475. if(empty($status))
  476. {
  477. return;
  478. }
  479. // 目前只需要进程的内存占用信息
  480. $match = array();
  481. if(preg_match('/VmRSS:\s+(\d+)\s+([a-zA-Z]+)/', $status, $match))
  482. {
  483. $memory_usage = $match[1];
  484. if($memory_usage >= $mem_limit)
  485. {
  486. posix_kill($pid, SIGHUP);
  487. $this->notice("worker:$worker_name pid:$pid memory exceeds the maximum $memory_usage>=$mem_limit");
  488. }
  489. }
  490. }
  491. }
  492. /**
  493. * 当有大量进程频繁退出时触发
  494. * @param string $worker_name
  495. * @param int $status
  496. * @param int $exit_count
  497. * @return void
  498. */
  499. public function onTooManyWorkersExits($worker_name, $status, $exit_count)
  500. {
  501. // 不要频繁告警,5分钟告警一次
  502. $time_now = time();
  503. if($time_now - self::$lastWarningTimeMap[self::WARNING_TOO_MANY_WORKERS_EXIT] < self::WARING_SEND_TIME_LONG)
  504. {
  505. return;
  506. }
  507. $ip = $this->getIp();
  508. $this->sendSms('告警消息 PHPServer框架监控 '.$ip.' '.$worker_name.'进程频繁退出 退出次数'.$exit_count.' 退出状态码:'.$status);
  509. // 记录这次告警时间
  510. self::$lastWarningTimeMap[self::WARNING_TOO_MANY_WORKERS_EXIT] = $time_now;
  511. }
  512. /**
  513. * 发送短信
  514. * @param int $phone_num
  515. * @param string $content
  516. * @return void
  517. */
  518. protected function sendSms($content)
  519. {
  520. // 短信告警
  521. }
  522. /**
  523. * 获取本地ip
  524. * @param string $worker_name
  525. * @return string
  526. */
  527. public function getIp($worker_name = '')
  528. {
  529. $ip = $this->getLocalIp();
  530. if(empty($ip) || $ip == '0.0.0.0' || $ip = '127.0.0.1')
  531. {
  532. if($worker_name)
  533. {
  534. $ip = \Man\Core\Lib\Config::get($worker_name . '.ip');
  535. }
  536. if(empty($ip) || $ip == '0.0.0.0' || $ip = '127.0.0.1')
  537. {
  538. $ret_string = shell_exec('ifconfig');
  539. if(preg_match("/:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/", $ret_string, $match))
  540. {
  541. $ip = $match[1];
  542. }
  543. }
  544. }
  545. return $ip;
  546. }
  547. /**
  548. * 递归删除文件
  549. * @param string $path
  550. */
  551. private function recursiveDelete($path)
  552. {
  553. return is_file($path) ? unlink($path) : array_map(array($this, 'recursiveDelete'),glob($path.'/*')) == rmdir($path);
  554. }
  555. }