SwooleCrontabController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <?php
  2. /**
  3. * rabbitMq 消费者
  4. */
  5. namespace console\controllers;
  6. use common\models\common\CrontabTask;
  7. use common\models\common\CrontabTaskExecute;
  8. use console\controllers\swoole_server\BaseSwooleServer;
  9. use Co;
  10. use Swoole\Process;
  11. use Swoole\Runtime;
  12. use Swoole\Server;
  13. use Swoole\Timer;
  14. use Swoole\Coroutine\Client;
  15. use function Swoole\Coroutine\run;
  16. use Yii;
  17. use yii\console\ExitCode;
  18. use common\helpers\DateHelper;
  19. use linslin\yii2\curl\Curl;
  20. /**
  21. * 基于swoole定时任务封装的,定时任务处理服务
  22. * @Author bing
  23. * @DateTime 2021-10-15 10:20:51
  24. * @copyright: Copyright (c) 2020 广东七件事集团
  25. */
  26. class SwooleCrontabController extends BaseSwooleServer
  27. {
  28. public $host;
  29. public $port;
  30. public $sign;
  31. private $serv;
  32. public $timeout;
  33. private $client;
  34. /**
  35. * console模式初始化
  36. * @Author bing
  37. * @DateTime 2021-10-18 13:16:01
  38. * @copyright: Copyright (c) 2020 广东七件事集团
  39. * @return void
  40. */
  41. public function init()
  42. {
  43. parent::init();
  44. }
  45. /**
  46. * 开启定时任务服务
  47. * @Author bing
  48. * @DateTime 2021-10-21 10:28:30
  49. * @copyright: Copyright (c) 2020 广东七件事集团
  50. * @return void
  51. */
  52. public function actionServerRun(){
  53. $this->beforeRun();
  54. // 重启服务
  55. if ($this->option == 'stop') return ExitCode::OK;
  56. $this->serv = new Server('0.0.0.0',9501,SWOOLE_PROCESS,SWOOLE_TCP);
  57. $this->serv->set(array(
  58. 'worker_num' => 2,
  59. 'daemonize' => false,
  60. 'task_worker_num' => 2,
  61. 'open_eof_split' => true,
  62. 'package_eof' => "\r\n",
  63. 'log_file' =>Yii::$app->getRuntimePath() .'/logs/swoole_crontab_server.log',
  64. // 'ssl_verify_peer' => true,
  65. // 'ssl_allow_self_signed' => true,
  66. // 'ssl_cert_file' => __DIR__ . '/task/ca/server/server.crt',
  67. // 'ssl_key_file' => __DIR__ . '/task/ca/server/server.key',
  68. // 'ssl_client_cert_file' => __DIR__ . '/task/ca/private/ca.crt',
  69. // 'ssl_verify_depth' => 10,
  70. ));
  71. $this->serv->on('Start', [$this, 'onStart']);
  72. $this->serv->on('Connect', [$this, 'onConnect']);
  73. $this->serv->on('Receive', [$this, 'onReceive']);
  74. $this->serv->on('Close', [$this, 'onClose']);
  75. $this->serv->on('Task', [$this, 'onTask']);
  76. $this->serv->on('Finish', [$this, 'onFinish']);
  77. $this->serv->on('workerStart', [$this, 'onWorkerStart']);
  78. $this->serv->on('pipeMessage', [$this, 'onPipeMessage']);
  79. $serv = $this->serv;
  80. // 准备任务数据
  81. $crontab_prepare_process = new Process(function ($process) use ($serv) {
  82. swoole_set_process_name("swoole : crontab_prepare_process {$process->pid}");
  83. run(function () use ($serv) {
  84. CrontabTask::prepareData();
  85. Timer::tick(60000, function () use ($serv) {
  86. //CrontabTask
  87. CrontabTask::prepareData();
  88. });
  89. });
  90. });
  91. $this->serv->addProcess($crontab_prepare_process);
  92. // 任务分发进程500ms每次
  93. $crontab_dispatch_process = new Process(function ($process) use ($serv) {
  94. swoole_set_process_name("swoole : crontab_dispatch_process {$process->pid}");
  95. run(function () use ($serv) {
  96. Timer::tick(500, function () use ($serv) {
  97. $client_list = [];
  98. $client_list_info = [];
  99. $start_fd = 0;
  100. $list = $serv->getClientList($start_fd, 100);
  101. if($list){
  102. foreach ($list as $fd) {
  103. array_push($client_list, $fd);
  104. array_push($client_list_info, $serv->getClientInfo($fd));
  105. }
  106. $start_fd = end($list);
  107. $count = count($client_list);
  108. if ($count > 0) {
  109. while ($task = CrontabTaskExecute::pop()) {
  110. $remaining = $task['id'] % $count;
  111. $this->addSign($task);
  112. $serv->send($client_list[$remaining], json_encode($task) . "\r\n");
  113. }
  114. }
  115. }
  116. });
  117. });
  118. });
  119. $this->serv->addProcess($crontab_dispatch_process);
  120. // 任务失败发送警告60s执行一次
  121. $crontab_prepare_process = new Process(function ($process) use ($serv) {
  122. swoole_set_process_name("swoole : crontab_warning_process {$process->pid}");
  123. run(function () use ($serv) {
  124. Timer::tick(60000, function () use ($serv) {
  125. CrontabTaskExecute::warningHandle();
  126. });
  127. });
  128. });
  129. $this->serv->addProcess($crontab_prepare_process);
  130. $this->serv->start();
  131. }
  132. /**
  133. * 使用父类的服务启动进行进程管理
  134. * @Author bing
  135. * @DateTime 2021-10-18 13:04:14
  136. * @copyright: Copyright (c) 2020 广东七件事集团
  137. * @param [type] $serv
  138. * @return void
  139. */
  140. public function onStart($serv)
  141. {
  142. parent::onStart($serv);
  143. }
  144. /**
  145. * 客户端连接回调
  146. * @Author bing
  147. * @DateTime 2021-10-18 13:05:03
  148. * @copyright: Copyright (c) 2020 广东七件事集团
  149. * @param $serv Server Server对象
  150. * @param $fd int 是TCP客户端连接的标识符
  151. * @param $from_id int 投递任务的worker_id
  152. * @return void
  153. */
  154. public function onConnect($serv, $fd, $from_id)
  155. {
  156. echo "have connect!\n";
  157. }
  158. /**
  159. * 接收到客户端消息
  160. * @Author bing
  161. * @DateTime 2021-10-18 13:05:03
  162. * @param $serv Server Server对象
  163. * @param $fd int 是TCP客户端连接的标识符
  164. * @param $from_id int 投递任务的worker_id
  165. * @param $data string 接收到的数据
  166. * * @return void
  167. */
  168. public function onReceive(Server $serv, $fd, $from_id, $data)
  169. {
  170. echo "Get Message From Client {$fd}:{$data}\n";
  171. }
  172. /**
  173. * 客户端关闭时
  174. * @Author bing
  175. * @DateTime 2021-10-18 13:05:03
  176. * @param $serv Server Server对象
  177. * @param $fd int 是TCP客户端连接的标识符
  178. * @param $from_id int 投递任务的worker_id
  179. */
  180. public function onClose($serv, $fd, $from_id)
  181. {
  182. echo "Client {$fd} close connection\n";
  183. }
  184. /**
  185. * 异步任务处理
  186. * @Author bing
  187. * @DateTime 2021-10-18 13:05:03
  188. * @param $serv Server Server对象
  189. * @param $task_id int 任务id
  190. * @param $from_id int 投递任务的worker_id
  191. * @param $data string 投递的数据
  192. */
  193. public function onTask(Server $serv, $task_id, $from_id, $data)
  194. {
  195. echo "onTask\n";
  196. $serv->finish($data);
  197. }
  198. /**
  199. * 异步任务执行完成回调
  200. * @Author bing
  201. * @DateTime 2021-10-18 13:05:03
  202. * @param $serv Server Server对象
  203. * @param $task_id int 任务id
  204. * @param $data string 任务返回的数据
  205. */
  206. public function onFinish(Server $serv, $task_id, $data)
  207. {
  208. echo "onFinish\n";
  209. }
  210. /**
  211. * worker进程启动时回调
  212. * @Author bing
  213. * @DateTime 2021-10-18 13:05:03
  214. * @param $serv Server Server对象
  215. * @param $worker_id
  216. */
  217. public function onWorkerStart($serv, $worker_id)
  218. {
  219. echo "onWorkerStart\n";
  220. if ($worker_id >= $serv->setting['worker_num']) {
  221. swoole_set_process_name("swoole : new_task_worker");
  222. } else {
  223. swoole_set_process_name("swoole : worker");
  224. }
  225. }
  226. /**
  227. * 客户端消费定时任务
  228. * @Author bing
  229. * @DateTime 2021-10-21 10:29:46
  230. * @copyright: Copyright (c) 2020 广东七件事集团
  231. * @return void
  232. */
  233. public function actionClientRun()
  234. {
  235. run(function () {
  236. $this->client = new Client(SWOOLE_SOCK_TCP);
  237. $this->client->set([
  238. 'open_eof_split' => true,
  239. 'package_eof' => "\r\n",
  240. ]);
  241. $is_docker_deploy = \Yii::$app->params['is_docker_deploy'] ?? false;
  242. $server = $is_docker_deploy ? 'crontab-server' : '127.0.0.1';
  243. if (!$this->client->connect($server, 9501, 0.5)){
  244. echo "connect failed. Error: {$this->client->errCode}".PHP_EOL;
  245. }
  246. while (true) {
  247. $data = $this->client->recv();
  248. if (strlen($data) > 0) {
  249. $this->ExecuteCrontab($data);
  250. } else {
  251. if ($data === '') {
  252. // 全等于空 直接关闭连接
  253. $this->client->close();
  254. break;
  255. } else {
  256. if ($data === false) {
  257. // 可以自行根据业务逻辑和错误码进行处理,例如:
  258. // 如果超时时则不关闭连接,其他情况直接关闭连接
  259. if ($this->client->errCode !== SOCKET_ETIMEDOUT) {
  260. $this->client->close();
  261. break;
  262. }
  263. } else {
  264. $this->client->close();
  265. break;
  266. }
  267. }
  268. }
  269. Co::sleep(0.3);
  270. }
  271. });
  272. }
  273. /**
  274. * 执行定时任务
  275. * @Author bing
  276. * @DateTime 2021-10-12 15:50:13
  277. * @copyright: Copyright (c) 2020 广东七件事集团
  278. * @param [type] $task
  279. * @return void
  280. */
  281. public function ExecuteCrontab($task){
  282. if ($this->checkSign($task)) {
  283. $task = json_decode($task,true);
  284. if (empty($task['execute_time']) || empty($task['command']) || empty($task['id']) || empty($task['type'])) return false;
  285. // 计算需要执行的时间
  286. $after_time_ms = $task['execute_time'] - time();
  287. if ($after_time_ms <= 0) $after_time_ms = 0.001;
  288. Timer::after($after_time_ms * 1000, function () use ($task) {
  289. // 开启一个协程处理任务
  290. go(function() use ($task){
  291. $res = CrontabTaskExecute::updateProcess($task['id'], CrontabTaskExecute::PROCESS_PENDING, time());
  292. $running_time = DateHelper::getMicrotime();
  293. $date = date('Y-m-d H:i:s');
  294. switch ($task['type']) {
  295. case CrontabTask::TYPE_SHELL:
  296. $tmpFile = tempnam("/tmp/", "swoole_corntab_task_");
  297. file_put_contents($tmpFile, $task['command']);
  298. $command = "bash $tmpFile";
  299. echo '['.$date.'] start exec '. $command . PHP_EOL;
  300. exec($command,$output,$return_var);
  301. $flag = $return_var === 0 ? true : false;
  302. unlink($tmpFile);
  303. break;
  304. case CrontabTask::TYPE_YII:
  305. $yii_path = dirname(Yii::$app->basePath);
  306. $command = $yii_path.'/yii '.$task['command'];
  307. echo '['.$date.'] start exec '. $command . PHP_EOL;
  308. exec($command,$output,$return_var);
  309. $flag = $return_var === 0 ? true : false;
  310. break;
  311. case CrontabTask::TYPE_URL:
  312. Runtime::enableCoroutine(SWOOLE_HOOK_ALL);
  313. Runtime::enableCoroutine(SWOOLE_HOOK_CURL);
  314. echo '['.$date.'] start exec '.$task['command'].PHP_EOL;
  315. $curl = new Curl();
  316. $response = $curl->get($task['command']);
  317. if ($curl->errorCode === null) {
  318. $flag = true;
  319. $output = $response;
  320. } else {
  321. $flag = false;
  322. // 错误码参考:https://curl.haxx.se/libcurl/c/libcurl-errors.html
  323. // 错误描述参考:http://php.net/manual/en/function.curl-strerror.php
  324. $output = 'curl请求错误,错误码:'.$curl->errorCode.'错误描述:'.$curl->errorText;
  325. }
  326. break;
  327. }
  328. if($flag === true){
  329. $running_time -= DateHelper::getMicrotime();
  330. CrontabTaskExecute::updateProcess($task['id'], CrontabTaskExecute::PROCESS_FINISH, null,json_encode($output, JSON_UNESCAPED_UNICODE), time(),abs($running_time/1000));
  331. }else{
  332. CrontabTaskExecute::updateProcess($task['id'], CrontabTaskExecute::PROCESS_FAIL,null,json_encode($output, JSON_UNESCAPED_UNICODE));
  333. }
  334. });
  335. });
  336. }
  337. }
  338. }