SwooleTask.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Services\Api\FinanceService;
  4. use App\Services\Api\PledgeOrderService;
  5. use App\Services\Api\PriceLogService;
  6. use App\Services\RedisService;
  7. use App\Services\WalletService;
  8. use Illuminate\Console\Command;
  9. use Illuminate\Support\Facades\DB;
  10. class SwooleTask extends Command
  11. {
  12. protected $serv;
  13. protected $host = '127.0.0.1';
  14. protected $port = 6630;
  15. // 进程名称
  16. protected $taskName = 'swooleTask';
  17. // PID路径
  18. protected $pidPath = '/storage/swoole.pid';
  19. // task
  20. protected $onlyReloadTaskWorker = false;
  21. // 设置运行时参数
  22. protected $options = [
  23. 'worker_num' => 8, //worker进程数,一般设置为CPU数的1-4倍
  24. 'daemonize' => true, //启用守护进程
  25. 'log_file' => '/storage/logs/swoole-task.log', //指定swoole错误日志文件
  26. 'log_level' => 0, //日志级别 范围是0-5,0-DEBUG,1-TRACE,2-INFO,3-NOTICE,4-WARNING,5-ERROR
  27. 'dispatch_mode' => 1, //数据包分发策略,1-轮询模式
  28. 'task_worker_num' => 6, //task进程的数量
  29. 'task_ipc_mode' => 3, //使用消息队列通信,并设置为争抢模式
  30. ];
  31. /**
  32. * The name and signature of the console command.
  33. *
  34. * @var string
  35. */
  36. protected $signature = 'swoole:task {op}';
  37. /**
  38. * The console command description.
  39. *
  40. * @var string
  41. */
  42. protected $description = 'Swoole task server description';
  43. /**
  44. * Create a new command instance.
  45. *
  46. * @return void
  47. */
  48. public function __construct()
  49. {
  50. parent::__construct();
  51. }
  52. /**
  53. * 入口
  54. * Execute the console command.
  55. *
  56. * @return mixed
  57. */
  58. public function handle()
  59. {
  60. ini_set("default_socket_timeout", -1);
  61. // 项目根目录
  62. defined('ROOT_PATH') or define('ROOT_PATH', base_path());
  63. // 文件上传目录
  64. defined('ATTACHMENT_PATH') or define('ATTACHMENT_PATH', base_path('public/uploads'));
  65. // 图片上传目录
  66. defined('IMG_PATH') or define('IMG_PATH', base_path('public/uploads/images'));
  67. // 临时存放目录
  68. defined('UPLOAD_TEMP_PATH') or define('UPLOAD_TEMP_PATH', ATTACHMENT_PATH . "/temp");
  69. // 定义普通图片域名
  70. defined('IMG_URL') or define('IMG_URL', env('IMG_URL'));
  71. // 数据表前缀
  72. defined('DB_PREFIX') or define('DB_PREFIX', DB::connection()->getTablePrefix());
  73. $this->options['log_file'] = base_path() . $this->options['log_file'];
  74. $this->pidPath = base_path() . $this->pidPath;
  75. $op = $this->argument('op');
  76. switch ($op) {
  77. case 'status': // 状态
  78. $res = $this->status();
  79. echo $res ? $res : 0;
  80. break;
  81. case 'start': // 运行
  82. return $this->start();
  83. break;
  84. case 'reload': // 平滑重启
  85. return $this->reload();
  86. break;
  87. case 'stop': // 停止运行
  88. return $this->stop();
  89. break;
  90. default:
  91. exit("{$op} command does not exist");
  92. break;
  93. }
  94. }
  95. /**
  96. * 启动
  97. */
  98. public function start()
  99. {
  100. date_default_timezone_set('PRC');
  101. // 构建Server对象,监听对应地址
  102. $this->serv = new \Swoole\Server($this->host, $this->port);
  103. $this->serv->set($this->options);
  104. // 注册事件
  105. $this->serv->on('start', [$this, 'onStart']);
  106. $this->serv->on('receive', [$this, 'onReceive']);
  107. $this->serv->on('task', [$this, 'onTask']);
  108. $this->serv->on('finish', [$this, 'onFinish']);
  109. // Run worker
  110. echo "swoole start...\n";
  111. $this->serv->start();
  112. }
  113. // 安全重启
  114. public function reload()
  115. {
  116. $pids = file_exists($this->pidPath) ? file_get_contents($this->pidPath) : '';
  117. $pids = $pids ? explode("\n", $pids) : [];
  118. $masterPid = isset($pids[0]) ? $pids[0] : '';
  119. $managePid = isset($pids[1]) ? $pids[1] : '';
  120. if (empty($masterPid)) {
  121. return false;
  122. }
  123. if (!$this->status($masterPid)) {
  124. return false;
  125. }
  126. \Swoole\Process::kill($managePid, SIGUSR1);
  127. echo "swoole reload...\n";
  128. }
  129. /**
  130. * 停止
  131. * @param bool $smooth
  132. * @return bool
  133. */
  134. public function stop($smooth = false)
  135. {
  136. $pids = file_exists($this->pidPath) ? file_get_contents($this->pidPath) : '';
  137. $pids = $pids ? explode("\n", $pids) : [];
  138. $masterPid = isset($pids[0]) ? $pids[0] : '';
  139. $managePid = isset($pids[1]) ? $pids[1] : '';
  140. if (empty($masterPid)) {
  141. return false;
  142. }
  143. if (!$this->status($masterPid)) {
  144. return false;
  145. }
  146. // 直接杀
  147. $stoSh = base_path().'/crontab/swooleTaskStop.sh';
  148. echo $stoSh;
  149. if(file_exists($stoSh) && function_exists('exec')){
  150. exec("{$stoSh}");
  151. }
  152. @unlink($this->pidPath);
  153. echo "swoole stop...\n";
  154. }
  155. /**
  156. * 状态
  157. * @return mixed
  158. */
  159. public function status($masterPid = 0)
  160. {
  161. $res = false;
  162. if (empty($masterPid) && file_exists($this->pidPath)) {
  163. $pids = file_get_contents($this->pidPath);
  164. $pids = $pids ? explode("\n", $pids) : [];
  165. $masterPid = isset($pids[0]) ? $pids[0] : '';
  166. }
  167. if ($masterPid) {
  168. $res = \Swoole\Process::kill($masterPid, 0);
  169. }
  170. return $res;
  171. }
  172. public function onStart($serv)
  173. {
  174. if (!is_dir(dirname($this->pidPath))) {
  175. @mkdir(dirname($this->pidPath), true, 755);
  176. }
  177. //记录进程id,脚本实现自动重启
  178. $pid = "{$serv->master_pid}\n{$serv->manager_pid}";
  179. file_put_contents($this->pidPath, $pid);
  180. // 定时任务
  181. $time = 0;
  182. $date = date('Y-m-d H:i:s');
  183. if(file_exists($this->options['log_file'])){
  184. $time = 0;
  185. file_put_contents($this->options['log_file'],"Task {$date}:清空日志\n");
  186. }
  187. // TODO 更新SBT每日价格
  188. \swoole_timer_tick(300000, function ($timer) use ($serv, &$time) { // 启用定时器,每5分钟执行一次
  189. $date = date('Y-m-d H:i:s');
  190. if($time>3600 && file_exists($this->options['log_file'])){
  191. $time = 0;
  192. file_put_contents($this->options['log_file'],"Task {$date}:清空日志\n");
  193. }
  194. $time++;
  195. if(!RedisService::get('caches:task:lock:sbt_loaded')){
  196. $taskData = [
  197. 'taskName' => 'UpdateSbtPrice',
  198. 'name' => "更新SBT每日价格",
  199. 'date' => date('Y-m-d'),
  200. ];
  201. $res = $serv->task($taskData);
  202. RedisService::set('caches:task:lock:sbt_loaded', true, rand(3,5));
  203. echo "[Task UpdateSbtPrice {$date}] 更新SBT每日价格:{$res}\n";
  204. }else{
  205. echo "[Task UpdateSbtPrice {$date}] 间隔时间调用\n";
  206. }
  207. });
  208. // TODO 检测质押订单退本,到期退本后(USDT余额足够)自动质押
  209. \swoole_timer_tick(180000, function ($timer) use ($serv, &$time) { // 启用定时器,每3分钟执行一次
  210. $date = date('Y-m-d H:i:s');
  211. if($time>3600 && file_exists($this->options['log_file'])){
  212. $time = 0;
  213. file_put_contents($this->options['log_file'],"Task {$date}:清空日志\n");
  214. }
  215. $time++;
  216. if(!RedisService::get('caches:task:lock:plende_refund_loaded')){
  217. $taskData = [
  218. 'taskName' => 'PledgeRefund',
  219. 'name' => "质押订单退本",
  220. 'date' => date('Y-m-d'),
  221. ];
  222. $res = $serv->task($taskData);
  223. RedisService::set('caches:task:lock:plende_refund_loaded', true, rand(3,5));
  224. echo "[Task PledgeRefund {$date}] 质押订单退本:{$res}\n";
  225. }else{
  226. echo "[Task PledgeRefund {$date}] 间隔时间调用\n";
  227. }
  228. });
  229. // TODO 质押订单到期结算收益,同时发放奖励(质押收益、推荐奖、管理奖、平级奖-基于管理奖)
  230. \swoole_timer_tick(120000, function ($timer) use ($serv, &$time) { // 启用定时器,每120秒执行一次
  231. $date = date('Y-m-d H:i:s');
  232. if($time>3600 && file_exists($this->options['log_file'])){
  233. $time = 0;
  234. file_put_contents($this->options['log_file'],"Task {$date}:清空日志\n");
  235. }
  236. $time++;
  237. if(!RedisService::get('caches:task:lock:pledge_settle_loaded')){
  238. $taskData = [
  239. 'taskName' => 'PledgeSettle',
  240. 'name' => "质押订单到期结算",
  241. 'date' => date('Y-m-d'),
  242. ];
  243. $res = $serv->task($taskData);
  244. RedisService::set('caches:task:lock:pledge_settle_loaded', true, rand(3,5));
  245. echo "[Task PledgeSettle {$date}] 质押订单到期结算:{$res}\n";
  246. }else{
  247. echo "[Task PledgeSettle {$date}] 间隔时间调用\n";
  248. }
  249. });
  250. }
  251. //监听连接进入事件
  252. public function onConnect($serv, $fd, $from_id)
  253. {
  254. $serv->send($fd, "Success {$fd}!");
  255. }
  256. // 监听数据接收事件
  257. public function onReceive(\Swoole\Server $serv, $fd, $from_id, $data)
  258. {
  259. echo "Get Message From Client {$fd}:{$data}\n";
  260. $res['result'] = 'success';
  261. $serv->send($fd, json_encode($res)); // 同步返回消息给客户端
  262. $serv->task($data); // 执行异步任务
  263. }
  264. /**
  265. * @param \Swoole\Server $serv
  266. * @param $task_id
  267. * @param $from_id
  268. * @param $data
  269. * @return false|string
  270. */
  271. public function onTask(\Swoole\Server $serv, $task_id, $from_id, $data)
  272. {
  273. $date = date('Y-m-d H:i:s');
  274. $taskName = isset($data['taskName']) ? $data['taskName'] : '';
  275. try {
  276. switch ($taskName) {
  277. case 'UpdateSbtPrice': // 更新SBT每日价格
  278. // 时间限制
  279. if(date('H:i') >= '00:00' && date('H:i') <= '03:00'){
  280. echo "[Task {$taskName} {$date}] 不在运行时间段内\n";
  281. return false;
  282. }
  283. // 调用处理
  284. if($res = PriceLogService::make()->updateSbtPrice()){
  285. $res = is_array($res) && $res? json_encode($res, 256) : '处理成功';
  286. echo "[Task {$taskName} {$date}] 更新SBT每日价格:{$res}\n";
  287. }else{
  288. $error = PriceLogService::make()->getError();
  289. $error = $error? lang($error) : '处理失败';
  290. echo "[Task {$taskName} {$date}] 更新SBT每日价格:{$error}\n";
  291. }
  292. break;
  293. case 'PledgeRefund': // 质押订单退本,退本后自动再质押处理
  294. // 时间限制
  295. if(date('H:i') <= '04:00' || (date('H:i') >= '08:00' && date('H:i') <= '20:00')){
  296. echo "[Task {$taskName} {$date}] 不在运行时间段内\n";
  297. return false;
  298. }
  299. // 调用处理
  300. if($res = PledgeOrderService::make()->refundAndBuy()){
  301. $res = is_array($res) && $res? json_encode($res, 256) : '处理成功';
  302. echo "[Task {$taskName} {$date}] 质押订单退本和自动质押:{$res}\n";
  303. }else{
  304. $error = PledgeOrderService::make()->getError();
  305. $error = $error? lang($error) : '处理失败';
  306. echo "[Task {$taskName} {$date}] 质押订单退本和自动质押:{$error}\n";
  307. }
  308. break;
  309. case 'PledgeSettle': // 质押订单到期结算,和收益、奖励结算
  310. // 时间限制
  311. if(date('H:i') >= '01:00' && date('H:i') <= '02:00'){
  312. echo "[Task {$taskName} {$date}] 不在运行时间段内\n";
  313. return false;
  314. }
  315. // 调用处理
  316. if($res = PledgeOrderService::make()->orderSettle(true)){
  317. $res = is_array($res) && $res? json_encode($res, 256) : '处理成功';
  318. echo "[Task {$taskName} {$date}] 质押订单到期结算和收益、奖励结算:{$res}\n";
  319. }else{
  320. $error = PledgeOrderService::make()->getError();
  321. $error = $error? lang($error) : '处理失败';
  322. echo "[Task {$taskName} {$date}] 质押订单到期结算和收益、奖励结算:{$error}\n";
  323. }
  324. break;
  325. }
  326. } catch(\Exception $exception){
  327. return $exception->getMessage();
  328. }
  329. return '暂无任务处理';
  330. }
  331. /**
  332. * @param $serv swoole_server swoole_server对象
  333. * @param $task_id int 任务id
  334. * @param $data string 任务返回的数据
  335. */
  336. public function onFinish(\Swoole\Server $serv, $task_id, $data)
  337. {
  338. //
  339. echo "任务处理完成...\n";
  340. }
  341. // 监听连接关闭事件
  342. public function onClose($serv, $fd, $from_id)
  343. {
  344. echo "Client {$fd} close connection\n";
  345. $serv->close();
  346. }
  347. }