工作进程退出

@param  \Swoole\Server   $server
@param  int              $workerId
483992
public function onWorkerExit(SwServer $server, int $workerId)
    {
        // {{ log
        $this->get('logger')->info('Worker 进程重启退出', [
            'id' => $workerId
        ]);
        // }}

        $this->callProtocolMethod('onExit', $server, $workerId);
    }
1272495
public function onSwooleTask($serv, $task_id, $from_id, $data)
    {
        $type = $data['type'] ?? '';
        $message = $data['message'] ?? '';
        switch ($type) {
            case SwooleMarco::MSG_TYPE_SEND_BATCH://发送消息
                foreach ($message['fd'] as $fd) {
                    $this->send($fd, $message['data'], true);
                }

                return null;
            case SwooleMarco::MSG_TYPE_SEND_ALL://发送广播
                foreach ($this->uid_fd_table as $row) {
                    $this->send($row['fd'], $message['data'], true);
                }

                return null;
            case SwooleMarco::MSG_TYPE_SEND_ALL_FD://发送广播
                foreach ($serv->connections as $fd) {
                    $this->send($fd, $message['data'], true);
                }

                return null;
            case SwooleMarco::SERVER_TYPE_TASK://task任务
                $task_name = $message['task_name'];
                $task = $this->loader->task($task_name, $this);
                $task_fuc_name = $message['task_fuc_name'];
                $task_data = $message['task_fuc_data'];
                $task_context = $message['task_context'];
                $call = [$task->getProxy(), $task_fuc_name];
                if (is_callable($call)) {
                    //给task做初始化操作
                    $task->initialization($task_id, $from_id, $this->server->worker_pid, $task_name, $task_fuc_name, $task_context);
                    $result = sd_call_user_func_array($call, $task_data);
                } else {
                    throw new SwooleException("method $task_fuc_name not exist in $task_name");
                }
                $task->destroy();

                return $result;
            default:
                return parent::onSwooleTask($serv, $task_id, $from_id, $data);
        }
    }
511912
public function onWorkerError(SwServer $server, int $workerId, int $workerPid, int $exitCode)
    {
        $workerType = $server->taskworker ? 'task' : 'worker';

        // {{ log
        $this->get('logger')->info('Worker 进程异常退出', [
            'id' => $workerId,
            'pid' => $workerPid,
            'type' => ucfirst($workerType),
            'exitcode' => $exitCode,
        ]);
        // }}

        unset($workerType);

        $this->callProtocolMethod('onError', $server, $workerId);
    }
133387
protected function unregisterJob(string $jobName, string $workerId) : bool
    {
        if (!isset($this->workerJobCapabilities[$jobName])) {
            return true;
        }
        if (($key = array_search($workerId, $this->workerJobCapabilities[$jobName])) !== false) {
            unset($this->workerJobCapabilities[$jobName][$key]);
        }
        if (empty($this->workerJobCapabilities[$jobName])) {
            unset($this->workerJobCapabilities[$jobName]);
        }
        return true;
    }
606054
public function onWorkerStop(SwooleServer $server, $worker_id)
    {
        //不能在这里处理 coroutine ，所以不能使用 Yii::$app
        $contexts = Yii::$context->getContextData();
        foreach ($contexts as $context){
            /** @var Application $application */
            $application = $context[Context::COROUTINE_APP] ?? null;
            if(empty($application)){
                continue;
            }
            $targets = $application->getLog()->targets;
            foreach ($targets as $target) {
                $target->export();
            }
        }

    }
836443
public function onConnect(SwServer $server, int $fd, int $reactorId)
    {
        // {{ log
        $this->get('logger')->info('连接接入', $server->getClientInfo($fd));
        // }}

        $this->callProtocolMethod('onConnect', $server, $fd, $fromId);
    }
442380
public function onWorkerStart(Server $server, int $workerId)
    {
        // Init Worker and TaskWorker
        $setting = $server->setting;
        $isWorker = false;

        if ($workerId >= $setting['worker_num']) {
            // TaskWorker
            ApplicationContext::setContext(ApplicationContext::TASK);
            ProcessHelper::setProcessTitle($this->serverSetting['pname'] . ' task process');
        } else {
            // Worker
            $isWorker = true;
            ApplicationContext::setContext(ApplicationContext::WORKER);
            ProcessHelper::setProcessTitle($this->serverSetting['pname'] . ' worker process');
        }

        $this->beforeWorkerStart($server, $workerId, $isWorker);

        $this->fireServerEvent(SwooleEvent::ON_WORKER_START, [$server, $workerId, $isWorker]);
    }
870158
public function onWorkerStart($server)
    {
        $this->clearCache();

        $this->container->make('events')->dispatch('swoole.workerStart', func_get_args());

        // don't init laravel app in task workers
        if ($server->taskworker) {
            $this->setProcessName('task process');

            return;
        }
        $this->setProcessName('worker process');

        // clear events instance in case of repeated listeners in worker process
        Facade::clearResolvedInstance('events');

        // prepare laravel app
        $this->getApplication();

        // bind after setting laravel app
        $this->bindToLaravelApp();

        // prepare websocket handler and routes
        if ($this->isServerWebsocket) {
            $this->prepareWebsocketHandler();
            $this->loadWebsocketRoutes();
        }
    }
1006234
public static function postWait(TaskInfo $taskInfo, $timeout, $workerID = -1)
    {
        $server = ServerManage::getServer('main')->getSwooleServer();
        $result = $server->taskwait($taskInfo, $timeout, $workerID);
        call_user_func([$taskInfo->getTaskHandler(), 'finish'], $server, -1, $result);
        return $result;
    }
821808
private function setWorkerID($workerID)
    {
        if ($workerID >= 1 &&
            $workerID <= 255
        ) {
            return (int)$workerID;
        } elseif ($workerID !== null) {
            throw new \InvalidArgumentException('WorkerID out of range (1-255)');
        }
        return rand(1, 255);
    }
704098
protected function runWorker($id, $pid)
    {
        $this->isWorker = true;
        $this->isMaster = false;

        $this->id = $id;
        $this->masterPid = $this->pid;
        $this->pid = getmypid();

        $eCode = $this->receiveTasks($this->queue);

        $this->log("Worker #$id exited(Exit-Code:$eCode)", ProcessLogger::PROC_INFO);
        $this->quit($eCode);
    }
115832
public function onReceive(SwServer $server, int $fd, int $fromId, string $data)
    {
        // {{ log
        $this->get('logger')->info('接收数据', [
            'type' => 'TCP',
            'client' => $server->getClientInfo($fd),
            'data' => $data
        ]);
        // }}

        $this->callProtocolMethod('onReceive', $server, $fd, $fromId, $data);
    }
151056
public function onSwooleWorkerError($serv, $worker_id, $worker_pid, $exit_code)
    {
        $data = ['worker_id' => $worker_id,
            'worker_pid' => $worker_pid,
            'exit_code' => $exit_code];
        $log = "WORKER Error ";
        $log .= json_encode($data);
        $this->log->alert($log);
        if ($this->onErrorHandel != null) {
            sd_call_user_func($this->onErrorHandel, '【！！！】服务器进程异常退出', $log);
        }
    }
359172
public function __start(\swoole\Server $server) {
        $pid = posix_getpid();
        file_put_contents($this->options['enable_pid'], $pid);

        if(method_exists($this->callback,'start')) {
            $this->callback->start($server);
        }
    }
945933
protected function reportWorkerError($workerId, $workerPid, $exitCode, $signal)
    {
        $this->handleException(new WorkerExitUnexpectedException(sprintf(
            'The worker %d quit unexpected with exit code %d, signal %d, pid %d.',
            $workerId, $exitCode, $signal, $workerPid
        )));
    }
146923
public static function post(TaskInfo $taskInfo, $workerID = -1)
    {
        return ServerManage::getServer('main')->getSwooleServer()->task($taskInfo, $workerID, [$taskInfo->getTaskHandler(), 'finish']);
    }
691775
public function onStart(Server $server): void
    {
        $this->fire(ServerEvent::STARTED, $server);

        $this->masterPid = $masterPid = $server->master_pid;
        $rootPath        = $this->config('rootPath');
        $rootPath        = $rootPath ? " (at $rootPath)" : '';

        // save master process id to file.
        ProcessUtil::setTitle(sprintf('%s: master%s', $this->name, $rootPath));

        $this->log("The <comment>master</comment> process success started. (PID:<info>{$masterPid}</info>, pidFile: $this->pidFile)");
    }