Worker.php 48 KB

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