Worker.php 48 KB

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