PullCode.php 2.5 KB
<?php

namespace App\Console\Commands;

use App\Repositories\BtRepository;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class PullCode extends Command
{
    protected $signature = 'pull_code';
    protected $description = '自动拉取代码';


    public function handle()
    {
        //查询更新代码任务
        $is_pull = Redis::get('pull_code');
        if (!$is_pull) {
            return true;
        }

        try {
            //拉取代码
            $this->pullCode();

            if ($is_pull > 1) {
                //重启进程
                $this->resetProcess();
            }
        } catch (\Exception $e) {
            Log::error('pull_code | error:' . $e->getMessage());
            $this->output($e->getMessage());
        }

        Redis::set('pull_code', 0);
        return true;
    }

    /**
     * 拉取代码
     * @return bool
     * @author Akun
     * @date 2024/08/14 16:00
     */
    public function pullCode()
    {
        $this->output('自动拉取代码: start.');

        if(env('BT_PANEL') == 'http://112.74.203.101:8888'){
            $shell = "cd /www/wwwroot/ai.cc && sudo git checkout . && sudo git pull 2>&1";
        }else{
            $shell = "cd /www/wwwroot/self_site && sudo git checkout . && sudo git pull 2>&1";
        }

        exec($shell, $out);
        dump($out);

        $this->output('自动拉取代码: end.');

        return true;
    }

    /**
     * 重启进程
     * @author Akun
     * @date 2025/06/13 16:56
     */
    public function resetProcess()
    {
        $this->output('重启进程: start.');

        $bt_repository = new BtRepository();
        $bt = $bt_repository->getBtObject();

        $list = $bt->getProcessList();
        foreach ($list as $value) {
            $process_name = $value['program'];
            $process_num = $value['numprocs'];

            $re_stop = $bt->stopProcess($process_name, $process_num);
            $re_stop_msg = $re_stop['msg'] ?? '';
            $this->output($value['ps'] . '-' . $re_stop_msg);

            $re_start = $bt->startProcess($process_name, $process_num);
            $re_start_msg = $re_start['msg'] ?? '';
            $this->output($value['ps'] . '-' . $re_start_msg);
        }

        $this->output('重启进程: end.');
    }

    /**
     * 输出处理日志
     * @param $message
     */
    public function output($message)
    {
        echo date('Y-m-d H:i:s') . ' | ' . $message . PHP_EOL;
    }
}