Worker.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Workerman;
  15. require_once __DIR__ . '/Lib/Constants.php';
  16. use Workerman\Events\EventInterface;
  17. use Workerman\Connection\ConnectionInterface;
  18. use Workerman\Connection\TcpConnection;
  19. use Workerman\Connection\UdpConnection;
  20. use Workerman\Lib\Timer;
  21. use Exception;
  22. /**
  23. * Worker class
  24. * A container for listening ports
  25. */
  26. class Worker
  27. {
  28. /**
  29. * Version.
  30. *
  31. * @var string
  32. */
  33. const VERSION = '3.4.0';
  34. /**
  35. * Status starting.
  36. *
  37. * @var int
  38. */
  39. const STATUS_STARTING = 1;
  40. /**
  41. * Status running.
  42. *
  43. * @var int
  44. */
  45. const STATUS_RUNNING = 2;
  46. /**
  47. * Status shutdown.
  48. *
  49. * @var int
  50. */
  51. const STATUS_SHUTDOWN = 4;
  52. /**
  53. * Status reloading.
  54. *
  55. * @var int
  56. */
  57. const STATUS_RELOADING = 8;
  58. /**
  59. * After sending the restart command to the child process KILL_WORKER_TIMER_TIME seconds,
  60. * if the process is still living then forced to kill.
  61. *
  62. * @var int
  63. */
  64. const KILL_WORKER_TIMER_TIME = 2;
  65. /**
  66. * Default backlog. Backlog is the maximum length of the queue of pending connections.
  67. *
  68. * @var int
  69. */
  70. const DEFAULT_BACKLOG = 102400;
  71. /**
  72. * Max udp package size.
  73. *
  74. * @var int
  75. */
  76. const MAX_UDP_PACKAGE_SIZE = 65535;
  77. /**
  78. * Worker id.
  79. *
  80. * @var int
  81. */
  82. public $id = 0;
  83. /**
  84. * Name of the worker processes.
  85. *
  86. * @var string
  87. */
  88. public $name = 'none';
  89. /**
  90. * Number of worker processes.
  91. *
  92. * @var int
  93. */
  94. public $count = 1;
  95. /**
  96. * Unix user of processes, needs appropriate privileges (usually root).
  97. *
  98. * @var string
  99. */
  100. public $user = '';
  101. /**
  102. * Unix group of processes, needs appropriate privileges (usually root).
  103. *
  104. * @var string
  105. */
  106. public $group = '';
  107. /**
  108. * reloadable.
  109. *
  110. * @var bool
  111. */
  112. public $reloadable = true;
  113. /**
  114. * reuse port.
  115. *
  116. * @var bool
  117. */
  118. public $reusePort = false;
  119. /**
  120. * Emitted when worker processes start.
  121. *
  122. * @var callback
  123. */
  124. public $onWorkerStart = null;
  125. /**
  126. * Emitted when a socket connection is successfully established.
  127. *
  128. * @var callback
  129. */
  130. public $onConnect = null;
  131. /**
  132. * Emitted when data is received.
  133. *
  134. * @var callback
  135. */
  136. public $onMessage = null;
  137. /**
  138. * Emitted when the other end of the socket sends a FIN packet.
  139. *
  140. * @var callback
  141. */
  142. public $onClose = null;
  143. /**
  144. * Emitted when an error occurs with connection.
  145. *
  146. * @var callback
  147. */
  148. public $onError = null;
  149. /**
  150. * Emitted when the send buffer becomes full.
  151. *
  152. * @var callback
  153. */
  154. public $onBufferFull = null;
  155. /**
  156. * Emitted when the send buffer becomes empty.
  157. *
  158. * @var callback
  159. */
  160. public $onBufferDrain = null;
  161. /**
  162. * Emitted when worker processes stoped.
  163. *
  164. * @var callback
  165. */
  166. public $onWorkerStop = null;
  167. /**
  168. * Emitted when worker processes get reload signal.
  169. *
  170. * @var callback
  171. */
  172. public $onWorkerReload = null;
  173. /**
  174. * Transport layer protocol.
  175. *
  176. * @var string
  177. */
  178. public $transport = 'tcp';
  179. /**
  180. * Store all connections of clients.
  181. *
  182. * @var array
  183. */
  184. public $connections = array();
  185. /**
  186. * Application layer protocol.
  187. *
  188. * @var Protocols\ProtocolInterface
  189. */
  190. public $protocol = '';
  191. /**
  192. * Root path for autoload.
  193. *
  194. * @var string
  195. */
  196. protected $_autoloadRootPath = '';
  197. /**
  198. * Daemonize.
  199. *
  200. * @var bool
  201. */
  202. public static $daemonize = false;
  203. /**
  204. * Stdout file.
  205. *
  206. * @var string
  207. */
  208. public static $stdoutFile = '/dev/null';
  209. /**
  210. * The file to store master process PID.
  211. *
  212. * @var string
  213. */
  214. public static $pidFile = '';
  215. /**
  216. * Log file.
  217. *
  218. * @var mixed
  219. */
  220. public static $logFile = '';
  221. /**
  222. * Global event loop.
  223. *
  224. * @var Events\EventInterface
  225. */
  226. public static $globalEvent = null;
  227. /**
  228. * Emitted when the master process get reload signal.
  229. *
  230. * @var callback
  231. */
  232. public static $onMasterReload = null;
  233. /**
  234. * Emitted when the master process terminated.
  235. *
  236. * @var callback
  237. */
  238. public static $onMasterStop = null;
  239. /**
  240. * EventLoopClass
  241. *
  242. * @var string
  243. */
  244. public static $eventLoopClass = '';
  245. /**
  246. * The PID of master process.
  247. *
  248. * @var int
  249. */
  250. protected static $_masterPid = 0;
  251. /**
  252. * Listening socket.
  253. *
  254. * @var resource
  255. */
  256. protected $_mainSocket = null;
  257. /**
  258. * Socket name. The format is like this http://0.0.0.0:80 .
  259. *
  260. * @var string
  261. */
  262. protected $_socketName = '';
  263. /**
  264. * Context of socket.
  265. *
  266. * @var resource
  267. */
  268. protected $_context = null;
  269. /**
  270. * All worker instances.
  271. *
  272. * @var array
  273. */
  274. protected static $_workers = array();
  275. /**
  276. * All worker porcesses pid.
  277. * The format is like this [worker_id=>[pid=>pid, pid=>pid, ..], ..]
  278. *
  279. * @var array
  280. */
  281. protected static $_pidMap = array();
  282. /**
  283. * All worker processes waiting for restart.
  284. * The format is like this [pid=>pid, pid=>pid].
  285. *
  286. * @var array
  287. */
  288. protected static $_pidsToRestart = array();
  289. /**
  290. * Mapping from PID to worker process ID.
  291. * The format is like this [worker_id=>[0=>$pid, 1=>$pid, ..], ..].
  292. *
  293. * @var array
  294. */
  295. protected static $_idMap = array();
  296. /**
  297. * Current status.
  298. *
  299. * @var int
  300. */
  301. protected static $_status = self::STATUS_STARTING;
  302. /**
  303. * Maximum length of the worker names.
  304. *
  305. * @var int
  306. */
  307. protected static $_maxWorkerNameLength = 12;
  308. /**
  309. * Maximum length of the socket names.
  310. *
  311. * @var int
  312. */
  313. protected static $_maxSocketNameLength = 12;
  314. /**
  315. * Maximum length of the process user names.
  316. *
  317. * @var int
  318. */
  319. protected static $_maxUserNameLength = 12;
  320. /**
  321. * The file to store status info of current worker process.
  322. *
  323. * @var string
  324. */
  325. protected static $_statisticsFile = '';
  326. /**
  327. * Start file.
  328. *
  329. * @var string
  330. */
  331. protected static $_startFile = '';
  332. /**
  333. * Status info of current worker process.
  334. *
  335. * @var array
  336. */
  337. protected static $_globalStatistics = array(
  338. 'start_timestamp' => 0,
  339. 'worker_exit_info' => array()
  340. );
  341. /**
  342. * Available event loops.
  343. *
  344. * @var array
  345. */
  346. protected static $_availableEventLoops = array(
  347. 'libevent' => '\Workerman\Events\Libevent',
  348. 'event' => '\Workerman\Events\Event'
  349. );
  350. /**
  351. * PHP built-in protocols.
  352. *
  353. * @var array
  354. */
  355. protected static $_builtinTransports = array(
  356. 'tcp' => 'tcp',
  357. 'udp' => 'udp',
  358. 'unix' => 'unix',
  359. 'ssl' => 'tcp'
  360. );
  361. /**
  362. * Run all worker instances.
  363. *
  364. * @return void
  365. */
  366. public static function runAll()
  367. {
  368. self::checkSapiEnv();
  369. self::init();
  370. self::parseCommand();
  371. self::daemonize();
  372. self::initWorkers();
  373. self::installSignal();
  374. self::saveMasterPid();
  375. self::forkWorkers();
  376. self::displayUI();
  377. self::resetStd();
  378. self::monitorWorkers();
  379. }
  380. /**
  381. * Check sapi.
  382. *
  383. * @return void
  384. */
  385. protected static function checkSapiEnv()
  386. {
  387. // Only for cli.
  388. if (php_sapi_name() != "cli") {
  389. exit("only run in command line mode \n");
  390. }
  391. }
  392. /**
  393. * Init.
  394. *
  395. * @return void
  396. */
  397. protected static function init()
  398. {
  399. // Start file.
  400. $backtrace = debug_backtrace();
  401. self::$_startFile = $backtrace[count($backtrace) - 1]['file'];
  402. // Pid file.
  403. if (empty(self::$pidFile)) {
  404. self::$pidFile = __DIR__ . "/../" . str_replace('/', '_', self::$_startFile) . ".pid";
  405. }
  406. // Log file.
  407. if (empty(self::$logFile)) {
  408. self::$logFile = __DIR__ . '/../workerman.log';
  409. }
  410. $log_file = (string)self::$logFile;
  411. if (!is_file($log_file)) {
  412. touch($log_file);
  413. chmod($log_file, 0622);
  414. }
  415. // State.
  416. self::$_status = self::STATUS_STARTING;
  417. // For statistics.
  418. self::$_globalStatistics['start_timestamp'] = time();
  419. self::$_statisticsFile = sys_get_temp_dir() . '/workerman.status';
  420. // Process title.
  421. self::setProcessTitle('WorkerMan: master process start_file=' . self::$_startFile);
  422. // Init data for worker id.
  423. self::initId();
  424. // Timer init.
  425. Timer::init();
  426. }
  427. /**
  428. * Init All worker instances.
  429. *
  430. * @return void
  431. */
  432. protected static function initWorkers()
  433. {
  434. foreach (self::$_workers as $worker) {
  435. // Worker name.
  436. if (empty($worker->name)) {
  437. $worker->name = 'none';
  438. }
  439. // Get maximum length of worker name.
  440. $worker_name_length = strlen($worker->name);
  441. if (self::$_maxWorkerNameLength < $worker_name_length) {
  442. self::$_maxWorkerNameLength = $worker_name_length;
  443. }
  444. // Get maximum length of socket name.
  445. $socket_name_length = strlen($worker->getSocketName());
  446. if (self::$_maxSocketNameLength < $socket_name_length) {
  447. self::$_maxSocketNameLength = $socket_name_length;
  448. }
  449. // Get unix user of the worker process.
  450. if (empty($worker->user)) {
  451. $worker->user = self::getCurrentUser();
  452. } else {
  453. if (posix_getuid() !== 0 && $worker->user != self::getCurrentUser()) {
  454. self::log('Warning: You must have the root privileges to change uid and gid.');
  455. }
  456. }
  457. // Get maximum length of unix user name.
  458. $user_name_length = strlen($worker->user);
  459. if (self::$_maxUserNameLength < $user_name_length) {
  460. self::$_maxUserNameLength = $user_name_length;
  461. }
  462. // Listen.
  463. if (!$worker->reusePort) {
  464. $worker->listen();
  465. }
  466. }
  467. }
  468. /**
  469. * Get all worker instances.
  470. *
  471. * @return array
  472. */
  473. public static function getAllWorkers()
  474. {
  475. return self::$_workers;
  476. }
  477. /**
  478. * Get global event-loop instance.
  479. *
  480. * @return EventInterface
  481. */
  482. public static function getEventLoop()
  483. {
  484. return self::$globalEvent;
  485. }
  486. /**
  487. * Init idMap.
  488. * return void
  489. */
  490. protected static function initId()
  491. {
  492. foreach (self::$_workers as $worker_id => $worker) {
  493. $new_id_map = array();
  494. for($key = 0; $key < $worker->count; $key++) {
  495. $new_id_map[$key] = isset(self::$_idMap[$worker_id][$key]) ? self::$_idMap[$worker_id][$key] : 0;
  496. }
  497. self::$_idMap[$worker_id] = $new_id_map;
  498. }
  499. }
  500. /**
  501. * Get unix user of current porcess.
  502. *
  503. * @return string
  504. */
  505. protected static function getCurrentUser()
  506. {
  507. $user_info = posix_getpwuid(posix_getuid());
  508. return $user_info['name'];
  509. }
  510. /**
  511. * Display staring UI.
  512. *
  513. * @return void
  514. */
  515. protected static function displayUI()
  516. {
  517. self::safeEcho("\033[1A\n\033[K-----------------------\033[47;30m WORKERMAN \033[0m-----------------------------\n\033[0m");
  518. self::safeEcho('Workerman version:'. Worker::VERSION. " PHP version:". PHP_VERSION. "\n");
  519. self::safeEcho("------------------------\033[47;30m WORKERS \033[0m-------------------------------\n");
  520. self::safeEcho("\033[47;30muser\033[0m". str_pad('',
  521. self::$_maxUserNameLength + 2 - strlen('user')). "\033[47;30mworker\033[0m". str_pad('',
  522. self::$_maxWorkerNameLength + 2 - strlen('worker')). "\033[47;30mlisten\033[0m". str_pad('',
  523. self::$_maxSocketNameLength + 2 - strlen('listen')). "\033[47;30mprocesses\033[0m \033[47;30m". "status\033[0m\n");
  524. foreach (self::$_workers as $worker) {
  525. self::safeEcho(str_pad($worker->user, self::$_maxUserNameLength + 2). str_pad($worker->name,
  526. self::$_maxWorkerNameLength + 2). str_pad($worker->getSocketName(),
  527. self::$_maxSocketNameLength + 2). str_pad(' ' . $worker->count, 9). " \033[32;40m [OK] \033[0m\n");
  528. }
  529. self::safeEcho("----------------------------------------------------------------\n");
  530. if (self::$daemonize) {
  531. global $argv;
  532. $start_file = $argv[0];
  533. self::safeEcho("Input \"php $start_file stop\" to quit. Start success.\n");
  534. } else {
  535. self::safeEcho("Press Ctrl-C to quit. Start success.\n");
  536. }
  537. }
  538. /**
  539. * Parse command.
  540. * php yourfile.php start | stop | restart | reload | status
  541. *
  542. * @return void
  543. */
  544. protected static function parseCommand()
  545. {
  546. global $argv;
  547. // Check argv;
  548. $start_file = $argv[0];
  549. if (!isset($argv[1])) {
  550. exit("Usage: php yourfile.php {start|stop|restart|reload|status}\n");
  551. }
  552. // Get command.
  553. $command = trim($argv[1]);
  554. $command2 = isset($argv[2]) ? $argv[2] : '';
  555. // Start command.
  556. $mode = '';
  557. if ($command === 'start') {
  558. if ($command2 === '-d' || Worker::$daemonize) {
  559. $mode = 'in DAEMON mode';
  560. } else {
  561. $mode = 'in DEBUG mode';
  562. }
  563. }
  564. self::log("Workerman[$start_file] $command $mode");
  565. // Get master process PID.
  566. $master_pid = @file_get_contents(self::$pidFile);
  567. $master_is_alive = $master_pid && @posix_kill($master_pid, 0);
  568. // Master is still alive?
  569. if ($master_is_alive) {
  570. if ($command === 'start' && posix_getpid() != $master_pid) {
  571. self::log("Workerman[$start_file] already running");
  572. exit;
  573. }
  574. } elseif ($command !== 'start' && $command !== 'restart') {
  575. self::log("Workerman[$start_file] not run");
  576. exit;
  577. }
  578. // execute command.
  579. switch ($command) {
  580. case 'start':
  581. if ($command2 === '-d') {
  582. Worker::$daemonize = true;
  583. }
  584. break;
  585. case 'status':
  586. if (is_file(self::$_statisticsFile)) {
  587. @unlink(self::$_statisticsFile);
  588. }
  589. // Master process will send status signal to all child processes.
  590. posix_kill($master_pid, SIGUSR2);
  591. // Waiting amoment.
  592. usleep(500000);
  593. // Display statisitcs data from a disk file.
  594. @readfile(self::$_statisticsFile);
  595. exit(0);
  596. case 'restart':
  597. case 'stop':
  598. self::log("Workerman[$start_file] is stoping ...");
  599. // Send stop signal to master process.
  600. $master_pid && posix_kill($master_pid, SIGINT);
  601. // Timeout.
  602. $timeout = 5;
  603. $start_time = time();
  604. // Check master process is still alive?
  605. while (1) {
  606. $master_is_alive = $master_pid && posix_kill($master_pid, 0);
  607. if ($master_is_alive) {
  608. // Timeout?
  609. if (time() - $start_time >= $timeout) {
  610. self::log("Workerman[$start_file] stop fail");
  611. exit;
  612. }
  613. // Waiting amoment.
  614. usleep(10000);
  615. continue;
  616. }
  617. // Stop success.
  618. self::log("Workerman[$start_file] stop success");
  619. if ($command === 'stop') {
  620. exit(0);
  621. }
  622. if ($command2 === '-d') {
  623. Worker::$daemonize = true;
  624. }
  625. break;
  626. }
  627. break;
  628. case 'reload':
  629. posix_kill($master_pid, SIGUSR1);
  630. self::log("Workerman[$start_file] reload");
  631. exit;
  632. default :
  633. exit("Usage: php yourfile.php {start|stop|restart|reload|status}\n");
  634. }
  635. }
  636. /**
  637. * Install signal handler.
  638. *
  639. * @return void
  640. */
  641. protected static function installSignal()
  642. {
  643. // stop
  644. pcntl_signal(SIGINT, array('\Workerman\Worker', 'signalHandler'), false);
  645. // reload
  646. pcntl_signal(SIGUSR1, array('\Workerman\Worker', 'signalHandler'), false);
  647. // status
  648. pcntl_signal(SIGUSR2, array('\Workerman\Worker', 'signalHandler'), false);
  649. // ignore
  650. pcntl_signal(SIGPIPE, SIG_IGN, false);
  651. }
  652. /**
  653. * Reinstall signal handler.
  654. *
  655. * @return void
  656. */
  657. protected static function reinstallSignal()
  658. {
  659. // uninstall stop signal handler
  660. pcntl_signal(SIGINT, SIG_IGN, false);
  661. // uninstall reload signal handler
  662. pcntl_signal(SIGUSR1, SIG_IGN, false);
  663. // uninstall status signal handler
  664. pcntl_signal(SIGUSR2, SIG_IGN, false);
  665. // reinstall stop signal handler
  666. self::$globalEvent->add(SIGINT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  667. // reinstall reload signal handler
  668. self::$globalEvent->add(SIGUSR1, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  669. // reinstall status signal handler
  670. self::$globalEvent->add(SIGUSR2, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  671. }
  672. /**
  673. * Signal handler.
  674. *
  675. * @param int $signal
  676. */
  677. public static function signalHandler($signal)
  678. {
  679. switch ($signal) {
  680. // Stop.
  681. case SIGINT:
  682. self::stopAll();
  683. break;
  684. // Reload.
  685. case SIGUSR1:
  686. self::$_pidsToRestart = self::getAllWorkerPids();
  687. self::reload();
  688. break;
  689. // Show status.
  690. case SIGUSR2:
  691. self::writeStatisticsToStatusFile();
  692. break;
  693. }
  694. }
  695. /**
  696. * Run as deamon mode.
  697. *
  698. * @throws Exception
  699. */
  700. protected static function daemonize()
  701. {
  702. if (!self::$daemonize) {
  703. return;
  704. }
  705. umask(0);
  706. $pid = pcntl_fork();
  707. if (-1 === $pid) {
  708. throw new Exception('fork fail');
  709. } elseif ($pid > 0) {
  710. exit(0);
  711. }
  712. if (-1 === posix_setsid()) {
  713. throw new Exception("setsid fail");
  714. }
  715. // Fork again avoid SVR4 system regain the control of terminal.
  716. $pid = pcntl_fork();
  717. if (-1 === $pid) {
  718. throw new Exception("fork fail");
  719. } elseif (0 !== $pid) {
  720. exit(0);
  721. }
  722. }
  723. /**
  724. * Redirect standard input and output.
  725. *
  726. * @throws Exception
  727. */
  728. protected static function resetStd()
  729. {
  730. if (!self::$daemonize) {
  731. return;
  732. }
  733. global $STDOUT, $STDERR;
  734. $handle = fopen(self::$stdoutFile, "a");
  735. if ($handle) {
  736. unset($handle);
  737. @fclose(STDOUT);
  738. @fclose(STDERR);
  739. $STDOUT = fopen(self::$stdoutFile, "a");
  740. $STDERR = fopen(self::$stdoutFile, "a");
  741. } else {
  742. throw new Exception('can not open stdoutFile ' . self::$stdoutFile);
  743. }
  744. }
  745. /**
  746. * Save pid.
  747. *
  748. * @throws Exception
  749. */
  750. protected static function saveMasterPid()
  751. {
  752. self::$_masterPid = posix_getpid();
  753. if (false === @file_put_contents(self::$pidFile, self::$_masterPid)) {
  754. throw new Exception('can not save pid to ' . self::$pidFile);
  755. }
  756. }
  757. /**
  758. * Get event loop name.
  759. *
  760. * @return string
  761. */
  762. protected static function getEventLoopName()
  763. {
  764. if (self::$eventLoopClass) {
  765. return self::$eventLoopClass;
  766. }
  767. $loop_name = '';
  768. foreach (self::$_availableEventLoops as $name=>$class) {
  769. if (extension_loaded($name)) {
  770. $loop_name = $name;
  771. break;
  772. }
  773. }
  774. if ($loop_name) {
  775. if (interface_exists('\React\EventLoop\LoopInterface')) {
  776. switch ($loop_name) {
  777. case 'libevent':
  778. self::$eventLoopClass = '\Workerman\Events\React\LibEventLoop';
  779. break;
  780. case 'event':
  781. self::$eventLoopClass = '\Workerman\Events\React\ExtEventLoop';
  782. break;
  783. default :
  784. self::$eventLoopClass = '\Workerman\Events\React\StreamSelectLoop';
  785. break;
  786. }
  787. } else {
  788. self::$eventLoopClass = self::$_availableEventLoops[$loop_name];
  789. }
  790. } else {
  791. self::$eventLoopClass = '\Workerman\Events\Select';
  792. }
  793. return self::$eventLoopClass;
  794. }
  795. /**
  796. * Get all pids of worker processes.
  797. *
  798. * @return array
  799. */
  800. protected static function getAllWorkerPids()
  801. {
  802. $pid_array = array();
  803. foreach (self::$_pidMap as $worker_pid_array) {
  804. foreach ($worker_pid_array as $worker_pid) {
  805. $pid_array[$worker_pid] = $worker_pid;
  806. }
  807. }
  808. return $pid_array;
  809. }
  810. /**
  811. * Fork some worker processes.
  812. *
  813. * @return void
  814. */
  815. protected static function forkWorkers()
  816. {
  817. foreach (self::$_workers as $worker) {
  818. if (self::$_status === self::STATUS_STARTING) {
  819. if (empty($worker->name)) {
  820. $worker->name = $worker->getSocketName();
  821. }
  822. $worker_name_length = strlen($worker->name);
  823. if (self::$_maxWorkerNameLength < $worker_name_length) {
  824. self::$_maxWorkerNameLength = $worker_name_length;
  825. }
  826. }
  827. $worker->count = $worker->count <= 0 ? 1 : $worker->count;
  828. while (count(self::$_pidMap[$worker->workerId]) < $worker->count) {
  829. static::forkOneWorker($worker);
  830. }
  831. }
  832. }
  833. /**
  834. * Fork one worker process.
  835. *
  836. * @param Worker $worker
  837. * @throws Exception
  838. */
  839. protected static function forkOneWorker($worker)
  840. {
  841. // Get available worker id.
  842. $id = self::getId($worker->workerId, 0);
  843. if ($id === false) {
  844. return;
  845. }
  846. $pid = pcntl_fork();
  847. // For master process.
  848. if ($pid > 0) {
  849. self::$_pidMap[$worker->workerId][$pid] = $pid;
  850. self::$_idMap[$worker->workerId][$id] = $pid;
  851. } // For child processes.
  852. elseif (0 === $pid) {
  853. if ($worker->reusePort) {
  854. $worker->listen();
  855. }
  856. if (self::$_status === self::STATUS_STARTING) {
  857. self::resetStd();
  858. }
  859. self::$_pidMap = array();
  860. self::$_workers = array($worker->workerId => $worker);
  861. Timer::delAll();
  862. self::setProcessTitle('WorkerMan: worker process ' . $worker->name . ' ' . $worker->getSocketName());
  863. $worker->setUserAndGroup();
  864. $worker->id = $id;
  865. $worker->run();
  866. $err = new Exception('event-loop exited');
  867. self::log($err);
  868. exit(250);
  869. } else {
  870. throw new Exception("forkOneWorker fail");
  871. }
  872. }
  873. /**
  874. * Get worker id.
  875. *
  876. * @param int $worker_id
  877. * @param int $pid
  878. */
  879. protected static function getId($worker_id, $pid)
  880. {
  881. return array_search($pid, self::$_idMap[$worker_id]);
  882. }
  883. /**
  884. * Set unix user and group for current process.
  885. *
  886. * @return void
  887. */
  888. public function setUserAndGroup()
  889. {
  890. // Get uid.
  891. $user_info = posix_getpwnam($this->user);
  892. if (!$user_info) {
  893. self::log("Warning: User {$this->user} not exsits");
  894. return;
  895. }
  896. $uid = $user_info['uid'];
  897. // Get gid.
  898. if ($this->group) {
  899. $group_info = posix_getgrnam($this->group);
  900. if (!$group_info) {
  901. self::log("Warning: Group {$this->group} not exsits");
  902. return;
  903. }
  904. $gid = $group_info['gid'];
  905. } else {
  906. $gid = $user_info['gid'];
  907. }
  908. // Set uid and gid.
  909. if ($uid != posix_getuid() || $gid != posix_getgid()) {
  910. if (!posix_setgid($gid) || !posix_initgroups($user_info['name'], $gid) || !posix_setuid($uid)) {
  911. self::log("Warning: change gid or uid fail.");
  912. }
  913. }
  914. }
  915. /**
  916. * Set process name.
  917. *
  918. * @param string $title
  919. * @return void
  920. */
  921. protected static function setProcessTitle($title)
  922. {
  923. // >=php 5.5
  924. if (function_exists('cli_set_process_title')) {
  925. @cli_set_process_title($title);
  926. } // Need proctitle when php<=5.5 .
  927. elseif (extension_loaded('proctitle') && function_exists('setproctitle')) {
  928. @setproctitle($title);
  929. }
  930. }
  931. /**
  932. * Monitor all child processes.
  933. *
  934. * @return void
  935. */
  936. protected static function monitorWorkers()
  937. {
  938. self::$_status = self::STATUS_RUNNING;
  939. while (1) {
  940. // Calls signal handlers for pending signals.
  941. pcntl_signal_dispatch();
  942. // Suspends execution of the current process until a child has exited, or until a signal is delivered
  943. $status = 0;
  944. $pid = pcntl_wait($status, WUNTRACED);
  945. // Calls signal handlers for pending signals again.
  946. pcntl_signal_dispatch();
  947. // If a child has already exited.
  948. if ($pid > 0) {
  949. // Find out witch worker process exited.
  950. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  951. if (isset($worker_pid_array[$pid])) {
  952. $worker = self::$_workers[$worker_id];
  953. // Exit status.
  954. if ($status !== 0) {
  955. self::log("worker[" . $worker->name . ":$pid] exit with status $status");
  956. }
  957. // For Statistics.
  958. if (!isset(self::$_globalStatistics['worker_exit_info'][$worker_id][$status])) {
  959. self::$_globalStatistics['worker_exit_info'][$worker_id][$status] = 0;
  960. }
  961. self::$_globalStatistics['worker_exit_info'][$worker_id][$status]++;
  962. // Clear process data.
  963. unset(self::$_pidMap[$worker_id][$pid]);
  964. // Mark id is available.
  965. $id = self::getId($worker_id, $pid);
  966. self::$_idMap[$worker_id][$id] = 0;
  967. break;
  968. }
  969. }
  970. // Is still running state then fork a new worker process.
  971. if (self::$_status !== self::STATUS_SHUTDOWN) {
  972. self::forkWorkers();
  973. // If reloading continue.
  974. if (isset(self::$_pidsToRestart[$pid])) {
  975. unset(self::$_pidsToRestart[$pid]);
  976. self::reload();
  977. }
  978. } else {
  979. // If shutdown state and all child processes exited then master process exit.
  980. if (!self::getAllWorkerPids()) {
  981. self::exitAndClearAll();
  982. }
  983. }
  984. } else {
  985. // If shutdown state and all child processes exited then master process exit.
  986. if (self::$_status === self::STATUS_SHUTDOWN && !self::getAllWorkerPids()) {
  987. self::exitAndClearAll();
  988. }
  989. }
  990. }
  991. }
  992. /**
  993. * Exit current process.
  994. *
  995. * @return void
  996. */
  997. protected static function exitAndClearAll()
  998. {
  999. foreach (self::$_workers as $worker) {
  1000. $socket_name = $worker->getSocketName();
  1001. if ($worker->transport === 'unix' && $socket_name) {
  1002. list(, $address) = explode(':', $socket_name, 2);
  1003. @unlink($address);
  1004. }
  1005. }
  1006. @unlink(self::$pidFile);
  1007. self::log("Workerman[" . basename(self::$_startFile) . "] has been stopped");
  1008. if (self::$onMasterStop) {
  1009. call_user_func(self::$onMasterStop);
  1010. }
  1011. exit(0);
  1012. }
  1013. /**
  1014. * Execute reload.
  1015. *
  1016. * @return void
  1017. */
  1018. protected static function reload()
  1019. {
  1020. // For master process.
  1021. if (self::$_masterPid === posix_getpid()) {
  1022. // Set reloading state.
  1023. if (self::$_status !== self::STATUS_RELOADING && self::$_status !== self::STATUS_SHUTDOWN) {
  1024. self::log("Workerman[" . basename(self::$_startFile) . "] reloading");
  1025. self::$_status = self::STATUS_RELOADING;
  1026. // Try to emit onMasterReload callback.
  1027. if (self::$onMasterReload) {
  1028. try {
  1029. call_user_func(self::$onMasterReload);
  1030. } catch (\Exception $e) {
  1031. self::log($e);
  1032. exit(250);
  1033. } catch (\Error $e) {
  1034. self::log($e);
  1035. exit(250);
  1036. }
  1037. self::initId();
  1038. }
  1039. }
  1040. // Send reload signal to all child processes.
  1041. $reloadable_pid_array = array();
  1042. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  1043. $worker = self::$_workers[$worker_id];
  1044. if ($worker->reloadable) {
  1045. foreach ($worker_pid_array as $pid) {
  1046. $reloadable_pid_array[$pid] = $pid;
  1047. }
  1048. } else {
  1049. foreach ($worker_pid_array as $pid) {
  1050. // Send reload signal to a worker process which reloadable is false.
  1051. posix_kill($pid, SIGUSR1);
  1052. }
  1053. }
  1054. }
  1055. // Get all pids that are waiting reload.
  1056. self::$_pidsToRestart = array_intersect(self::$_pidsToRestart, $reloadable_pid_array);
  1057. // Reload complete.
  1058. if (empty(self::$_pidsToRestart)) {
  1059. if (self::$_status !== self::STATUS_SHUTDOWN) {
  1060. self::$_status = self::STATUS_RUNNING;
  1061. }
  1062. return;
  1063. }
  1064. // Continue reload.
  1065. $one_worker_pid = current(self::$_pidsToRestart);
  1066. // Send reload signal to a worker process.
  1067. posix_kill($one_worker_pid, SIGUSR1);
  1068. // If the process does not exit after self::KILL_WORKER_TIMER_TIME seconds try to kill it.
  1069. Timer::add(self::KILL_WORKER_TIMER_TIME, 'posix_kill', array($one_worker_pid, SIGKILL), false);
  1070. } // For child processes.
  1071. else {
  1072. $worker = current(self::$_workers);
  1073. // Try to emit onWorkerReload callback.
  1074. if ($worker->onWorkerReload) {
  1075. try {
  1076. call_user_func($worker->onWorkerReload, $worker);
  1077. } catch (\Exception $e) {
  1078. self::log($e);
  1079. exit(250);
  1080. } catch (\Error $e) {
  1081. self::log($e);
  1082. exit(250);
  1083. }
  1084. }
  1085. if ($worker->reloadable) {
  1086. self::stopAll();
  1087. }
  1088. }
  1089. }
  1090. /**
  1091. * Stop.
  1092. *
  1093. * @return void
  1094. */
  1095. public static function stopAll()
  1096. {
  1097. self::$_status = self::STATUS_SHUTDOWN;
  1098. // For master process.
  1099. if (self::$_masterPid === posix_getpid()) {
  1100. self::log("Workerman[" . basename(self::$_startFile) . "] Stopping ...");
  1101. $worker_pid_array = self::getAllWorkerPids();
  1102. // Send stop signal to all child processes.
  1103. foreach ($worker_pid_array as $worker_pid) {
  1104. posix_kill($worker_pid, SIGINT);
  1105. Timer::add(self::KILL_WORKER_TIMER_TIME, 'posix_kill', array($worker_pid, SIGKILL), false);
  1106. }
  1107. } // For child processes.
  1108. else {
  1109. // Execute exit.
  1110. foreach (self::$_workers as $worker) {
  1111. $worker->stop();
  1112. }
  1113. self::$globalEvent->destroy();
  1114. exit(0);
  1115. }
  1116. }
  1117. /**
  1118. * Write statistics data to disk.
  1119. *
  1120. * @return void
  1121. */
  1122. protected static function writeStatisticsToStatusFile()
  1123. {
  1124. // For master process.
  1125. if (self::$_masterPid === posix_getpid()) {
  1126. $loadavg = function_exists('sys_getloadavg') ? array_map('round', sys_getloadavg(), array(2)) : array('-', '-', '-');
  1127. file_put_contents(self::$_statisticsFile,
  1128. "---------------------------------------GLOBAL STATUS--------------------------------------------\n");
  1129. file_put_contents(self::$_statisticsFile,
  1130. 'Workerman version:' . Worker::VERSION . " PHP version:" . PHP_VERSION . "\n", FILE_APPEND);
  1131. file_put_contents(self::$_statisticsFile, 'start time:' . date('Y-m-d H:i:s',
  1132. self::$_globalStatistics['start_timestamp']) . ' run ' . floor((time() - self::$_globalStatistics['start_timestamp']) / (24 * 60 * 60)) . ' days ' . floor(((time() - self::$_globalStatistics['start_timestamp']) % (24 * 60 * 60)) / (60 * 60)) . " hours \n",
  1133. FILE_APPEND);
  1134. $load_str = 'load average: ' . implode(", ", $loadavg);
  1135. file_put_contents(self::$_statisticsFile,
  1136. str_pad($load_str, 33) . 'event-loop:' . self::getEventLoopName() . "\n", FILE_APPEND);
  1137. file_put_contents(self::$_statisticsFile,
  1138. count(self::$_pidMap) . ' workers ' . count(self::getAllWorkerPids()) . " processes\n",
  1139. FILE_APPEND);
  1140. file_put_contents(self::$_statisticsFile,
  1141. str_pad('worker_name', self::$_maxWorkerNameLength) . " exit_status exit_count\n", FILE_APPEND);
  1142. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  1143. $worker = self::$_workers[$worker_id];
  1144. if (isset(self::$_globalStatistics['worker_exit_info'][$worker_id])) {
  1145. foreach (self::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
  1146. file_put_contents(self::$_statisticsFile,
  1147. str_pad($worker->name, self::$_maxWorkerNameLength) . " " . str_pad($worker_exit_status,
  1148. 16) . " $worker_exit_count\n", FILE_APPEND);
  1149. }
  1150. } else {
  1151. file_put_contents(self::$_statisticsFile,
  1152. str_pad($worker->name, self::$_maxWorkerNameLength) . " " . str_pad(0, 16) . " 0\n",
  1153. FILE_APPEND);
  1154. }
  1155. }
  1156. file_put_contents(self::$_statisticsFile,
  1157. "---------------------------------------PROCESS STATUS-------------------------------------------\n",
  1158. FILE_APPEND);
  1159. file_put_contents(self::$_statisticsFile,
  1160. "pid\tmemory " . str_pad('listening', self::$_maxSocketNameLength) . " " . str_pad('worker_name',
  1161. self::$_maxWorkerNameLength) . " connections " . str_pad('total_request',
  1162. 13) . " " . str_pad('send_fail', 9) . " " . str_pad('throw_exception', 15) . "\n", FILE_APPEND);
  1163. chmod(self::$_statisticsFile, 0722);
  1164. foreach (self::getAllWorkerPids() as $worker_pid) {
  1165. posix_kill($worker_pid, SIGUSR2);
  1166. }
  1167. return;
  1168. }
  1169. // For child processes.
  1170. /** @var Worker $worker */
  1171. $worker = current(self::$_workers);
  1172. $worker_status_str = posix_getpid() . "\t" . str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M",
  1173. 7) . " " . str_pad($worker->getSocketName(),
  1174. self::$_maxSocketNameLength) . " " . str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name),
  1175. self::$_maxWorkerNameLength) . " ";
  1176. $worker_status_str .= str_pad(ConnectionInterface::$statistics['connection_count'],
  1177. 11) . " " . str_pad(ConnectionInterface::$statistics['total_request'],
  1178. 14) . " " . str_pad(ConnectionInterface::$statistics['send_fail'],
  1179. 9) . " " . str_pad(ConnectionInterface::$statistics['throw_exception'], 15) . "\n";
  1180. file_put_contents(self::$_statisticsFile, $worker_status_str, FILE_APPEND);
  1181. }
  1182. /**
  1183. * Check errors when current process exited.
  1184. *
  1185. * @return void
  1186. */
  1187. public static function checkErrors()
  1188. {
  1189. if (self::STATUS_SHUTDOWN != self::$_status) {
  1190. $error_msg = "WORKER EXIT UNEXPECTED ";
  1191. $errors = error_get_last();
  1192. if ($errors && ($errors['type'] === E_ERROR ||
  1193. $errors['type'] === E_PARSE ||
  1194. $errors['type'] === E_CORE_ERROR ||
  1195. $errors['type'] === E_COMPILE_ERROR ||
  1196. $errors['type'] === E_RECOVERABLE_ERROR)
  1197. ) {
  1198. $error_msg .= self::getErrorType($errors['type']) . " {$errors['message']} in {$errors['file']} on line {$errors['line']}";
  1199. }
  1200. self::log($error_msg);
  1201. }
  1202. }
  1203. /**
  1204. * Get error message by error code.
  1205. *
  1206. * @param integer $type
  1207. * @return string
  1208. */
  1209. protected static function getErrorType($type)
  1210. {
  1211. switch ($type) {
  1212. case E_ERROR: // 1 //
  1213. return 'E_ERROR';
  1214. case E_WARNING: // 2 //
  1215. return 'E_WARNING';
  1216. case E_PARSE: // 4 //
  1217. return 'E_PARSE';
  1218. case E_NOTICE: // 8 //
  1219. return 'E_NOTICE';
  1220. case E_CORE_ERROR: // 16 //
  1221. return 'E_CORE_ERROR';
  1222. case E_CORE_WARNING: // 32 //
  1223. return 'E_CORE_WARNING';
  1224. case E_COMPILE_ERROR: // 64 //
  1225. return 'E_COMPILE_ERROR';
  1226. case E_COMPILE_WARNING: // 128 //
  1227. return 'E_COMPILE_WARNING';
  1228. case E_USER_ERROR: // 256 //
  1229. return 'E_USER_ERROR';
  1230. case E_USER_WARNING: // 512 //
  1231. return 'E_USER_WARNING';
  1232. case E_USER_NOTICE: // 1024 //
  1233. return 'E_USER_NOTICE';
  1234. case E_STRICT: // 2048 //
  1235. return 'E_STRICT';
  1236. case E_RECOVERABLE_ERROR: // 4096 //
  1237. return 'E_RECOVERABLE_ERROR';
  1238. case E_DEPRECATED: // 8192 //
  1239. return 'E_DEPRECATED';
  1240. case E_USER_DEPRECATED: // 16384 //
  1241. return 'E_USER_DEPRECATED';
  1242. }
  1243. return "";
  1244. }
  1245. /**
  1246. * Log.
  1247. *
  1248. * @param string $msg
  1249. * @return void
  1250. */
  1251. public static function log($msg)
  1252. {
  1253. $msg = $msg . "\n";
  1254. if (!self::$daemonize) {
  1255. self::safeEcho($msg);
  1256. }
  1257. file_put_contents((string)self::$logFile, date('Y-m-d H:i:s') . ' ' . 'pid:'. posix_getpid() . ' ' . $msg, FILE_APPEND | LOCK_EX);
  1258. }
  1259. /**
  1260. * Safe Echo.
  1261. *
  1262. * @param $msg
  1263. */
  1264. public static function safeEcho($msg)
  1265. {
  1266. if (!function_exists('posix_isatty') || posix_isatty(STDOUT)) {
  1267. echo $msg;
  1268. }
  1269. }
  1270. /**
  1271. * Construct.
  1272. *
  1273. * @param string $socket_name
  1274. * @param array $context_option
  1275. */
  1276. public function __construct($socket_name = '', $context_option = array())
  1277. {
  1278. // Save all worker instances.
  1279. $this->workerId = spl_object_hash($this);
  1280. self::$_workers[$this->workerId] = $this;
  1281. self::$_pidMap[$this->workerId] = array();
  1282. // Get autoload root path.
  1283. $backtrace = debug_backtrace();
  1284. $this->_autoloadRootPath = dirname($backtrace[0]['file']);
  1285. // Context for socket.
  1286. if ($socket_name) {
  1287. $this->_socketName = $socket_name;
  1288. if (!isset($context_option['socket']['backlog'])) {
  1289. $context_option['socket']['backlog'] = self::DEFAULT_BACKLOG;
  1290. }
  1291. $this->_context = stream_context_create($context_option);
  1292. }
  1293. // Set an empty onMessage callback.
  1294. $this->onMessage = function () {
  1295. };
  1296. }
  1297. /**
  1298. * Listen port.
  1299. *
  1300. * @throws Exception
  1301. */
  1302. public function listen()
  1303. {
  1304. if (!$this->_socketName || $this->_mainSocket) {
  1305. return;
  1306. }
  1307. // Autoload.
  1308. Autoloader::setRootPath($this->_autoloadRootPath);
  1309. // Get the application layer communication protocol and listening address.
  1310. list($scheme, $address) = explode(':', $this->_socketName, 2);
  1311. // Check application layer protocol class.
  1312. if (!isset(self::$_builtinTransports[$scheme])) {
  1313. if(class_exists($scheme)){
  1314. $this->protocol = $scheme;
  1315. } else {
  1316. $scheme = ucfirst($scheme);
  1317. $this->protocol = '\\Protocols\\' . $scheme;
  1318. if (!class_exists($this->protocol)) {
  1319. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  1320. if (!class_exists($this->protocol)) {
  1321. throw new Exception("class \\Protocols\\$scheme not exist");
  1322. }
  1323. }
  1324. }
  1325. if (!isset(self::$_builtinTransports[$this->transport])) {
  1326. throw new \Exception('Bad worker->transport ' . var_export($this->transport, true));
  1327. }
  1328. } else {
  1329. $this->transport = $scheme;
  1330. }
  1331. $local_socket = self::$_builtinTransports[$this->transport] . ":" . $address;
  1332. // Flag.
  1333. $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
  1334. $errno = 0;
  1335. $errmsg = '';
  1336. // SO_REUSEPORT.
  1337. if ($this->reusePort) {
  1338. stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
  1339. }
  1340. // Create an Internet or Unix domain server socket.
  1341. $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context);
  1342. if (!$this->_mainSocket) {
  1343. throw new Exception($errmsg);
  1344. }
  1345. if ($this->transport === 'ssl') {
  1346. stream_socket_enable_crypto($this->_mainSocket, false);
  1347. }
  1348. // Try to open keepalive for tcp and disable Nagle algorithm.
  1349. if (function_exists('socket_import_stream') && self::$_builtinTransports[$this->transport] === 'tcp') {
  1350. $socket = socket_import_stream($this->_mainSocket);
  1351. @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
  1352. @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
  1353. }
  1354. // Non blocking.
  1355. stream_set_blocking($this->_mainSocket, 0);
  1356. // Register a listener to be notified when server socket is ready to read.
  1357. if (self::$globalEvent) {
  1358. if ($this->transport !== 'udp') {
  1359. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptConnection'));
  1360. } else {
  1361. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1362. array($this, 'acceptUdpConnection'));
  1363. }
  1364. }
  1365. }
  1366. /**
  1367. * Get socket name.
  1368. *
  1369. * @return string
  1370. */
  1371. public function getSocketName()
  1372. {
  1373. return $this->_socketName ? lcfirst($this->_socketName) : 'none';
  1374. }
  1375. /**
  1376. * Run worker instance.
  1377. *
  1378. * @return void
  1379. */
  1380. public function run()
  1381. {
  1382. //Update process state.
  1383. self::$_status = self::STATUS_RUNNING;
  1384. // Register shutdown function for checking errors.
  1385. register_shutdown_function(array("\\Workerman\\Worker", 'checkErrors'));
  1386. // Set autoload root path.
  1387. Autoloader::setRootPath($this->_autoloadRootPath);
  1388. // Create a global event loop.
  1389. if (!self::$globalEvent) {
  1390. $event_loop_class = self::getEventLoopName();
  1391. self::$globalEvent = new $event_loop_class;
  1392. // Register a listener to be notified when server socket is ready to read.
  1393. if ($this->_socketName) {
  1394. if ($this->transport !== 'udp') {
  1395. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1396. array($this, 'acceptConnection'));
  1397. } else {
  1398. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1399. array($this, 'acceptUdpConnection'));
  1400. }
  1401. }
  1402. }
  1403. // Reinstall signal.
  1404. self::reinstallSignal();
  1405. // Init Timer.
  1406. Timer::init(self::$globalEvent);
  1407. // Try to emit onWorkerStart callback.
  1408. if ($this->onWorkerStart) {
  1409. try {
  1410. call_user_func($this->onWorkerStart, $this);
  1411. } catch (\Exception $e) {
  1412. self::log($e);
  1413. exit(250);
  1414. } catch (\Error $e) {
  1415. self::log($e);
  1416. exit(250);
  1417. }
  1418. }
  1419. // Main loop.
  1420. self::$globalEvent->loop();
  1421. }
  1422. /**
  1423. * Stop current worker instance.
  1424. *
  1425. * @return void
  1426. */
  1427. public function stop()
  1428. {
  1429. // Try to emit onWorkerStop callback.
  1430. if ($this->onWorkerStop) {
  1431. try {
  1432. call_user_func($this->onWorkerStop, $this);
  1433. } catch (\Exception $e) {
  1434. self::log($e);
  1435. exit(250);
  1436. } catch (\Error $e) {
  1437. self::log($e);
  1438. exit(250);
  1439. }
  1440. }
  1441. // Remove listener for server socket.
  1442. self::$globalEvent->del($this->_mainSocket, EventInterface::EV_READ);
  1443. @fclose($this->_mainSocket);
  1444. }
  1445. /**
  1446. * Accept a connection.
  1447. *
  1448. * @param resource $socket
  1449. * @return void
  1450. */
  1451. public function acceptConnection($socket)
  1452. {
  1453. // Accept a connection on server socket.
  1454. $new_socket = @stream_socket_accept($socket, 0, $remote_address);
  1455. // Thundering herd.
  1456. if (!$new_socket) {
  1457. return;
  1458. }
  1459. // TcpConnection.
  1460. $connection = new TcpConnection($new_socket, $remote_address);
  1461. $this->connections[$connection->id] = $connection;
  1462. $connection->worker = $this;
  1463. $connection->protocol = $this->protocol;
  1464. $connection->transport = $this->transport;
  1465. $connection->onMessage = $this->onMessage;
  1466. $connection->onClose = $this->onClose;
  1467. $connection->onError = $this->onError;
  1468. $connection->onBufferDrain = $this->onBufferDrain;
  1469. $connection->onBufferFull = $this->onBufferFull;
  1470. // Try to emit onConnect callback.
  1471. if ($this->onConnect) {
  1472. try {
  1473. call_user_func($this->onConnect, $connection);
  1474. } catch (\Exception $e) {
  1475. self::log($e);
  1476. exit(250);
  1477. } catch (\Error $e) {
  1478. self::log($e);
  1479. exit(250);
  1480. }
  1481. }
  1482. }
  1483. /**
  1484. * For udp package.
  1485. *
  1486. * @param resource $socket
  1487. * @return bool
  1488. */
  1489. public function acceptUdpConnection($socket)
  1490. {
  1491. $recv_buffer = stream_socket_recvfrom($socket, self::MAX_UDP_PACKAGE_SIZE, 0, $remote_address);
  1492. if (false === $recv_buffer || empty($remote_address)) {
  1493. return false;
  1494. }
  1495. // UdpConnection.
  1496. $connection = new UdpConnection($socket, $remote_address);
  1497. $connection->protocol = $this->protocol;
  1498. if ($this->onMessage) {
  1499. if ($this->protocol) {
  1500. $parser = $this->protocol;
  1501. $recv_buffer = $parser::decode($recv_buffer, $connection);
  1502. // Discard bad packets.
  1503. if ($recv_buffer === false)
  1504. return true;
  1505. }
  1506. ConnectionInterface::$statistics['total_request']++;
  1507. try {
  1508. call_user_func($this->onMessage, $connection, $recv_buffer);
  1509. } catch (\Exception $e) {
  1510. self::log($e);
  1511. exit(250);
  1512. } catch (\Error $e) {
  1513. self::log($e);
  1514. exit(250);
  1515. }
  1516. }
  1517. return true;
  1518. }
  1519. }