Analysis of easyswoole source code (startup service)

Posted by Serberus on Mon, 06 Jan 2020 18:09:39 +0100

Previous link When reading, it is better to refer to the source code of easysoole 2.1.2

$inst->run();//Startup service

The actual call here is the start method servermanager:: getinstance() - > start();

This method is mainly used to start the swoole service

//Create master service
$this->createMainServer();

In this code, the core is to set the relevant configuration and configure the relevant callback function before the start service is executed by swoole. The specific code is as follows

First, configure the relevant operation parameters for the server

$conf = Config::getInstance()->getConf("MAIN_SERVER");//Obtain Config.php Configured in MAIN_SERVER array
$runModel = $conf['RUN_MODEL'];//Get run mode default is SWOOLE_PROCESS Pattern,Using process mode, the business code is Worker In process execution
$host = $conf['HOST'];//Get running host 'HOST'=>'0.0.0.0',
$port = $conf['PORT'];//The operation port to get the configuration is 9501 'PORT'=>9501,
$setting = $conf['SETTING'];//The related configuration items set here are explained,Reference https://wiki.swoole.com/wiki/page/274.html
'SETTING'=>[
         'task_worker_num' => 8, //To configure Task Number of processes, which will be enabled after this parameter is configured task Function. therefore Server Be sure to register onTask,onFinish2 Event callback functions. If not registered, the server program will not start.
         'task_max_request'=>10,//Set up task The maximum number of tasks for the process. One task The process will automatically exit after processing tasks that exceed this value. This parameter is to prevent PHP Process memory overflow. If you don't want the process to exit automatically, you can set it to 0. It's important to fry the chicken. If there is a global Array, or global variable, if this is not set, it will not be recycled, resulting in memory overflow
         'max_request'=>5000,//Set up worker The maximum number of tasks for the process, and task_max_request The function is the same, in order to solve PHP Process memory overflow
         'worker_num'=>8//Set up started Worker Process number
       ],
//In fact, there are also two configurations mentioned in the previous article, in line 19 of the previous article $this->sysDirectoryInit();Configuration will be initialized pid_file and log_file
pid_file //stay Server Start automatically master Process PID Write to file, on Server Automatically delete on close PID Papers.
log_file //Appoint swoole Error log file. stay swoole The exception information during the run time will be recorded in this file. It will print to the screen by default.
$sockType = $conf['SOCK_TYPE'];//Specifies what server the currently running service is. Yes tcp Service, http Service, websocket Service. The default is tcp service
switch ($conf['SERVER_TYPE']){
  case self::TYPE_SERVER:{
    $this->mainServer = new \swoole_server($host,$port,$runModel,$sockType);//Establish mainServer,Here we create a tcp The server
       break;
   }
  case self::TYPE_WEB_SERVER:{
    $this->mainServer = new \swoole_http_server($host,$port,$runModel,$sockType);//web mode is the default
       break;
   }
  case self::TYPE_WEB_SOCKET_SERVER:{
       $this->mainServer = new \swoole_websocket_server($host,$port,$runModel,$sockType);
       break;
   }
  default:{
    Trigger::throwable(new \Exception("unknown server type :{$conf['SERVER_TYPE']}"));
  }
}
$this->mainServer->set($setting);//Configure the above related service startup to mainServer

Create a default event registrar and register the service with an event handler by default

$register = new EventRegister();
$this->finalHook($register);
EasySwooleEvent::mainServerCreate($this,$register);//This is the framework global event mainServerCreate Master service creation event
 $events = $register->all();
//And then cycle to swoole Server binding callback function. Here, the same callback method sets multiple callback functions
foreach ($events as $event => $callback){
     $this->mainServer->on($event, function () use ($callback) {
       $ret = [];
       $args = func_get_args();
       foreach ($callback as $item) {
          array_push($ret,Invoker::callUserFuncArray($item, $args));
       }
       if(count($ret) > 1){
          return $ret;
       }
       return array_shift($ret);
     });
}

Here's what finalHook does

$this->finalHook($register);
//Instantiation object pool management
PoolManager::getInstance();
//register, bind a workerStart callback function first. This event occurs when the Worker process / Task process starts. The objects created here can be used during the global cycle of the process.
$register->add($register::onWorkerStart,function (\swoole_server $server,int $workerId){
	PoolManager::getInstance()->__workerStartHook($workerId);
	$workerNum = Config::getInstance()->getConf('MAIN_SERVER.SETTING.worker_num');
	$name = Config::getInstance()->getConf('SERVER_NAME');
	if(PHP_OS != 'Darwin'){
		if($workerId <= ($workerNum -1)){//Determine whether the current process is a worker process
			$name = "{$name}_Worker_".$workerId;
		}else{//This is the task process
			$name = "{$name}_Task_Worker_".$workerId;
		}
		cli_set_process_title($name);//Set current process name
		//picture
	}
});
//EventHelper is a default event handler provided by the framework (these will be covered later)
EventHelper::registerDefaultOnTask($register);//Register the default task callback and handle the specific function of task task
EventHelper::registerDefaultOnFinish($register);//Register the callback after the default task task is completed
EventHelper::registerDefaultOnPipeMessage($register);//Register the pipeMessage callback function
$conf = Config::getInstance()->getConf("MAIN_SERVER");
//If it is an http server or websocket, you need to register the request callback function
if($conf['SERVER_TYPE'] == self::TYPE_WEB_SERVER || $conf['SERVER_TYPE'] == self::TYPE_WEB_SOCKET_SERVER){
	if(!$register->get($register::onRequest)){
		EventHelper::registerDefaultOnRequest($register);//This includes the function of request, route resolution and return processing. Similar to general web framework
	}
}  

After the system is started, when the worker is started, it will change its name, as shown in the following figure

 

Finally, register the relevant cache listening port and start the swoole service.

Cache::getInstance(); //Register Cache here
Cluster::getInstance()->run(); //Implementation of RPC
CronTab::getInstance()->run(); //Timing task
$this->attachListener();//Swoole provides swoole_server::addListener to increase the listening port. In the business code, you can call swoole? Server:: connection? Info to get which port a connection comes from. When the framework is started, the host is configured as 0.0.0.0, so it's unnecessary to set this when listening to all addresses
$this->isStart = true;
$this->getServer()->start();//Start the swoole server, and all the objects created before are in the global phase of the program

The next article introduces PoolManager. Because it's used in many places.   

Topics: PHP crontab