Worker.php 50 KB

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