Worker.php 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770
  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.8';
  34. /**
  35. * Status starting.
  36. *
  37. * @var int
  38. */
  39. const STATUS_STARTING = 1;
  40. /**
  41. * Status running.
  42. *
  43. * @var int
  44. */
  45. const STATUS_RUNNING = 2;
  46. /**
  47. * Status shutdown.
  48. *
  49. * @var int
  50. */
  51. const STATUS_SHUTDOWN = 4;
  52. /**
  53. * Status reloading.
  54. *
  55. * @var int
  56. */
  57. const STATUS_RELOADING = 8;
  58. /**
  59. * After sending the restart command to the child process KILL_WORKER_TIMER_TIME seconds,
  60. * if the process is still living then forced to kill.
  61. *
  62. * @var int
  63. */
  64. const KILL_WORKER_TIMER_TIME = 2;
  65. /**
  66. * Default backlog. Backlog is the maximum length of the queue of pending connections.
  67. *
  68. * @var int
  69. */
  70. const DEFAULT_BACKLOG = 102400;
  71. /**
  72. * Max udp package size.
  73. *
  74. * @var int
  75. */
  76. const MAX_UDP_PACKAGE_SIZE = 65535;
  77. /**
  78. * Worker id.
  79. *
  80. * @var int
  81. */
  82. public $id = 0;
  83. /**
  84. * Name of the worker processes.
  85. *
  86. * @var string
  87. */
  88. public $name = 'none';
  89. /**
  90. * Number of worker processes.
  91. *
  92. * @var int
  93. */
  94. public $count = 1;
  95. /**
  96. * Unix user of processes, needs appropriate privileges (usually root).
  97. *
  98. * @var string
  99. */
  100. public $user = '';
  101. /**
  102. * Unix group of processes, needs appropriate privileges (usually root).
  103. *
  104. * @var string
  105. */
  106. public $group = '';
  107. /**
  108. * reloadable.
  109. *
  110. * @var bool
  111. */
  112. public $reloadable = true;
  113. /**
  114. * reuse port.
  115. *
  116. * @var bool
  117. */
  118. public $reusePort = false;
  119. /**
  120. * Emitted when worker processes start.
  121. *
  122. * @var callback
  123. */
  124. public $onWorkerStart = null;
  125. /**
  126. * Emitted when a socket connection is successfully established.
  127. *
  128. * @var callback
  129. */
  130. public $onConnect = null;
  131. /**
  132. * Emitted when data is received.
  133. *
  134. * @var callback
  135. */
  136. public $onMessage = null;
  137. /**
  138. * Emitted when the other end of the socket sends a FIN packet.
  139. *
  140. * @var callback
  141. */
  142. public $onClose = null;
  143. /**
  144. * Emitted when an error occurs with connection.
  145. *
  146. * @var callback
  147. */
  148. public $onError = null;
  149. /**
  150. * Emitted when the send buffer becomes full.
  151. *
  152. * @var callback
  153. */
  154. public $onBufferFull = null;
  155. /**
  156. * Emitted when the send buffer becomes empty.
  157. *
  158. * @var callback
  159. */
  160. public $onBufferDrain = null;
  161. /**
  162. * Emitted when worker processes stoped.
  163. *
  164. * @var callback
  165. */
  166. public $onWorkerStop = null;
  167. /**
  168. * Emitted when worker processes get reload signal.
  169. *
  170. * @var callback
  171. */
  172. public $onWorkerReload = null;
  173. /**
  174. * Transport layer protocol.
  175. *
  176. * @var string
  177. */
  178. public $transport = 'tcp';
  179. /**
  180. * Store all connections of clients.
  181. *
  182. * @var array
  183. */
  184. public $connections = array();
  185. /**
  186. * Application layer protocol.
  187. *
  188. * @var Protocols\ProtocolInterface
  189. */
  190. public $protocol = null;
  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. $available_commands = array(
  550. 'start',
  551. 'stop',
  552. 'restart',
  553. 'reload',
  554. 'status',
  555. 'connections',
  556. );
  557. if (!isset($argv[1]) || !in_array($argv[1], $available_commands)) {
  558. exit("Usage: php yourfile.php {" . implode('|', $available_commands) . "}\n");
  559. }
  560. // Get command.
  561. $command = trim($argv[1]);
  562. $command2 = isset($argv[2]) ? $argv[2] : '';
  563. // Start command.
  564. $mode = '';
  565. if ($command === 'start') {
  566. if ($command2 === '-d' || Worker::$daemonize) {
  567. $mode = 'in DAEMON mode';
  568. } else {
  569. $mode = 'in DEBUG mode';
  570. }
  571. }
  572. self::log("Workerman[$start_file] $command $mode");
  573. // Get master process PID.
  574. $master_pid = is_file(self::$pidFile) ? file_get_contents(self::$pidFile) : 0;
  575. $master_is_alive = $master_pid && @posix_kill($master_pid, 0) && posix_getpid() != $master_pid;
  576. // Master is still alive?
  577. if ($master_is_alive) {
  578. if ($command === 'start') {
  579. self::log("Workerman[$start_file] already running");
  580. exit;
  581. }
  582. } elseif ($command !== 'start' && $command !== 'restart') {
  583. self::log("Workerman[$start_file] not run");
  584. exit;
  585. }
  586. // execute command.
  587. switch ($command) {
  588. case 'start':
  589. if ($command2 === '-d') {
  590. Worker::$daemonize = true;
  591. }
  592. break;
  593. case 'status':
  594. case 'connections':
  595. if (is_file(self::$_statisticsFile)) {
  596. @unlink(self::$_statisticsFile);
  597. }
  598. // Master process will send status signal to all child processes.
  599. $signal = $command === 'status' ? SIGUSR2 : SIGIO;
  600. posix_kill($master_pid, $signal);
  601. // Waiting amoment.
  602. usleep(500000);
  603. // Display statisitcs data from a disk file.
  604. @readfile(self::$_statisticsFile);
  605. exit(0);
  606. case 'restart':
  607. case 'stop':
  608. self::log("Workerman[$start_file] is stoping ...");
  609. // Send stop signal to master process.
  610. $master_pid && posix_kill($master_pid, SIGINT);
  611. // Timeout.
  612. $timeout = 5;
  613. $start_time = time();
  614. // Check master process is still alive?
  615. while (1) {
  616. $master_is_alive = $master_pid && posix_kill($master_pid, 0);
  617. if ($master_is_alive) {
  618. // Timeout?
  619. if (time() - $start_time >= $timeout) {
  620. self::log("Workerman[$start_file] stop fail");
  621. exit;
  622. }
  623. // Waiting amoment.
  624. usleep(10000);
  625. continue;
  626. }
  627. // Stop success.
  628. self::log("Workerman[$start_file] stop success");
  629. if ($command === 'stop') {
  630. exit(0);
  631. }
  632. if ($command2 === '-d') {
  633. Worker::$daemonize = true;
  634. }
  635. break;
  636. }
  637. break;
  638. case 'reload':
  639. posix_kill($master_pid, SIGUSR1);
  640. self::log("Workerman[$start_file] reload");
  641. exit;
  642. default :
  643. exit("Usage: php yourfile.php {" . implode('|', $available_commands) . "}\n");
  644. }
  645. }
  646. /**
  647. * Install signal handler.
  648. *
  649. * @return void
  650. */
  651. protected static function installSignal()
  652. {
  653. // stop
  654. pcntl_signal(SIGINT, array('\Workerman\Worker', 'signalHandler'), false);
  655. // reload
  656. pcntl_signal(SIGUSR1, array('\Workerman\Worker', 'signalHandler'), false);
  657. // status
  658. pcntl_signal(SIGUSR2, array('\Workerman\Worker', 'signalHandler'), false);
  659. // connection status
  660. pcntl_signal(SIGIO, array('\Workerman\Worker', 'signalHandler'), false);
  661. // ignore
  662. pcntl_signal(SIGPIPE, SIG_IGN, false);
  663. }
  664. /**
  665. * Reinstall signal handler.
  666. *
  667. * @return void
  668. */
  669. protected static function reinstallSignal()
  670. {
  671. // uninstall stop signal handler
  672. pcntl_signal(SIGINT, SIG_IGN, false);
  673. // uninstall reload signal handler
  674. pcntl_signal(SIGUSR1, SIG_IGN, false);
  675. // uninstall status signal handler
  676. pcntl_signal(SIGUSR2, SIG_IGN, false);
  677. // reinstall stop signal handler
  678. self::$globalEvent->add(SIGINT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  679. // reinstall reload signal handler
  680. self::$globalEvent->add(SIGUSR1, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  681. // reinstall status signal handler
  682. self::$globalEvent->add(SIGUSR2, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  683. // reinstall connection status signal handler
  684. self::$globalEvent->add(SIGIO, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  685. }
  686. /**
  687. * Signal handler.
  688. *
  689. * @param int $signal
  690. */
  691. public static function signalHandler($signal)
  692. {
  693. switch ($signal) {
  694. // Stop.
  695. case SIGINT:
  696. self::stopAll();
  697. break;
  698. // Reload.
  699. case SIGUSR1:
  700. self::$_pidsToRestart = self::getAllWorkerPids();
  701. self::reload();
  702. break;
  703. // Show status.
  704. case SIGUSR2:
  705. self::writeStatisticsToStatusFile();
  706. break;
  707. // Show connection status.
  708. case SIGIO:
  709. self::writeConnectionsStatisticsToStatusFile();
  710. break;
  711. }
  712. }
  713. /**
  714. * Run as deamon mode.
  715. *
  716. * @throws Exception
  717. */
  718. protected static function daemonize()
  719. {
  720. if (!self::$daemonize) {
  721. return;
  722. }
  723. umask(0);
  724. $pid = pcntl_fork();
  725. if (-1 === $pid) {
  726. throw new Exception('fork fail');
  727. } elseif ($pid > 0) {
  728. exit(0);
  729. }
  730. if (-1 === posix_setsid()) {
  731. throw new Exception("setsid fail");
  732. }
  733. // Fork again avoid SVR4 system regain the control of terminal.
  734. $pid = pcntl_fork();
  735. if (-1 === $pid) {
  736. throw new Exception("fork fail");
  737. } elseif (0 !== $pid) {
  738. exit(0);
  739. }
  740. }
  741. /**
  742. * Redirect standard input and output.
  743. *
  744. * @throws Exception
  745. */
  746. public static function resetStd()
  747. {
  748. if (!self::$daemonize) {
  749. return;
  750. }
  751. global $STDOUT, $STDERR;
  752. $handle = fopen(self::$stdoutFile, "a");
  753. if ($handle) {
  754. unset($handle);
  755. @fclose(STDOUT);
  756. @fclose(STDERR);
  757. $STDOUT = fopen(self::$stdoutFile, "a");
  758. $STDERR = fopen(self::$stdoutFile, "a");
  759. } else {
  760. throw new Exception('can not open stdoutFile ' . self::$stdoutFile);
  761. }
  762. }
  763. /**
  764. * Save pid.
  765. *
  766. * @throws Exception
  767. */
  768. protected static function saveMasterPid()
  769. {
  770. self::$_masterPid = posix_getpid();
  771. if (false === @file_put_contents(self::$pidFile, self::$_masterPid)) {
  772. throw new Exception('can not save pid to ' . self::$pidFile);
  773. }
  774. }
  775. /**
  776. * Get event loop name.
  777. *
  778. * @return string
  779. */
  780. protected static function getEventLoopName()
  781. {
  782. if (self::$eventLoopClass) {
  783. return self::$eventLoopClass;
  784. }
  785. $loop_name = '';
  786. foreach (self::$_availableEventLoops as $name=>$class) {
  787. if (extension_loaded($name)) {
  788. $loop_name = $name;
  789. break;
  790. }
  791. }
  792. if ($loop_name) {
  793. if (interface_exists('\React\EventLoop\LoopInterface')) {
  794. switch ($loop_name) {
  795. case 'libevent':
  796. self::$eventLoopClass = '\Workerman\Events\React\LibEventLoop';
  797. break;
  798. case 'event':
  799. self::$eventLoopClass = '\Workerman\Events\React\ExtEventLoop';
  800. break;
  801. default :
  802. self::$eventLoopClass = '\Workerman\Events\React\StreamSelectLoop';
  803. break;
  804. }
  805. } else {
  806. self::$eventLoopClass = self::$_availableEventLoops[$loop_name];
  807. }
  808. } else {
  809. self::$eventLoopClass = interface_exists('\React\EventLoop\LoopInterface')? '\Workerman\Events\React\StreamSelectLoop':'\Workerman\Events\Select';
  810. }
  811. return self::$eventLoopClass;
  812. }
  813. /**
  814. * Get all pids of worker processes.
  815. *
  816. * @return array
  817. */
  818. protected static function getAllWorkerPids()
  819. {
  820. $pid_array = array();
  821. foreach (self::$_pidMap as $worker_pid_array) {
  822. foreach ($worker_pid_array as $worker_pid) {
  823. $pid_array[$worker_pid] = $worker_pid;
  824. }
  825. }
  826. return $pid_array;
  827. }
  828. /**
  829. * Fork some worker processes.
  830. *
  831. * @return void
  832. */
  833. protected static function forkWorkers()
  834. {
  835. foreach (self::$_workers as $worker) {
  836. if (self::$_status === self::STATUS_STARTING) {
  837. if (empty($worker->name)) {
  838. $worker->name = $worker->getSocketName();
  839. }
  840. $worker_name_length = strlen($worker->name);
  841. if (self::$_maxWorkerNameLength < $worker_name_length) {
  842. self::$_maxWorkerNameLength = $worker_name_length;
  843. }
  844. }
  845. $worker->count = $worker->count <= 0 ? 1 : $worker->count;
  846. while (count(self::$_pidMap[$worker->workerId]) < $worker->count) {
  847. static::forkOneWorker($worker);
  848. }
  849. }
  850. }
  851. /**
  852. * Fork one worker process.
  853. *
  854. * @param Worker $worker
  855. * @throws Exception
  856. */
  857. protected static function forkOneWorker($worker)
  858. {
  859. // Get available worker id.
  860. $id = self::getId($worker->workerId, 0);
  861. if ($id === false) {
  862. return;
  863. }
  864. $pid = pcntl_fork();
  865. // For master process.
  866. if ($pid > 0) {
  867. self::$_pidMap[$worker->workerId][$pid] = $pid;
  868. self::$_idMap[$worker->workerId][$id] = $pid;
  869. } // For child processes.
  870. elseif (0 === $pid) {
  871. if ($worker->reusePort) {
  872. $worker->listen();
  873. }
  874. if (self::$_status === self::STATUS_STARTING) {
  875. self::resetStd();
  876. }
  877. self::$_pidMap = array();
  878. self::$_workers = array($worker->workerId => $worker);
  879. Timer::delAll();
  880. self::setProcessTitle('WorkerMan: worker process ' . $worker->name . ' ' . $worker->getSocketName());
  881. $worker->setUserAndGroup();
  882. $worker->id = $id;
  883. $worker->run();
  884. $err = new Exception('event-loop exited');
  885. self::log($err);
  886. exit(250);
  887. } else {
  888. throw new Exception("forkOneWorker fail");
  889. }
  890. }
  891. /**
  892. * Get worker id.
  893. *
  894. * @param int $worker_id
  895. * @param int $pid
  896. *
  897. * @return integer
  898. */
  899. protected static function getId($worker_id, $pid)
  900. {
  901. return array_search($pid, self::$_idMap[$worker_id]);
  902. }
  903. /**
  904. * Set unix user and group for current process.
  905. *
  906. * @return void
  907. */
  908. public function setUserAndGroup()
  909. {
  910. // Get uid.
  911. $user_info = posix_getpwnam($this->user);
  912. if (!$user_info) {
  913. self::log("Warning: User {$this->user} not exsits");
  914. return;
  915. }
  916. $uid = $user_info['uid'];
  917. // Get gid.
  918. if ($this->group) {
  919. $group_info = posix_getgrnam($this->group);
  920. if (!$group_info) {
  921. self::log("Warning: Group {$this->group} not exsits");
  922. return;
  923. }
  924. $gid = $group_info['gid'];
  925. } else {
  926. $gid = $user_info['gid'];
  927. }
  928. // Set uid and gid.
  929. if ($uid != posix_getuid() || $gid != posix_getgid()) {
  930. if (!posix_setgid($gid) || !posix_initgroups($user_info['name'], $gid) || !posix_setuid($uid)) {
  931. self::log("Warning: change gid or uid fail.");
  932. }
  933. }
  934. }
  935. /**
  936. * Set process name.
  937. *
  938. * @param string $title
  939. * @return void
  940. */
  941. protected static function setProcessTitle($title)
  942. {
  943. // >=php 5.5
  944. if (function_exists('cli_set_process_title')) {
  945. @cli_set_process_title($title);
  946. } // Need proctitle when php<=5.5 .
  947. elseif (extension_loaded('proctitle') && function_exists('setproctitle')) {
  948. @setproctitle($title);
  949. }
  950. }
  951. /**
  952. * Monitor all child processes.
  953. *
  954. * @return void
  955. */
  956. protected static function monitorWorkers()
  957. {
  958. self::$_status = self::STATUS_RUNNING;
  959. while (1) {
  960. // Calls signal handlers for pending signals.
  961. pcntl_signal_dispatch();
  962. // Suspends execution of the current process until a child has exited, or until a signal is delivered
  963. $status = 0;
  964. $pid = pcntl_wait($status, WUNTRACED);
  965. // Calls signal handlers for pending signals again.
  966. pcntl_signal_dispatch();
  967. // If a child has already exited.
  968. if ($pid > 0) {
  969. // Find out witch worker process exited.
  970. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  971. if (isset($worker_pid_array[$pid])) {
  972. $worker = self::$_workers[$worker_id];
  973. // Exit status.
  974. if ($status !== 0) {
  975. self::log("worker[" . $worker->name . ":$pid] exit with status $status");
  976. }
  977. // For Statistics.
  978. if (!isset(self::$_globalStatistics['worker_exit_info'][$worker_id][$status])) {
  979. self::$_globalStatistics['worker_exit_info'][$worker_id][$status] = 0;
  980. }
  981. self::$_globalStatistics['worker_exit_info'][$worker_id][$status]++;
  982. // Clear process data.
  983. unset(self::$_pidMap[$worker_id][$pid]);
  984. // Mark id is available.
  985. $id = self::getId($worker_id, $pid);
  986. self::$_idMap[$worker_id][$id] = 0;
  987. break;
  988. }
  989. }
  990. // Is still running state then fork a new worker process.
  991. if (self::$_status !== self::STATUS_SHUTDOWN) {
  992. self::forkWorkers();
  993. // If reloading continue.
  994. if (isset(self::$_pidsToRestart[$pid])) {
  995. unset(self::$_pidsToRestart[$pid]);
  996. self::reload();
  997. }
  998. } else {
  999. // If shutdown state and all child processes exited then master process exit.
  1000. if (!self::getAllWorkerPids()) {
  1001. self::exitAndClearAll();
  1002. }
  1003. }
  1004. } else {
  1005. // If shutdown state and all child processes exited then master process exit.
  1006. if (self::$_status === self::STATUS_SHUTDOWN && !self::getAllWorkerPids()) {
  1007. self::exitAndClearAll();
  1008. }
  1009. }
  1010. }
  1011. }
  1012. /**
  1013. * Exit current process.
  1014. *
  1015. * @return void
  1016. */
  1017. protected static function exitAndClearAll()
  1018. {
  1019. foreach (self::$_workers as $worker) {
  1020. $socket_name = $worker->getSocketName();
  1021. if ($worker->transport === 'unix' && $socket_name) {
  1022. list(, $address) = explode(':', $socket_name, 2);
  1023. @unlink($address);
  1024. }
  1025. }
  1026. @unlink(self::$pidFile);
  1027. self::log("Workerman[" . basename(self::$_startFile) . "] has been stopped");
  1028. if (self::$onMasterStop) {
  1029. call_user_func(self::$onMasterStop);
  1030. }
  1031. exit(0);
  1032. }
  1033. /**
  1034. * Execute reload.
  1035. *
  1036. * @return void
  1037. */
  1038. protected static function reload()
  1039. {
  1040. // For master process.
  1041. if (self::$_masterPid === posix_getpid()) {
  1042. // Set reloading state.
  1043. if (self::$_status !== self::STATUS_RELOADING && self::$_status !== self::STATUS_SHUTDOWN) {
  1044. self::log("Workerman[" . basename(self::$_startFile) . "] reloading");
  1045. self::$_status = self::STATUS_RELOADING;
  1046. // Try to emit onMasterReload callback.
  1047. if (self::$onMasterReload) {
  1048. try {
  1049. call_user_func(self::$onMasterReload);
  1050. } catch (\Exception $e) {
  1051. self::log($e);
  1052. exit(250);
  1053. } catch (\Error $e) {
  1054. self::log($e);
  1055. exit(250);
  1056. }
  1057. self::initId();
  1058. }
  1059. }
  1060. // Send reload signal to all child processes.
  1061. $reloadable_pid_array = array();
  1062. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  1063. $worker = self::$_workers[$worker_id];
  1064. if ($worker->reloadable) {
  1065. foreach ($worker_pid_array as $pid) {
  1066. $reloadable_pid_array[$pid] = $pid;
  1067. }
  1068. } else {
  1069. foreach ($worker_pid_array as $pid) {
  1070. // Send reload signal to a worker process which reloadable is false.
  1071. posix_kill($pid, SIGUSR1);
  1072. }
  1073. }
  1074. }
  1075. // Get all pids that are waiting reload.
  1076. self::$_pidsToRestart = array_intersect(self::$_pidsToRestart, $reloadable_pid_array);
  1077. // Reload complete.
  1078. if (empty(self::$_pidsToRestart)) {
  1079. if (self::$_status !== self::STATUS_SHUTDOWN) {
  1080. self::$_status = self::STATUS_RUNNING;
  1081. }
  1082. return;
  1083. }
  1084. // Continue reload.
  1085. $one_worker_pid = current(self::$_pidsToRestart);
  1086. // Send reload signal to a worker process.
  1087. posix_kill($one_worker_pid, SIGUSR1);
  1088. // If the process does not exit after self::KILL_WORKER_TIMER_TIME seconds try to kill it.
  1089. Timer::add(self::KILL_WORKER_TIMER_TIME, 'posix_kill', array($one_worker_pid, SIGKILL), false);
  1090. } // For child processes.
  1091. else {
  1092. reset(self::$_workers);
  1093. $worker = current(self::$_workers);
  1094. // Try to emit onWorkerReload callback.
  1095. if ($worker->onWorkerReload) {
  1096. try {
  1097. call_user_func($worker->onWorkerReload, $worker);
  1098. } catch (\Exception $e) {
  1099. self::log($e);
  1100. exit(250);
  1101. } catch (\Error $e) {
  1102. self::log($e);
  1103. exit(250);
  1104. }
  1105. }
  1106. if ($worker->reloadable) {
  1107. self::stopAll();
  1108. }
  1109. }
  1110. }
  1111. /**
  1112. * Stop.
  1113. *
  1114. * @return void
  1115. */
  1116. public static function stopAll()
  1117. {
  1118. self::$_status = self::STATUS_SHUTDOWN;
  1119. // For master process.
  1120. if (self::$_masterPid === posix_getpid()) {
  1121. self::log("Workerman[" . basename(self::$_startFile) . "] Stopping ...");
  1122. $worker_pid_array = self::getAllWorkerPids();
  1123. // Send stop signal to all child processes.
  1124. foreach ($worker_pid_array as $worker_pid) {
  1125. posix_kill($worker_pid, SIGINT);
  1126. Timer::add(self::KILL_WORKER_TIMER_TIME, 'posix_kill', array($worker_pid, SIGKILL), false);
  1127. }
  1128. // Remove statistics file.
  1129. if (is_file(self::$_statisticsFile)) {
  1130. @unlink(self::$_statisticsFile);
  1131. }
  1132. } // For child processes.
  1133. else {
  1134. // Execute exit.
  1135. foreach (self::$_workers as $worker) {
  1136. $worker->stop();
  1137. }
  1138. self::$globalEvent->destroy();
  1139. exit(0);
  1140. }
  1141. }
  1142. /**
  1143. * Write statistics data to disk.
  1144. *
  1145. * @return void
  1146. */
  1147. protected static function writeStatisticsToStatusFile()
  1148. {
  1149. // For master process.
  1150. if (self::$_masterPid === posix_getpid()) {
  1151. $loadavg = function_exists('sys_getloadavg') ? array_map('round', sys_getloadavg(), array(2)) : array('-', '-', '-');
  1152. file_put_contents(self::$_statisticsFile,
  1153. "---------------------------------------GLOBAL STATUS--------------------------------------------\n");
  1154. file_put_contents(self::$_statisticsFile,
  1155. 'Workerman version:' . Worker::VERSION . " PHP version:" . PHP_VERSION . "\n", FILE_APPEND);
  1156. file_put_contents(self::$_statisticsFile, 'start time:' . date('Y-m-d H:i:s',
  1157. 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",
  1158. FILE_APPEND);
  1159. $load_str = 'load average: ' . implode(", ", $loadavg);
  1160. file_put_contents(self::$_statisticsFile,
  1161. str_pad($load_str, 33) . 'event-loop:' . self::getEventLoopName() . "\n", FILE_APPEND);
  1162. file_put_contents(self::$_statisticsFile,
  1163. count(self::$_pidMap) . ' workers ' . count(self::getAllWorkerPids()) . " processes\n",
  1164. FILE_APPEND);
  1165. file_put_contents(self::$_statisticsFile,
  1166. str_pad('worker_name', self::$_maxWorkerNameLength) . " exit_status exit_count\n", FILE_APPEND);
  1167. foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
  1168. $worker = self::$_workers[$worker_id];
  1169. if (isset(self::$_globalStatistics['worker_exit_info'][$worker_id])) {
  1170. foreach (self::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
  1171. file_put_contents(self::$_statisticsFile,
  1172. str_pad($worker->name, self::$_maxWorkerNameLength) . " " . str_pad($worker_exit_status,
  1173. 16) . " $worker_exit_count\n", FILE_APPEND);
  1174. }
  1175. } else {
  1176. file_put_contents(self::$_statisticsFile,
  1177. str_pad($worker->name, self::$_maxWorkerNameLength) . " " . str_pad(0, 16) . " 0\n",
  1178. FILE_APPEND);
  1179. }
  1180. }
  1181. file_put_contents(self::$_statisticsFile,
  1182. "---------------------------------------PROCESS STATUS-------------------------------------------\n",
  1183. FILE_APPEND);
  1184. file_put_contents(self::$_statisticsFile,
  1185. "pid\tmemory " . str_pad('listening', self::$_maxSocketNameLength) . " " . str_pad('worker_name',
  1186. self::$_maxWorkerNameLength) . " connections " . str_pad('total_request',
  1187. 13) . " " . str_pad('send_fail', 9) . " " . str_pad('timers', 15) . "\n", FILE_APPEND);
  1188. chmod(self::$_statisticsFile, 0722);
  1189. foreach (self::getAllWorkerPids() as $worker_pid) {
  1190. posix_kill($worker_pid, SIGUSR2);
  1191. }
  1192. return;
  1193. }
  1194. // For child processes.
  1195. /** @var Worker $worker */
  1196. $worker = current(self::$_workers);
  1197. $worker_status_str = posix_getpid() . "\t" . str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M",
  1198. 7) . " " . str_pad($worker->getSocketName(),
  1199. self::$_maxSocketNameLength) . " " . str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name),
  1200. self::$_maxWorkerNameLength) . " ";
  1201. $worker_status_str .= str_pad(ConnectionInterface::$statistics['connection_count'],
  1202. 11) . " " . str_pad(ConnectionInterface::$statistics['total_request'],
  1203. 14) . " " . str_pad(ConnectionInterface::$statistics['send_fail'],
  1204. 9) . " " . str_pad(self::$globalEvent->getTimerCount(), 15) . "\n";
  1205. file_put_contents(self::$_statisticsFile, $worker_status_str, FILE_APPEND);
  1206. }
  1207. /**
  1208. * Write statistics data to disk.
  1209. *
  1210. * @return void
  1211. */
  1212. protected static function writeConnectionsStatisticsToStatusFile()
  1213. {
  1214. // For master process.
  1215. if (self::$_masterPid === posix_getpid()) {
  1216. file_put_contents(self::$_statisticsFile, "------------------------------------------------------------ WORKERMAN CONNECTION STATUS --------------------------------------------------------------------------------\n", FILE_APPEND);
  1217. file_put_contents(self::$_statisticsFile, "Trans ipv4 ipv6 Recv-Q Send-Q Bytes-R Bytes-W Local Address Foreign Address Status PID ID Protocol Worker\n", FILE_APPEND);
  1218. chmod(self::$_statisticsFile, 0722);
  1219. foreach (self::getAllWorkerPids() as $worker_pid) {
  1220. posix_kill($worker_pid, SIGIO);
  1221. }
  1222. return;
  1223. }
  1224. // For child processes.
  1225. $bytes_format = function($bytes)
  1226. {
  1227. if($bytes > 1024*1024*1024*1024) {
  1228. return round($bytes/(1024*1024*1024*1024), 1)."TB";
  1229. }
  1230. if($bytes > 1024*1024*1024) {
  1231. return round($bytes/(1024*1024*1024), 1)."GB";
  1232. }
  1233. if($bytes > 1024*1024) {
  1234. return round($bytes/(1024*1024), 1)."MB";
  1235. }
  1236. if($bytes > 1024) {
  1237. return round($bytes/(1024), 1)."KB";
  1238. }
  1239. return $bytes."B";
  1240. };
  1241. $pid = posix_getpid();
  1242. $str = '';
  1243. reset(self::$_workers);
  1244. $current_worker = current(self::$_workers);
  1245. $default_worker_name = $current_worker->name;
  1246. /** @var Worker $worker */
  1247. foreach(TcpConnection::$connections as $connection) {
  1248. /** @var Connection\TcpConnection $connection */
  1249. $transport = $connection->transport;
  1250. $ipv4 = $connection->isIpV4() ? ' 1' : ' 0';
  1251. $ipv6 = $connection->isIpV6() ? ' 1' : ' 0';
  1252. $recv_q = $bytes_format($connection->getRecvBufferQueueSize());
  1253. $send_q = $bytes_format($connection->getSendBufferQueueSize());
  1254. $local_address = trim($connection->getLocalAddress());
  1255. $remote_address = trim($connection->getRemoteAddress());
  1256. $state = $connection->getStatus(false);
  1257. $bytes_read = $bytes_format($connection->bytesRead);
  1258. $bytes_written = $bytes_format($connection->bytesWritten);
  1259. $id = $connection->id;
  1260. $protocol = $connection->protocol ? $connection->protocol : $connection->transport;
  1261. $pos = strrpos($protocol, '\\');
  1262. if ($pos) {
  1263. $protocol = substr($protocol, $pos+1);
  1264. }
  1265. $worker_name = isset($connection->worker) ? $connection->worker->name : $default_worker_name;
  1266. $str .= str_pad($transport, 8) . str_pad($ipv4, 7) . str_pad($ipv6, 7)
  1267. . str_pad($recv_q, 13) . str_pad($send_q, 13) . str_pad($bytes_read, 13)
  1268. . str_pad($bytes_written, 13) . str_pad($local_address, 22) . ' '
  1269. . str_pad($remote_address, 22) . ' ' . str_pad($state, 14) . str_pad($pid, 8)
  1270. . str_pad($id, 10) . str_pad($protocol, 15) . ' ' . $worker_name."\n" ;
  1271. }
  1272. if ($str) {
  1273. file_put_contents(self::$_statisticsFile, $str, FILE_APPEND);
  1274. }
  1275. }
  1276. /**
  1277. * Check errors when current process exited.
  1278. *
  1279. * @return void
  1280. */
  1281. public static function checkErrors()
  1282. {
  1283. if (self::STATUS_SHUTDOWN != self::$_status) {
  1284. $error_msg = 'Worker['. posix_getpid() .'] process terminated with ';
  1285. $errors = error_get_last();
  1286. if ($errors && ($errors['type'] === E_ERROR ||
  1287. $errors['type'] === E_PARSE ||
  1288. $errors['type'] === E_CORE_ERROR ||
  1289. $errors['type'] === E_COMPILE_ERROR ||
  1290. $errors['type'] === E_RECOVERABLE_ERROR)
  1291. ) {
  1292. $error_msg .= self::getErrorType($errors['type']) . " \"{$errors['message']} in {$errors['file']} on line {$errors['line']}\"";
  1293. } else {
  1294. $error_msg .= 'exit()/die(). Please do not call exit()/die() in workerman.';
  1295. }
  1296. self::log($error_msg);
  1297. }
  1298. }
  1299. /**
  1300. * Get error message by error code.
  1301. *
  1302. * @param integer $type
  1303. * @return string
  1304. */
  1305. protected static function getErrorType($type)
  1306. {
  1307. switch ($type) {
  1308. case E_ERROR: // 1 //
  1309. return 'E_ERROR';
  1310. case E_WARNING: // 2 //
  1311. return 'E_WARNING';
  1312. case E_PARSE: // 4 //
  1313. return 'E_PARSE';
  1314. case E_NOTICE: // 8 //
  1315. return 'E_NOTICE';
  1316. case E_CORE_ERROR: // 16 //
  1317. return 'E_CORE_ERROR';
  1318. case E_CORE_WARNING: // 32 //
  1319. return 'E_CORE_WARNING';
  1320. case E_COMPILE_ERROR: // 64 //
  1321. return 'E_COMPILE_ERROR';
  1322. case E_COMPILE_WARNING: // 128 //
  1323. return 'E_COMPILE_WARNING';
  1324. case E_USER_ERROR: // 256 //
  1325. return 'E_USER_ERROR';
  1326. case E_USER_WARNING: // 512 //
  1327. return 'E_USER_WARNING';
  1328. case E_USER_NOTICE: // 1024 //
  1329. return 'E_USER_NOTICE';
  1330. case E_STRICT: // 2048 //
  1331. return 'E_STRICT';
  1332. case E_RECOVERABLE_ERROR: // 4096 //
  1333. return 'E_RECOVERABLE_ERROR';
  1334. case E_DEPRECATED: // 8192 //
  1335. return 'E_DEPRECATED';
  1336. case E_USER_DEPRECATED: // 16384 //
  1337. return 'E_USER_DEPRECATED';
  1338. }
  1339. return "";
  1340. }
  1341. /**
  1342. * Log.
  1343. *
  1344. * @param string $msg
  1345. * @return void
  1346. */
  1347. public static function log($msg)
  1348. {
  1349. $msg = $msg . "\n";
  1350. if (!self::$daemonize) {
  1351. self::safeEcho($msg);
  1352. }
  1353. file_put_contents((string)self::$logFile, date('Y-m-d H:i:s') . ' ' . 'pid:'. posix_getpid() . ' ' . $msg, FILE_APPEND | LOCK_EX);
  1354. }
  1355. /**
  1356. * Safe Echo.
  1357. *
  1358. * @param $msg
  1359. */
  1360. public static function safeEcho($msg)
  1361. {
  1362. if (!function_exists('posix_isatty') || posix_isatty(STDOUT)) {
  1363. echo $msg;
  1364. }
  1365. }
  1366. /**
  1367. * Construct.
  1368. *
  1369. * @param string $socket_name
  1370. * @param array $context_option
  1371. */
  1372. public function __construct($socket_name = '', $context_option = array())
  1373. {
  1374. // Save all worker instances.
  1375. $this->workerId = spl_object_hash($this);
  1376. self::$_workers[$this->workerId] = $this;
  1377. self::$_pidMap[$this->workerId] = array();
  1378. // Get autoload root path.
  1379. $backtrace = debug_backtrace();
  1380. $this->_autoloadRootPath = dirname($backtrace[0]['file']);
  1381. // Context for socket.
  1382. if ($socket_name) {
  1383. $this->_socketName = $socket_name;
  1384. if (!isset($context_option['socket']['backlog'])) {
  1385. $context_option['socket']['backlog'] = self::DEFAULT_BACKLOG;
  1386. }
  1387. $this->_context = stream_context_create($context_option);
  1388. }
  1389. // Set an empty onMessage callback.
  1390. $this->onMessage = function () {
  1391. };
  1392. }
  1393. /**
  1394. * Listen port.
  1395. *
  1396. * @throws Exception
  1397. */
  1398. public function listen()
  1399. {
  1400. if (!$this->_socketName || $this->_mainSocket) {
  1401. return;
  1402. }
  1403. // Autoload.
  1404. Autoloader::setRootPath($this->_autoloadRootPath);
  1405. // Get the application layer communication protocol and listening address.
  1406. list($scheme, $address) = explode(':', $this->_socketName, 2);
  1407. // Check application layer protocol class.
  1408. if (!isset(self::$_builtinTransports[$scheme])) {
  1409. $scheme = ucfirst($scheme);
  1410. $this->protocol = '\\Protocols\\' . $scheme;
  1411. if (!class_exists($this->protocol)) {
  1412. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  1413. if (!class_exists($this->protocol)) {
  1414. throw new Exception("class \\Protocols\\$scheme not exist");
  1415. }
  1416. }
  1417. if (!isset(self::$_builtinTransports[$this->transport])) {
  1418. throw new \Exception('Bad worker->transport ' . var_export($this->transport, true));
  1419. }
  1420. } else {
  1421. $this->transport = $scheme;
  1422. }
  1423. $local_socket = self::$_builtinTransports[$this->transport] . ":" . $address;
  1424. // Flag.
  1425. $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
  1426. $errno = 0;
  1427. $errmsg = '';
  1428. // SO_REUSEPORT.
  1429. if ($this->reusePort) {
  1430. stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
  1431. }
  1432. // Create an Internet or Unix domain server socket.
  1433. $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context);
  1434. if (!$this->_mainSocket) {
  1435. throw new Exception($errmsg);
  1436. }
  1437. if ($this->transport === 'ssl') {
  1438. stream_socket_enable_crypto($this->_mainSocket, false);
  1439. }
  1440. // Try to open keepalive for tcp and disable Nagle algorithm.
  1441. if (function_exists('socket_import_stream') && self::$_builtinTransports[$this->transport] === 'tcp') {
  1442. $socket = socket_import_stream($this->_mainSocket);
  1443. @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
  1444. @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
  1445. }
  1446. // Non blocking.
  1447. stream_set_blocking($this->_mainSocket, 0);
  1448. // Register a listener to be notified when server socket is ready to read.
  1449. if (self::$globalEvent) {
  1450. if ($this->transport !== 'udp') {
  1451. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptConnection'));
  1452. } else {
  1453. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1454. array($this, 'acceptUdpConnection'));
  1455. }
  1456. }
  1457. }
  1458. /**
  1459. * Get socket name.
  1460. *
  1461. * @return string
  1462. */
  1463. public function getSocketName()
  1464. {
  1465. return $this->_socketName ? lcfirst($this->_socketName) : 'none';
  1466. }
  1467. /**
  1468. * Run worker instance.
  1469. *
  1470. * @return void
  1471. */
  1472. public function run()
  1473. {
  1474. //Update process state.
  1475. self::$_status = self::STATUS_RUNNING;
  1476. // Register shutdown function for checking errors.
  1477. register_shutdown_function(array("\\Workerman\\Worker", 'checkErrors'));
  1478. // Set autoload root path.
  1479. Autoloader::setRootPath($this->_autoloadRootPath);
  1480. // Create a global event loop.
  1481. if (!self::$globalEvent) {
  1482. $event_loop_class = self::getEventLoopName();
  1483. self::$globalEvent = new $event_loop_class;
  1484. // Register a listener to be notified when server socket is ready to read.
  1485. if ($this->_socketName) {
  1486. if ($this->transport !== 'udp') {
  1487. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1488. array($this, 'acceptConnection'));
  1489. } else {
  1490. self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1491. array($this, 'acceptUdpConnection'));
  1492. }
  1493. }
  1494. }
  1495. // Reinstall signal.
  1496. self::reinstallSignal();
  1497. // Init Timer.
  1498. Timer::init(self::$globalEvent);
  1499. // Try to emit onWorkerStart callback.
  1500. if ($this->onWorkerStart) {
  1501. try {
  1502. call_user_func($this->onWorkerStart, $this);
  1503. } catch (\Exception $e) {
  1504. self::log($e);
  1505. // Avoid rapid infinite loop exit.
  1506. sleep(1);
  1507. exit(250);
  1508. } catch (\Error $e) {
  1509. self::log($e);
  1510. // Avoid rapid infinite loop exit.
  1511. sleep(1);
  1512. exit(250);
  1513. }
  1514. }
  1515. // Main loop.
  1516. self::$globalEvent->loop();
  1517. }
  1518. /**
  1519. * Stop current worker instance.
  1520. *
  1521. * @return void
  1522. */
  1523. public function stop()
  1524. {
  1525. // Try to emit onWorkerStop callback.
  1526. if ($this->onWorkerStop) {
  1527. try {
  1528. call_user_func($this->onWorkerStop, $this);
  1529. } catch (\Exception $e) {
  1530. self::log($e);
  1531. exit(250);
  1532. } catch (\Error $e) {
  1533. self::log($e);
  1534. exit(250);
  1535. }
  1536. }
  1537. // Remove listener for server socket.
  1538. if ($this->_mainSocket) {
  1539. self::$globalEvent->del($this->_mainSocket, EventInterface::EV_READ);
  1540. @fclose($this->_mainSocket);
  1541. }
  1542. }
  1543. /**
  1544. * Accept a connection.
  1545. *
  1546. * @param resource $socket
  1547. * @return void
  1548. */
  1549. public function acceptConnection($socket)
  1550. {
  1551. // Accept a connection on server socket.
  1552. $new_socket = @stream_socket_accept($socket, 0, $remote_address);
  1553. // Thundering herd.
  1554. if (!$new_socket) {
  1555. return;
  1556. }
  1557. // TcpConnection.
  1558. $connection = new TcpConnection($new_socket, $remote_address);
  1559. $this->connections[$connection->id] = $connection;
  1560. $connection->worker = $this;
  1561. $connection->protocol = $this->protocol;
  1562. $connection->transport = $this->transport;
  1563. $connection->onMessage = $this->onMessage;
  1564. $connection->onClose = $this->onClose;
  1565. $connection->onError = $this->onError;
  1566. $connection->onBufferDrain = $this->onBufferDrain;
  1567. $connection->onBufferFull = $this->onBufferFull;
  1568. // Try to emit onConnect callback.
  1569. if ($this->onConnect) {
  1570. try {
  1571. call_user_func($this->onConnect, $connection);
  1572. } catch (\Exception $e) {
  1573. self::log($e);
  1574. exit(250);
  1575. } catch (\Error $e) {
  1576. self::log($e);
  1577. exit(250);
  1578. }
  1579. }
  1580. }
  1581. /**
  1582. * For udp package.
  1583. *
  1584. * @param resource $socket
  1585. * @return bool
  1586. */
  1587. public function acceptUdpConnection($socket)
  1588. {
  1589. $recv_buffer = stream_socket_recvfrom($socket, self::MAX_UDP_PACKAGE_SIZE, 0, $remote_address);
  1590. if (false === $recv_buffer || empty($remote_address)) {
  1591. return false;
  1592. }
  1593. // UdpConnection.
  1594. $connection = new UdpConnection($socket, $remote_address);
  1595. $connection->protocol = $this->protocol;
  1596. if ($this->onMessage) {
  1597. if ($this->protocol !== null) {
  1598. $parser = $this->protocol;
  1599. $recv_buffer = $parser::decode($recv_buffer, $connection);
  1600. // Discard bad packets.
  1601. if ($recv_buffer === false)
  1602. return true;
  1603. }
  1604. ConnectionInterface::$statistics['total_request']++;
  1605. try {
  1606. call_user_func($this->onMessage, $connection, $recv_buffer);
  1607. } catch (\Exception $e) {
  1608. self::log($e);
  1609. exit(250);
  1610. } catch (\Error $e) {
  1611. self::log($e);
  1612. exit(250);
  1613. }
  1614. }
  1615. return true;
  1616. }
  1617. }