Process.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CatchAdmin [Just Like ~ ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2020 http://catchadmin.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( https://github.com/yanwenwu/catch-admin/blob/master/LICENSE.txt )
  8. // +----------------------------------------------------------------------
  9. // | Author: JaguarJack [ njphper@gmail.com ]
  10. // +----------------------------------------------------------------------
  11. namespace catcher\library\crontab;
  12. use catcher\CatchAdmin;
  13. use think\console\Table;
  14. use think\facade\Log;
  15. trait Process
  16. {
  17. /**
  18. * quit 退出
  19. *
  20. * @var boolean
  21. */
  22. protected $quit =false;
  23. /**
  24. * 设置最大内存/256M
  25. *
  26. * @var [type]
  27. */
  28. protected $maxMemory = 256 * 1024 * 1024;
  29. /**
  30. * 创建进程
  31. *
  32. * @return \Closure
  33. */
  34. protected function createProcessCallback()
  35. {
  36. return function (\Swoole\Process $process) {
  37. // 必须使用 pcntl signal 注册捕获
  38. // Swoole\Process::signal ignalfd 和 EventLoop 是异步 IO,不能用于阻塞的程序中,会导致注册的监听回调函数得不到调度
  39. // 同步阻塞的程序可以使用 pcntl 扩展提供的 pcntl_signal
  40. // 安全退出进程
  41. pcntl_signal(SIGTERM, function() {
  42. $this->quit = true;
  43. });
  44. pcntl_signal(SIGUSR1, function () use ($process){
  45. // todo
  46. $this->updateTask($process->pid);
  47. });
  48. while (true) {
  49. $cron = $process->pop();
  50. if ($cron && is_string($cron)) {
  51. $cron = unserialize($cron);
  52. $this->beforeTask($process->pid);
  53. try {
  54. $cron->run();
  55. } catch (\Throwable $e) {
  56. $this->addErrors($process->pid);
  57. Log::error($e->getMessage() . ': at ' . $e->getFile() . ' ' . $e->getLine() . '行'.
  58. PHP_EOL . $e->getTraceAsString());
  59. }
  60. $this->afterTask($process->pid);
  61. }
  62. pcntl_signal_dispatch();
  63. sleep(1);
  64. // 超过最大内存
  65. if (memory_get_usage() > $this->maxMemory) {
  66. $this->quit = true;
  67. }
  68. // 如果收到安全退出的信号,需要在最后任务处理完成之后退出
  69. if ($this->quit) {
  70. Log::info('worker quit');
  71. $process->exit(0);
  72. }
  73. }
  74. };
  75. }
  76. /**
  77. * 进程信息
  78. *
  79. * @time 2020年07月05日
  80. * @param $process
  81. * @return array
  82. */
  83. protected function processInfo($process)
  84. {
  85. return [
  86. 'pid' => $process->pid,
  87. 'memory' => memory_get_usage(),
  88. 'start_at' => time(),
  89. 'running_time' => 0,
  90. 'status' => self::WAITING,
  91. 'deal_tasks' => 0,
  92. 'errors' => 0,
  93. ];
  94. }
  95. /**
  96. * 是否有等待的 Process
  97. *
  98. * @time 2020年07月07日
  99. * @return array
  100. */
  101. protected function hasWaitingProcess()
  102. {
  103. $waiting = [false, null];
  104. $pid = 0;
  105. // $processIds
  106. foreach ($this->table as $process) {
  107. if ($process['status'] == self::WAITING) {
  108. $pid = $process['pid'];
  109. break;
  110. }
  111. }
  112. // 获取相应的进程投递任务
  113. if (isset($this->processes[$pid])) {
  114. return [true, $this->processes[$pid]];
  115. }
  116. return $waiting;
  117. }
  118. /**
  119. * 处理任务前
  120. *
  121. * @time 2020年07月07日
  122. * @param $pid
  123. * @return void
  124. */
  125. protected function beforeTask($pid)
  126. {
  127. if ($process = $this->table->get($this->getColumnKey($pid))) {
  128. $process['status'] = self::BUSYING;
  129. $process['running_time'] = time() - $process['start_at'];
  130. $process['memory'] = memory_get_usage();
  131. $this->table->set($this->getColumnKey($pid), $process);
  132. }
  133. }
  134. /**
  135. * 处理任务后
  136. *
  137. * @time 2020年07月07日
  138. * @param $pid
  139. * @return void
  140. */
  141. protected function afterTask($pid)
  142. {
  143. if ($process = $this->table->get($this->getColumnKey($pid))) {
  144. $process['status'] = self::WAITING;
  145. $process['running_time'] = time() - $process['start_at'];
  146. $process['memory'] = memory_get_usage();
  147. $process['deal_tasks'] += 1;
  148. $this->table->set($this->getColumnKey($pid), $process);
  149. }
  150. }
  151. /**
  152. * 更新信息
  153. *
  154. * @time 2020年07月09日
  155. * @param $pid
  156. * @return void
  157. */
  158. protected function updateTask($pid)
  159. {
  160. if ($process = $this->table->get($this->getColumnKey($pid))) {
  161. $process['running_time'] = time() - $process['start_at'];
  162. $process['memory'] = memory_get_usage();
  163. $this->table->set($this->getColumnKey($pid), $process);
  164. }
  165. }
  166. /**
  167. * 增加错误
  168. *
  169. * @time 2020年07月09日
  170. * @param $pid
  171. * @return void
  172. */
  173. protected function addErrors($pid)
  174. {
  175. if ($process = $this->table->get($this->getColumnKey($pid))) {
  176. $process['errors'] += 1;
  177. $this->table->set($this->getColumnKey($pid), $process);
  178. }
  179. }
  180. /**
  181. * 退出服务
  182. *
  183. * @time 2020年07月07日
  184. * @return void
  185. */
  186. public function stop()
  187. {
  188. \Swoole\Process::kill($this->getMasterPid(), SIGTERM);
  189. }
  190. /**
  191. * 状态输出
  192. *
  193. * @time 2020年07月07日
  194. * @return void
  195. */
  196. public function status()
  197. {
  198. \Swoole\Process::kill($this->getMasterPid(), SIGUSR1);
  199. }
  200. /**
  201. * 子进程重启
  202. *
  203. * @time 2020年07月07日
  204. * @return void
  205. */
  206. public function reload()
  207. {
  208. \Swoole\Process::kill($this->getMasterPid(), SIGUSR2);
  209. }
  210. /**
  211. * 输出 process 信息
  212. *
  213. * @time 2020年07月05日
  214. * @return string
  215. */
  216. public function renderProcessesStatusToString()
  217. {
  218. $scheduleV = self::VERSION;
  219. $adminV = CatchAdmin::VERSION;
  220. $phpV = PHP_VERSION;
  221. $processNumber = $this->table->count();
  222. $memory = (int)(memory_get_usage()/1024/1024). 'M';
  223. $startAt = date('Y-m-d H:i:s', $this->master_start_at);
  224. $runtime = gmstrftime('%H:%M:%S', time() - $this->master_start_at);
  225. $info = <<<EOT
  226. -------------------------------------------------------------------------------------------------------
  227. | ____ _ _ _ _ _ ____ _ _ _ |
  228. | / ___|__ _| |_ ___| |__ / \ __| |_ __ ___ (_)_ __ / ___| ___| |__ ___ __| |_ _| | ___ |
  229. | | | / _` | __/ __| '_ \ / _ \ / _` | '_ ` _ \| | '_ \ \___ \ / __| '_ \ / _ \/ _` | | | | |/ _ \ |
  230. | | |__| (_| | || (__| | | |/ ___ \ (_| | | | | | | | | | | ___) | (__| | | | __/ (_| | |_| | | __/ |
  231. | \____\__,_|\__\___|_| |_/_/ \_\__,_|_| |_| |_|_|_| |_| |____/ \___|_| |_|\___|\__,_|\__,_|_|\___| |
  232. | ----------------------------------------- CatchAdmin Schedule ---------------------------------------|
  233. | Schedule Version: $scheduleV CatchAdmin Version: $adminV PHP Version: $phpV |
  234. | Process Number: $processNumber Memory: $memory Start at: $startAt |
  235. | Running Time: $runtime |
  236. |------------------------------------------------------------------------------------------------------|
  237. EOT;
  238. $table = new Table();
  239. $table->setHeader([
  240. 'pid', 'memory', 'start_at', 'running_time', 'status', 'deal_tasks','errors'
  241. ], 2);
  242. $processes = [];
  243. foreach ($this->table as $process) {
  244. $processes[] = [
  245. $process['pid'],
  246. (int)($process['memory']/1024/1024) . 'M',
  247. date('Y-m-d H:i', $process['start_at']),
  248. gmstrftime('%H:%M:%S', $process['running_time']),
  249. $process['status'],
  250. $process['deal_tasks'],
  251. $process['errors'],
  252. ];
  253. }
  254. $table->setRows($processes, 2);
  255. $table->render();
  256. return $info . PHP_EOL . $table->render();
  257. }
  258. }