WalletTask.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Services\RedisService;
  4. use App\Services\WalletService;
  5. use Illuminate\Console\Command;
  6. use Illuminate\Support\Facades\DB;
  7. class WalletTask extends Command
  8. {
  9. protected $serv;
  10. protected $host = '127.0.0.1';
  11. protected $port = 6632;
  12. // 进程名称
  13. protected $taskName = 'walletTask';
  14. // PID路径
  15. protected $pidPath = '/storage/wallet.pid';
  16. // task
  17. protected $onlyReloadTaskWorker = false;
  18. // 设置运行时参数
  19. protected $options = [
  20. 'worker_num' => 8, //worker进程数,一般设置为CPU数的1-4倍
  21. 'daemonize' => true, //启用守护进程
  22. 'log_file' => '/storage/logs/wallet-task.log', //指定swoole错误日志文件
  23. 'log_level' => 0, //日志级别 范围是0-5,0-DEBUG,1-TRACE,2-INFO,3-NOTICE,4-WARNING,5-ERROR
  24. 'dispatch_mode' => 1, //数据包分发策略,1-轮询模式
  25. 'task_worker_num' => 6, //task进程的数量
  26. 'task_ipc_mode' => 3, //使用消息队列通信,并设置为争抢模式
  27. ];
  28. /**
  29. * The name and signature of the console command.
  30. *
  31. * @var string
  32. */
  33. protected $signature = 'wallet:task {op}';
  34. /**
  35. * The console command description.
  36. *
  37. * @var string
  38. */
  39. protected $description = 'Solana 钱包监控服务';
  40. /**
  41. * Create a new command instance.
  42. *
  43. * @return void
  44. */
  45. public function __construct()
  46. {
  47. parent::__construct();
  48. }
  49. /**
  50. * 入口
  51. * Execute the console command.
  52. *
  53. * @return mixed
  54. */
  55. public function handle()
  56. {
  57. ini_set("default_socket_timeout", -1);
  58. // 项目根目录
  59. defined('ROOT_PATH') or define('ROOT_PATH', base_path());
  60. // 文件上传目录
  61. defined('ATTACHMENT_PATH') or define('ATTACHMENT_PATH', base_path('public/uploads'));
  62. // 图片上传目录
  63. defined('IMG_PATH') or define('IMG_PATH', base_path('public/uploads/images'));
  64. // 临时存放目录
  65. defined('UPLOAD_TEMP_PATH') or define('UPLOAD_TEMP_PATH', ATTACHMENT_PATH . "/temp");
  66. // 定义普通图片域名
  67. defined('IMG_URL') or define('IMG_URL', env('IMG_URL'));
  68. // 数据表前缀
  69. defined('DB_PREFIX') or define('DB_PREFIX', DB::connection()->getTablePrefix());
  70. $this->options['log_file'] = base_path() . $this->options['log_file'];
  71. $this->pidPath = base_path() . $this->pidPath;
  72. $op = $this->argument('op');
  73. switch ($op) {
  74. case 'status': // 状态
  75. $res = $this->status();
  76. echo $res ? $res : 0;
  77. break;
  78. case 'start': // 运行
  79. return $this->start();
  80. break;
  81. case 'reload': // 平滑重启
  82. return $this->reload();
  83. break;
  84. case 'stop': // 停止运行
  85. return $this->stop();
  86. break;
  87. default:
  88. exit("{$op} command does not exist");
  89. break;
  90. }
  91. }
  92. /**
  93. * 启动
  94. */
  95. public function start()
  96. {
  97. date_default_timezone_set('PRC');
  98. // 构建Server对象,监听对应地址
  99. $this->serv = new \Swoole\Server($this->host, $this->port);
  100. $this->serv->set($this->options);
  101. // 注册事件
  102. $this->serv->on('start', [$this, 'onStart']);
  103. $this->serv->on('receive', [$this, 'onReceive']);
  104. $this->serv->on('task', [$this, 'onTask']);
  105. $this->serv->on('finish', [$this, 'onFinish']);
  106. // Run worker
  107. echo "wallet start...\n";
  108. $this->serv->start();
  109. }
  110. // 安全重启
  111. public function reload()
  112. {
  113. $pids = file_exists($this->pidPath) ? file_get_contents($this->pidPath) : '';
  114. $pids = $pids ? explode("\n", $pids) : [];
  115. $masterPid = isset($pids[0]) ? $pids[0] : '';
  116. $managePid = isset($pids[1]) ? $pids[1] : '';
  117. if (empty($masterPid)) {
  118. return false;
  119. }
  120. if (!$this->status($masterPid)) {
  121. return false;
  122. }
  123. \Swoole\Process::kill($managePid, SIGUSR1);
  124. echo "wallet reload...\n";
  125. }
  126. /**
  127. * 停止
  128. * @param bool $smooth
  129. * @return bool
  130. */
  131. public function stop($smooth = false)
  132. {
  133. $pids = file_exists($this->pidPath) ? file_get_contents($this->pidPath) : '';
  134. $pids = $pids ? explode("\n", $pids) : [];
  135. $masterPid = isset($pids[0]) ? $pids[0] : '';
  136. $managePid = isset($pids[1]) ? $pids[1] : '';
  137. if (empty($masterPid)) {
  138. return false;
  139. }
  140. if (!$this->status($masterPid)) {
  141. return false;
  142. }
  143. // 直接杀
  144. $stoSh = base_path().'/crontab/walletTaskStop.sh';
  145. if(file_exists($stoSh) && function_exists('exec')){
  146. exec("{$stoSh}");
  147. }
  148. // 清除分页
  149. $wallets = WalletService::make()->getWalletList();
  150. if($wallets){
  151. foreach ($wallets as $item){
  152. RedisService::clear('caches:wallet:listen_recharge_page_'.$item['address']);
  153. }
  154. }
  155. @unlink($this->pidPath);
  156. echo "wallet stop...\n";
  157. }
  158. /**
  159. * 状态
  160. * @return mixed
  161. */
  162. public function status($masterPid = 0)
  163. {
  164. $res = false;
  165. if (empty($masterPid) && file_exists($this->pidPath)) {
  166. $pids = file_get_contents($this->pidPath);
  167. $pids = $pids ? explode("\n", $pids) : [];
  168. $masterPid = isset($pids[0]) ? $pids[0] : '';
  169. }
  170. if ($masterPid) {
  171. $res = \Swoole\Process::kill($masterPid, 0);
  172. }
  173. return $res;
  174. }
  175. public function onStart($serv)
  176. {
  177. if (!is_dir(dirname($this->pidPath))) {
  178. @mkdir(dirname($this->pidPath), true, 755);
  179. }
  180. //记录进程id,脚本实现自动重启
  181. $pid = "{$serv->master_pid}\n{$serv->manager_pid}";
  182. file_put_contents($this->pidPath, $pid);
  183. // 定时任务
  184. $time = 0;
  185. $date = date('Y-m-d H:i:s');
  186. if(file_exists($this->options['log_file'])){
  187. $time = 0;
  188. file_put_contents($this->options['log_file'],"Task {$date}:清空日志\n");
  189. }
  190. \swoole_timer_tick(10000, function ($timer) use ($serv, &$time) { // 启用定时器,每10秒执行一次
  191. $date = date('Y-m-d H:i:s');
  192. if($time>6*3600 && file_exists($this->options['log_file'])){
  193. $time = 0;
  194. file_put_contents($this->options['log_file'],"Task {$date}:清空日志\n");
  195. }
  196. $time++;
  197. $wallets = WalletService::make()->getWalletList();
  198. if($wallets){
  199. if(!RedisService::get('caches:task:lock:wallet_loaded')){
  200. foreach ($wallets as $item){
  201. $taskData = [
  202. 'taskName' => 'listenWallet',
  203. 'name' => "平台钱包地址监控",
  204. 'params' => $item,
  205. 'date' => date('Y-m-d'),
  206. ];
  207. $res = $serv->task($taskData);
  208. }
  209. RedisService::set('caches:task:lock:wallet_loaded', true, rand(3,5));
  210. echo "[Task listenWallet {$date}] 平台钱包地址监控调用完成:{$res}\n";
  211. }else{
  212. echo "[Task listenWallet {$date}] 间隔时间调用\n";
  213. }
  214. }else{
  215. echo "[Task listenWallet {$date}] 钱包地址未配置\n";
  216. }
  217. });
  218. }
  219. //监听连接进入事件
  220. public function onConnect($serv, $fd, $from_id)
  221. {
  222. $serv->send($fd, "Success {$fd}!");
  223. }
  224. // 监听数据接收事件
  225. public function onReceive(\Swoole\Server $serv, $fd, $from_id, $data)
  226. {
  227. echo "Get Message From Client {$fd}:{$data}\n";
  228. $res['result'] = 'success';
  229. $serv->send($fd, json_encode($res)); // 同步返回消息给客户端
  230. $serv->task($data); // 执行异步任务
  231. }
  232. /**
  233. * @param \Swoole\Server $serv
  234. * @param $task_id
  235. * @param $from_id
  236. * @param $data
  237. * @return false|string
  238. */
  239. public function onTask(\Swoole\Server $serv, $task_id, $from_id, $data)
  240. {
  241. $date = date('Y-m-d H:i:s');
  242. $taskName = isset($data['taskName']) ? $data['taskName'] : '';
  243. $params = isset($data['params']) ? $data['params'] : [];
  244. switch ($taskName) {
  245. case 'listenWallet': // 钱包监控
  246. $address = isset($params['address'])? $params['address'] : '';
  247. $type = isset($params['type'])? $params['type'] : 1;
  248. if(empty($address)){
  249. echo "[Task {$taskName}-{$task_id} {$date}] address 地址参数错误\n";
  250. return false;
  251. }
  252. // 调用处理
  253. if($res = WalletService::make()->listenWallet($address, $type, 0)){
  254. $success = isset($res['success'])? $res['success'] : 0;
  255. $total = isset($res['total'])? $res['total'] : 0;
  256. echo "[Task {$taskName}-{$task_id} {$date}] 钱包地址[{$address}]监控处理结果:".($total? "监控{$total}条记录,成功处理{$success}条":'success')."\n";
  257. }else{
  258. $error = WalletService::make()->getError();
  259. $error = $error? lang($error) : 'failed';
  260. echo "[Task {$taskName}-{$task_id} {$date}] 钱包地址[{$address}]监控处理结果:{$error}\n";
  261. }
  262. break;
  263. }
  264. return "[Task {$taskName}-{$task_id} {$date}] 暂无任务处理\n";
  265. }
  266. /**
  267. * @param $serv swoole_server swoole_server对象
  268. * @param $task_id int 任务id
  269. * @param $data string 任务返回的数据
  270. */
  271. public function onFinish(\Swoole\Server $serv, $task_id, $data)
  272. {
  273. //
  274. echo "任务[{$task_id}]处理完成...\n";
  275. }
  276. // 监听连接关闭事件
  277. public function onClose($serv, $fd, $from_id)
  278. {
  279. echo "Client {$fd} close connection\n";
  280. $serv->close();
  281. }
  282. }