Monitor.php 19 KB

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