Worker.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  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.7';
  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. exit(250);
  846. } else {
  847. throw new Exception("forkOneWorker fail");
  848. }
  849. }
  850. /**
  851. * Get worker id.
  852. *
  853. * @param int $worker_id
  854. * @param int $pid
  855. */
  856. protected static function getId($worker_id, $pid)
  857. {
  858. return array_search($pid, self::$_idMap[$worker_id]);
  859. }
  860. /**
  861. * Set unix user and group for current process.
  862. *
  863. * @return void
  864. */
  865. public function setUserAndGroup()
  866. {
  867. // Get uid.
  868. $user_info = posix_getpwnam($this->user);
  869. if (!$user_info) {
  870. self::log("Warning: User {$this->user} not exsits");
  871. return;
  872. }
  873. $uid = $user_info['uid'];
  874. // Get gid.
  875. if ($this->group) {
  876. $group_info = posix_getgrnam($this->group);
  877. if (!$group_info) {
  878. self::log("Warning: Group {$this->group} not exsits");
  879. return;
  880. }
  881. $gid = $group_info['gid'];
  882. } else {
  883. $gid = $user_info['gid'];
  884. }
  885. // Set uid and gid.
  886. if ($uid != posix_getuid() || $gid != posix_getgid()) {
  887. if (!posix_setgid($gid) || !posix_initgroups($user_info['name'], $gid) || !posix_setuid($uid)) {
  888. self::log("Warning: change gid or uid fail.");
  889. }
  890. }
  891. }
  892. /**
  893. * Set process name.
  894. *
  895. * @param string $title
  896. * @return void
  897. */
  898. protected static function setProcessTitle($title)
  899. {
  900. // >=php 5.5
  901. if (function_exists('cli_set_process_title')) {
  902. @cli_set_process_title($title);
  903. } // Need proctitle when php<=5.5 .
  904. elseif (extension_loaded('proctitle') && function_exists('setproctitle')) {
  905. @setproctitle($title);
  906. }
  907. }
  908. /**
  909. * Monitor all child processes.
  910. *
  911. * @return void
  912. */
  913. protected static function monitorWorkers()
  914. {
  915. self::$_status = self::STATUS_RUNNING;
  916. while (1) {
  917. // Calls signal handlers for pending signals.
  918. pcntl_signal_dispatch();
  919. // Suspends execution of the current process until a child has exited, or until a signal is delivered
  920. $status = 0;
  921. $pid = pcntl_wait($status, WUNTRACED);
  922. // Calls signal handlers for pending signals again.
  923. pcntl_signal_dispatch();
  924. // If a child has already exited.
  925. if ($pid > 0) {
  926. // Find out witch worker process exited.
  927. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  928. if (isset($worker_pid_array[$pid])) {
  929. $worker = self::$_workers[$worker_id];
  930. // Exit status.
  931. if ($status !== 0) {
  932. self::log("worker[" . $worker->name . ":$pid] exit with status $status");
  933. }
  934. // For Statistics.
  935. if (!isset(self::$_globalStatistics['worker_exit_info'][$worker_id][$status])) {
  936. self::$_globalStatistics['worker_exit_info'][$worker_id][$status] = 0;
  937. }
  938. self::$_globalStatistics['worker_exit_info'][$worker_id][$status]++;
  939. // Clear process data.
  940. unset(self::$_pidMap[$worker_id][$pid]);
  941. // Mark id is available.
  942. $id = self::getId($worker_id, $pid);
  943. self::$_idMap[$worker_id][$id] = 0;
  944. break;
  945. }
  946. }
  947. // Is still running state then fork a new worker process.
  948. if (self::$_status !== self::STATUS_SHUTDOWN) {
  949. self::forkWorkers();
  950. // If reloading continue.
  951. if (isset(self::$_pidsToRestart[$pid])) {
  952. unset(self::$_pidsToRestart[$pid]);
  953. self::reload();
  954. }
  955. } else {
  956. // If shutdown state and all child processes exited then master process exit.
  957. if (!self::getAllWorkerPids()) {
  958. self::exitAndClearAll();
  959. }
  960. }
  961. } else {
  962. // If shutdown state and all child processes exited then master process exit.
  963. if (self::$_status === self::STATUS_SHUTDOWN && !self::getAllWorkerPids()) {
  964. self::exitAndClearAll();
  965. }
  966. }
  967. }
  968. }
  969. /**
  970. * Exit current process.
  971. *
  972. * @return void
  973. */
  974. protected static function exitAndClearAll()
  975. {
  976. foreach (self::$_workers as $worker) {
  977. $socket_name = $worker->getSocketName();
  978. if ($worker->transport === 'unix' && $socket_name) {
  979. list(, $address) = explode(':', $socket_name, 2);
  980. @unlink($address);
  981. }
  982. }
  983. @unlink(self::$pidFile);
  984. self::log("Workerman[" . basename(self::$_startFile) . "] has been stopped");
  985. if (self::$onMasterStop) {
  986. call_user_func(self::$onMasterStop);
  987. }
  988. exit(0);
  989. }
  990. /**
  991. * Execute reload.
  992. *
  993. * @return void
  994. */
  995. protected static function reload()
  996. {
  997. // For master process.
  998. if (self::$_masterPid === posix_getpid()) {
  999. // Set reloading state.
  1000. if (self::$_status !== self::STATUS_RELOADING && self::$_status !== self::STATUS_SHUTDOWN) {
  1001. self::log("Workerman[" . basename(self::$_startFile) . "] reloading");
  1002. self::$_status = self::STATUS_RELOADING;
  1003. // Try to emit onMasterReload callback.
  1004. if (self::$onMasterReload) {
  1005. try {
  1006. call_user_func(self::$onMasterReload);
  1007. } catch (\Exception $e) {
  1008. self::log($e);
  1009. exit(250);
  1010. } catch (\Error $e) {
  1011. self::log($e);
  1012. exit(250);
  1013. }
  1014. self::initId();
  1015. }
  1016. }
  1017. // Send reload signal to all child processes.
  1018. $reloadable_pid_array = array();
  1019. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  1020. $worker = self::$_workers[$worker_id];
  1021. if ($worker->reloadable) {
  1022. foreach ($worker_pid_array as $pid) {
  1023. $reloadable_pid_array[$pid] = $pid;
  1024. }
  1025. } else {
  1026. foreach ($worker_pid_array as $pid) {
  1027. // Send reload signal to a worker process which reloadable is false.
  1028. posix_kill($pid, SIGUSR1);
  1029. }
  1030. }
  1031. }
  1032. // Get all pids that are waiting reload.
  1033. self::$_pidsToRestart = array_intersect(self::$_pidsToRestart, $reloadable_pid_array);
  1034. // Reload complete.
  1035. if (empty(self::$_pidsToRestart)) {
  1036. if (self::$_status !== self::STATUS_SHUTDOWN) {
  1037. self::$_status = self::STATUS_RUNNING;
  1038. }
  1039. return;
  1040. }
  1041. // Continue reload.
  1042. $one_worker_pid = current(self::$_pidsToRestart);
  1043. // Send reload signal to a worker process.
  1044. posix_kill($one_worker_pid, SIGUSR1);
  1045. // If the process does not exit after self::KILL_WORKER_TIMER_TIME seconds try to kill it.
  1046. Timer::add(self::KILL_WORKER_TIMER_TIME, 'posix_kill', array($one_worker_pid, SIGKILL), false);
  1047. } // For child processes.
  1048. else {
  1049. $worker = current(self::$_workers);
  1050. // Try to emit onWorkerReload callback.
  1051. if ($worker->onWorkerReload) {
  1052. try {
  1053. call_user_func($worker->onWorkerReload, $worker);
  1054. } catch (\Exception $e) {
  1055. self::log($e);
  1056. exit(250);
  1057. } catch (\Error $e) {
  1058. self::log($e);
  1059. exit(250);
  1060. }
  1061. }
  1062. if ($worker->reloadable) {
  1063. self::stopAll();
  1064. }
  1065. }
  1066. }
  1067. /**
  1068. * Stop.
  1069. *
  1070. * @return void
  1071. */
  1072. public static function stopAll()
  1073. {
  1074. self::$_status = self::STATUS_SHUTDOWN;
  1075. // For master process.
  1076. if (self::$_masterPid === posix_getpid()) {
  1077. self::log("Workerman[" . basename(self::$_startFile) . "] Stopping ...");
  1078. $worker_pid_array = self::getAllWorkerPids();
  1079. // Send stop signal to all child processes.
  1080. foreach ($worker_pid_array as $worker_pid) {
  1081. posix_kill($worker_pid, SIGINT);
  1082. Timer::add(self::KILL_WORKER_TIMER_TIME, 'posix_kill', array($worker_pid, SIGKILL), false);
  1083. }
  1084. } // For child processes.
  1085. else {
  1086. // Execute exit.
  1087. foreach (self::$_workers as $worker) {
  1088. $worker->stop();
  1089. }
  1090. exit(0);
  1091. }
  1092. }
  1093. /**
  1094. * Write statistics data to disk.
  1095. *
  1096. * @return void
  1097. */
  1098. protected static function writeStatisticsToStatusFile()
  1099. {
  1100. // For master process.
  1101. if (self::$_masterPid === posix_getpid()) {
  1102. $loadavg = sys_getloadavg();
  1103. file_put_contents(self::$_statisticsFile,
  1104. "---------------------------------------GLOBAL STATUS--------------------------------------------\n");
  1105. file_put_contents(self::$_statisticsFile,
  1106. 'Workerman version:' . Worker::VERSION . " PHP version:" . PHP_VERSION . "\n", FILE_APPEND);
  1107. file_put_contents(self::$_statisticsFile, 'start time:' . date('Y-m-d H:i:s',
  1108. 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",
  1109. FILE_APPEND);
  1110. $load_str = 'load average: ' . implode(", ", $loadavg);
  1111. file_put_contents(self::$_statisticsFile,
  1112. str_pad($load_str, 33) . 'event-loop:' . self::getEventLoopName() . "\n", FILE_APPEND);
  1113. file_put_contents(self::$_statisticsFile,
  1114. count(self::$_pidMap) . ' workers ' . count(self::getAllWorkerPids()) . " processes\n",
  1115. FILE_APPEND);
  1116. file_put_contents(self::$_statisticsFile,
  1117. str_pad('worker_name', self::$_maxWorkerNameLength) . " exit_status exit_count\n", FILE_APPEND);
  1118. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  1119. $worker = self::$_workers[$worker_id];
  1120. if (isset(self::$_globalStatistics['worker_exit_info'][$worker_id])) {
  1121. foreach (self::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
  1122. file_put_contents(self::$_statisticsFile,
  1123. str_pad($worker->name, self::$_maxWorkerNameLength) . " " . str_pad($worker_exit_status,
  1124. 16) . " $worker_exit_count\n", FILE_APPEND);
  1125. }
  1126. } else {
  1127. file_put_contents(self::$_statisticsFile,
  1128. str_pad($worker->name, self::$_maxWorkerNameLength) . " " . str_pad(0, 16) . " 0\n",
  1129. FILE_APPEND);
  1130. }
  1131. }
  1132. file_put_contents(self::$_statisticsFile,
  1133. "---------------------------------------PROCESS STATUS-------------------------------------------\n",
  1134. FILE_APPEND);
  1135. file_put_contents(self::$_statisticsFile,
  1136. "pid\tmemory " . str_pad('listening', self::$_maxSocketNameLength) . " " . str_pad('worker_name',
  1137. self::$_maxWorkerNameLength) . " connections " . str_pad('total_request',
  1138. 13) . " " . str_pad('send_fail', 9) . " " . str_pad('throw_exception', 15) . "\n", FILE_APPEND);
  1139. chmod(self::$_statisticsFile, 0722);
  1140. foreach (self::getAllWorkerPids() as $worker_pid) {
  1141. posix_kill($worker_pid, SIGUSR2);
  1142. }
  1143. return;
  1144. }
  1145. // For child processes.
  1146. /** @var Worker $worker */
  1147. $worker = current(self::$_workers);
  1148. $worker_status_str = posix_getpid() . "\t" . str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M",
  1149. 7) . " " . str_pad($worker->getSocketName(),
  1150. self::$_maxSocketNameLength) . " " . str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name),
  1151. self::$_maxWorkerNameLength) . " ";
  1152. $worker_status_str .= str_pad(ConnectionInterface::$statistics['connection_count'],
  1153. 11) . " " . str_pad(ConnectionInterface::$statistics['total_request'],
  1154. 14) . " " . str_pad(ConnectionInterface::$statistics['send_fail'],
  1155. 9) . " " . str_pad(ConnectionInterface::$statistics['throw_exception'], 15) . "\n";
  1156. file_put_contents(self::$_statisticsFile, $worker_status_str, FILE_APPEND);
  1157. }
  1158. /**
  1159. * Check errors when current process exited.
  1160. *
  1161. * @return void
  1162. */
  1163. public static function checkErrors()
  1164. {
  1165. if (self::STATUS_SHUTDOWN != self::$_status) {
  1166. $error_msg = "WORKER EXIT UNEXPECTED ";
  1167. $errors = error_get_last();
  1168. if ($errors && ($errors['type'] === E_ERROR ||
  1169. $errors['type'] === E_PARSE ||
  1170. $errors['type'] === E_CORE_ERROR ||
  1171. $errors['type'] === E_COMPILE_ERROR ||
  1172. $errors['type'] === E_RECOVERABLE_ERROR)
  1173. ) {
  1174. $error_msg .= self::getErrorType($errors['type']) . " {$errors['message']} in {$errors['file']} on line {$errors['line']}";
  1175. }
  1176. self::log($error_msg);
  1177. }
  1178. }
  1179. /**
  1180. * Get error message by error code.
  1181. *
  1182. * @param integer $type
  1183. * @return string
  1184. */
  1185. protected static function getErrorType($type)
  1186. {
  1187. switch ($type) {
  1188. case E_ERROR: // 1 //
  1189. return 'E_ERROR';
  1190. case E_WARNING: // 2 //
  1191. return 'E_WARNING';
  1192. case E_PARSE: // 4 //
  1193. return 'E_PARSE';
  1194. case E_NOTICE: // 8 //
  1195. return 'E_NOTICE';
  1196. case E_CORE_ERROR: // 16 //
  1197. return 'E_CORE_ERROR';
  1198. case E_CORE_WARNING: // 32 //
  1199. return 'E_CORE_WARNING';
  1200. case E_COMPILE_ERROR: // 64 //
  1201. return 'E_COMPILE_ERROR';
  1202. case E_COMPILE_WARNING: // 128 //
  1203. return 'E_COMPILE_WARNING';
  1204. case E_USER_ERROR: // 256 //
  1205. return 'E_USER_ERROR';
  1206. case E_USER_WARNING: // 512 //
  1207. return 'E_USER_WARNING';
  1208. case E_USER_NOTICE: // 1024 //
  1209. return 'E_USER_NOTICE';
  1210. case E_STRICT: // 2048 //
  1211. return 'E_STRICT';
  1212. case E_RECOVERABLE_ERROR: // 4096 //
  1213. return 'E_RECOVERABLE_ERROR';
  1214. case E_DEPRECATED: // 8192 //
  1215. return 'E_DEPRECATED';
  1216. case E_USER_DEPRECATED: // 16384 //
  1217. return 'E_USER_DEPRECATED';
  1218. }
  1219. return "";
  1220. }
  1221. /**
  1222. * Log.
  1223. *
  1224. * @param string $msg
  1225. * @return void
  1226. */
  1227. public static function log($msg)
  1228. {
  1229. $msg = $msg . "\n";
  1230. if (!self::$daemonize) {
  1231. self::safeEcho($msg);
  1232. }
  1233. file_put_contents((string)self::$logFile, date('Y-m-d H:i:s') . ' ' . 'pid:'. posix_getpid() . ' ' . $msg, FILE_APPEND | LOCK_EX);
  1234. }
  1235. /**
  1236. * Safe Echo.
  1237. *
  1238. * @param $msg
  1239. */
  1240. public static function safeEcho($msg)
  1241. {
  1242. if (!function_exists('posix_isatty') || posix_isatty(STDOUT)) {
  1243. echo $msg;
  1244. }
  1245. }
  1246. /**
  1247. * Construct.
  1248. *
  1249. * @param string $socket_name
  1250. * @param array $context_option
  1251. */
  1252. public function __construct($socket_name = '', $context_option = array())
  1253. {
  1254. // Save all worker instances.
  1255. $this->workerId = spl_object_hash($this);
  1256. self::$_workers[$this->workerId] = $this;
  1257. self::$_pidMap[$this->workerId] = array();
  1258. // Get autoload root path.
  1259. $backtrace = debug_backtrace();
  1260. $this->_autoloadRootPath = dirname($backtrace[0]['file']);
  1261. // Context for socket.
  1262. if ($socket_name) {
  1263. $this->_socketName = $socket_name;
  1264. if (!isset($context_option['socket']['backlog'])) {
  1265. $context_option['socket']['backlog'] = self::DEFAULT_BACKLOG;
  1266. }
  1267. $this->_context = stream_context_create($context_option);
  1268. }
  1269. // Set an empty onMessage callback.
  1270. $this->onMessage = function () {
  1271. };
  1272. }
  1273. /**
  1274. * Listen port.
  1275. *
  1276. * @throws Exception
  1277. */
  1278. public function listen()
  1279. {
  1280. if (!$this->_socketName || $this->_mainSocket) {
  1281. return;
  1282. }
  1283. // Autoload.
  1284. Autoloader::setRootPath($this->_autoloadRootPath);
  1285. // Get the application layer communication protocol and listening address.
  1286. list($scheme, $address) = explode(':', $this->_socketName, 2);
  1287. // Check application layer protocol class.
  1288. if (!isset(self::$_builtinTransports[$scheme])) {
  1289. if(class_exists($scheme)){
  1290. $this->protocol = $scheme;
  1291. } else {
  1292. $scheme = ucfirst($scheme);
  1293. $this->protocol = '\\Protocols\\' . $scheme;
  1294. if (!class_exists($this->protocol)) {
  1295. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  1296. if (!class_exists($this->protocol)) {
  1297. throw new Exception("class \\Protocols\\$scheme not exist");
  1298. }
  1299. }
  1300. }
  1301. if (!isset(self::$_builtinTransports[$this->transport])) {
  1302. throw new \Exception('Bad worker->transport ' . var_export($this->transport, true));
  1303. }
  1304. } else {
  1305. $this->transport = $scheme;
  1306. }
  1307. $local_socket = self::$_builtinTransports[$this->transport] . ":" . $address;
  1308. // Flag.
  1309. $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
  1310. $errno = 0;
  1311. $errmsg = '';
  1312. // SO_REUSEPORT.
  1313. if ($this->reusePort) {
  1314. stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
  1315. }
  1316. // Create an Internet or Unix domain server socket.
  1317. $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context);
  1318. if (!$this->_mainSocket) {
  1319. throw new Exception($errmsg);
  1320. }
  1321. if ($this->transport === 'ssl') {
  1322. stream_socket_enable_crypto($this->_mainSocket, false);
  1323. }
  1324. // Try to open keepalive for tcp and disable Nagle algorithm.
  1325. if (function_exists('socket_import_stream') && self::$_builtinTransports[$this->transport] === 'tcp') {
  1326. $socket = socket_import_stream($this->_mainSocket);
  1327. @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
  1328. @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
  1329. }
  1330. // Non blocking.
  1331. stream_set_blocking($this->_mainSocket, 0);
  1332. // Register a listener to be notified when server socket is ready to read.
  1333. if (self::$globalEvent) {
  1334. if ($this->transport !== 'udp') {
  1335. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptConnection'));
  1336. } else {
  1337. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1338. array($this, 'acceptUdpConnection'));
  1339. }
  1340. }
  1341. }
  1342. /**
  1343. * Get socket name.
  1344. *
  1345. * @return string
  1346. */
  1347. public function getSocketName()
  1348. {
  1349. return $this->_socketName ? lcfirst($this->_socketName) : 'none';
  1350. }
  1351. /**
  1352. * Run worker instance.
  1353. *
  1354. * @return void
  1355. */
  1356. public function run()
  1357. {
  1358. //Update process state.
  1359. self::$_status = self::STATUS_RUNNING;
  1360. // Register shutdown function for checking errors.
  1361. register_shutdown_function(array("\\Workerman\\Worker", 'checkErrors'));
  1362. // Set autoload root path.
  1363. Autoloader::setRootPath($this->_autoloadRootPath);
  1364. // Create a global event loop.
  1365. if (!self::$globalEvent) {
  1366. $eventLoopClass = "\\Workerman\\Events\\" . ucfirst(self::getEventLoopName());
  1367. self::$globalEvent = new $eventLoopClass;
  1368. // Register a listener to be notified when server socket is ready to read.
  1369. if ($this->_socketName) {
  1370. if ($this->transport !== 'udp') {
  1371. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1372. array($this, 'acceptConnection'));
  1373. } else {
  1374. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1375. array($this, 'acceptUdpConnection'));
  1376. }
  1377. }
  1378. }
  1379. // Reinstall signal.
  1380. self::reinstallSignal();
  1381. // Init Timer.
  1382. Timer::init(self::$globalEvent);
  1383. // Try to emit onWorkerStart callback.
  1384. if ($this->onWorkerStart) {
  1385. try {
  1386. call_user_func($this->onWorkerStart, $this);
  1387. } catch (\Exception $e) {
  1388. self::log($e);
  1389. exit(250);
  1390. } catch (\Error $e) {
  1391. self::log($e);
  1392. exit(250);
  1393. }
  1394. }
  1395. // Main loop.
  1396. self::$globalEvent->loop();
  1397. }
  1398. /**
  1399. * Stop current worker instance.
  1400. *
  1401. * @return void
  1402. */
  1403. public function stop()
  1404. {
  1405. // Try to emit onWorkerStop callback.
  1406. if ($this->onWorkerStop) {
  1407. try {
  1408. call_user_func($this->onWorkerStop, $this);
  1409. } catch (\Exception $e) {
  1410. self::log($e);
  1411. exit(250);
  1412. } catch (\Error $e) {
  1413. self::log($e);
  1414. exit(250);
  1415. }
  1416. }
  1417. // Remove listener for server socket.
  1418. self::$globalEvent->del($this->_mainSocket, EventInterface::EV_READ);
  1419. @fclose($this->_mainSocket);
  1420. }
  1421. /**
  1422. * Accept a connection.
  1423. *
  1424. * @param resource $socket
  1425. * @return void
  1426. */
  1427. public function acceptConnection($socket)
  1428. {
  1429. // Accept a connection on server socket.
  1430. $new_socket = @stream_socket_accept($socket, 0, $remote_address);
  1431. // Thundering herd.
  1432. if (!$new_socket) {
  1433. return;
  1434. }
  1435. // TcpConnection.
  1436. $connection = new TcpConnection($new_socket, $remote_address);
  1437. $this->connections[$connection->id] = $connection;
  1438. $connection->worker = $this;
  1439. $connection->protocol = $this->protocol;
  1440. $connection->transport = $this->transport;
  1441. $connection->onMessage = $this->onMessage;
  1442. $connection->onClose = $this->onClose;
  1443. $connection->onError = $this->onError;
  1444. $connection->onBufferDrain = $this->onBufferDrain;
  1445. $connection->onBufferFull = $this->onBufferFull;
  1446. // Try to emit onConnect callback.
  1447. if ($this->onConnect) {
  1448. try {
  1449. call_user_func($this->onConnect, $connection);
  1450. } catch (\Exception $e) {
  1451. self::log($e);
  1452. exit(250);
  1453. } catch (\Error $e) {
  1454. self::log($e);
  1455. exit(250);
  1456. }
  1457. }
  1458. }
  1459. /**
  1460. * For udp package.
  1461. *
  1462. * @param resource $socket
  1463. * @return bool
  1464. */
  1465. public function acceptUdpConnection($socket)
  1466. {
  1467. $recv_buffer = stream_socket_recvfrom($socket, self::MAX_UDP_PACKAGE_SIZE, 0, $remote_address);
  1468. if (false === $recv_buffer || empty($remote_address)) {
  1469. return false;
  1470. }
  1471. // UdpConnection.
  1472. $connection = new UdpConnection($socket, $remote_address);
  1473. $connection->protocol = $this->protocol;
  1474. if ($this->onMessage) {
  1475. if ($this->protocol) {
  1476. $parser = $this->protocol;
  1477. $recv_buffer = $parser::decode($recv_buffer, $connection);
  1478. // Discard bad packets.
  1479. if ($recv_buffer === false)
  1480. return true;
  1481. }
  1482. ConnectionInterface::$statistics['total_request']++;
  1483. try {
  1484. call_user_func($this->onMessage, $connection, $recv_buffer);
  1485. } catch (\Exception $e) {
  1486. self::log($e);
  1487. exit(250);
  1488. } catch (\Error $e) {
  1489. self::log($e);
  1490. exit(250);
  1491. }
  1492. }
  1493. return true;
  1494. }
  1495. }