Worker.php 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250
  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 Workerman\Events\Select;
  22. use Exception;
  23. /**
  24. * Worker class
  25. * A container for listening ports
  26. */
  27. class Worker
  28. {
  29. /**
  30. * Version.
  31. *
  32. * @var string
  33. */
  34. const VERSION = '3.5.6';
  35. /**
  36. * Status starting.
  37. *
  38. * @var int
  39. */
  40. const STATUS_STARTING = 1;
  41. /**
  42. * Status running.
  43. *
  44. * @var int
  45. */
  46. const STATUS_RUNNING = 2;
  47. /**
  48. * Status shutdown.
  49. *
  50. * @var int
  51. */
  52. const STATUS_SHUTDOWN = 4;
  53. /**
  54. * Status reloading.
  55. *
  56. * @var int
  57. */
  58. const STATUS_RELOADING = 8;
  59. /**
  60. * After sending the restart command to the child process KILL_WORKER_TIMER_TIME seconds,
  61. * if the process is still living then forced to kill.
  62. *
  63. * @var int
  64. */
  65. const KILL_WORKER_TIMER_TIME = 2;
  66. /**
  67. * Default backlog. Backlog is the maximum length of the queue of pending connections.
  68. *
  69. * @var int
  70. */
  71. const DEFAULT_BACKLOG = 102400;
  72. /**
  73. * Max udp package size.
  74. *
  75. * @var int
  76. */
  77. const MAX_UDP_PACKAGE_SIZE = 65535;
  78. /**
  79. * Worker id.
  80. *
  81. * @var int
  82. */
  83. public $id = 0;
  84. /**
  85. * Name of the worker processes.
  86. *
  87. * @var string
  88. */
  89. public $name = 'none';
  90. /**
  91. * Number of worker processes.
  92. *
  93. * @var int
  94. */
  95. public $count = 1;
  96. /**
  97. * Unix user of processes, needs appropriate privileges (usually root).
  98. *
  99. * @var string
  100. */
  101. public $user = '';
  102. /**
  103. * Unix group of processes, needs appropriate privileges (usually root).
  104. *
  105. * @var string
  106. */
  107. public $group = '';
  108. /**
  109. * reloadable.
  110. *
  111. * @var bool
  112. */
  113. public $reloadable = true;
  114. /**
  115. * reuse port.
  116. *
  117. * @var bool
  118. */
  119. public $reusePort = false;
  120. /**
  121. * Emitted when worker processes start.
  122. *
  123. * @var callback
  124. */
  125. public $onWorkerStart = null;
  126. /**
  127. * Emitted when a socket connection is successfully established.
  128. *
  129. * @var callback
  130. */
  131. public $onConnect = null;
  132. /**
  133. * Emitted when data is received.
  134. *
  135. * @var callback
  136. */
  137. public $onMessage = null;
  138. /**
  139. * Emitted when the other end of the socket sends a FIN packet.
  140. *
  141. * @var callback
  142. */
  143. public $onClose = null;
  144. /**
  145. * Emitted when an error occurs with connection.
  146. *
  147. * @var callback
  148. */
  149. public $onError = null;
  150. /**
  151. * Emitted when the send buffer becomes full.
  152. *
  153. * @var callback
  154. */
  155. public $onBufferFull = null;
  156. /**
  157. * Emitted when the send buffer becomes empty.
  158. *
  159. * @var callback
  160. */
  161. public $onBufferDrain = null;
  162. /**
  163. * Emitted when worker processes stoped.
  164. *
  165. * @var callback
  166. */
  167. public $onWorkerStop = null;
  168. /**
  169. * Emitted when worker processes get reload signal.
  170. *
  171. * @var callback
  172. */
  173. public $onWorkerReload = null;
  174. /**
  175. * Transport layer protocol.
  176. *
  177. * @var string
  178. */
  179. public $transport = 'tcp';
  180. /**
  181. * Store all connections of clients.
  182. *
  183. * @var array
  184. */
  185. public $connections = array();
  186. /**
  187. * Application layer protocol.
  188. *
  189. * @var string
  190. */
  191. public $protocol = null;
  192. /**
  193. * Root path for autoload.
  194. *
  195. * @var string
  196. */
  197. protected $_autoloadRootPath = '';
  198. /**
  199. * Pause accept new connections or not.
  200. *
  201. * @var bool
  202. */
  203. protected $_pauseAccept = true;
  204. /**
  205. * Is worker stopping ?
  206. * @var bool
  207. */
  208. public $stopping = false;
  209. /**
  210. * Daemonize.
  211. *
  212. * @var bool
  213. */
  214. public static $daemonize = false;
  215. /**
  216. * Stdout file.
  217. *
  218. * @var string
  219. */
  220. public static $stdoutFile = '/dev/null';
  221. /**
  222. * The file to store master process PID.
  223. *
  224. * @var string
  225. */
  226. public static $pidFile = '';
  227. /**
  228. * Log file.
  229. *
  230. * @var mixed
  231. */
  232. public static $logFile = '';
  233. /**
  234. * Global event loop.
  235. *
  236. * @var Events\EventInterface
  237. */
  238. public static $globalEvent = null;
  239. /**
  240. * Emitted when the master process get reload signal.
  241. *
  242. * @var callback
  243. */
  244. public static $onMasterReload = null;
  245. /**
  246. * Emitted when the master process terminated.
  247. *
  248. * @var callback
  249. */
  250. public static $onMasterStop = null;
  251. /**
  252. * EventLoopClass
  253. *
  254. * @var string
  255. */
  256. public static $eventLoopClass = '';
  257. /**
  258. * The PID of master process.
  259. *
  260. * @var int
  261. */
  262. protected static $_masterPid = 0;
  263. /**
  264. * Listening socket.
  265. *
  266. * @var resource
  267. */
  268. protected $_mainSocket = null;
  269. /**
  270. * Socket name. The format is like this http://0.0.0.0:80 .
  271. *
  272. * @var string
  273. */
  274. protected $_socketName = '';
  275. /**
  276. * Context of socket.
  277. *
  278. * @var resource
  279. */
  280. protected $_context = null;
  281. /**
  282. * All worker instances.
  283. *
  284. * @var array
  285. */
  286. protected static $_workers = array();
  287. /**
  288. * All worker porcesses pid.
  289. * The format is like this [worker_id=>[pid=>pid, pid=>pid, ..], ..]
  290. *
  291. * @var array
  292. */
  293. protected static $_pidMap = array();
  294. /**
  295. * All worker processes waiting for restart.
  296. * The format is like this [pid=>pid, pid=>pid].
  297. *
  298. * @var array
  299. */
  300. protected static $_pidsToRestart = array();
  301. /**
  302. * Mapping from PID to worker process ID.
  303. * The format is like this [worker_id=>[0=>$pid, 1=>$pid, ..], ..].
  304. *
  305. * @var array
  306. */
  307. protected static $_idMap = array();
  308. /**
  309. * Current status.
  310. *
  311. * @var int
  312. */
  313. protected static $_status = self::STATUS_STARTING;
  314. /**
  315. * Maximum length of the worker names.
  316. *
  317. * @var int
  318. */
  319. protected static $_maxWorkerNameLength = 12;
  320. /**
  321. * Maximum length of the socket names.
  322. *
  323. * @var int
  324. */
  325. protected static $_maxSocketNameLength = 12;
  326. /**
  327. * Maximum length of the process user names.
  328. *
  329. * @var int
  330. */
  331. protected static $_maxUserNameLength = 12;
  332. /**
  333. * The file to store status info of current worker process.
  334. *
  335. * @var string
  336. */
  337. protected static $_statisticsFile = '';
  338. /**
  339. * Start file.
  340. *
  341. * @var string
  342. */
  343. protected static $_startFile = '';
  344. /**
  345. * OS.
  346. *
  347. * @var string
  348. */
  349. protected static $_OS = 'linux';
  350. /**
  351. * Processes for windows.
  352. *
  353. * @var array
  354. */
  355. protected static $_processForWindows = array();
  356. /**
  357. * Status info of current worker process.
  358. *
  359. * @var array
  360. */
  361. protected static $_globalStatistics = array(
  362. 'start_timestamp' => 0,
  363. 'worker_exit_info' => array()
  364. );
  365. /**
  366. * Available event loops.
  367. *
  368. * @var array
  369. */
  370. protected static $_availableEventLoops = array(
  371. 'libevent' => '\Workerman\Events\Libevent',
  372. 'event' => '\Workerman\Events\Event',
  373. 'swoole' => '\Workerman\Events\Swoole'
  374. );
  375. /**
  376. * PHP built-in protocols.
  377. *
  378. * @var array
  379. */
  380. protected static $_builtinTransports = array(
  381. 'tcp' => 'tcp',
  382. 'udp' => 'udp',
  383. 'unix' => 'unix',
  384. 'ssl' => 'tcp'
  385. );
  386. /**
  387. * Graceful stop or not.
  388. *
  389. * @var string
  390. */
  391. protected static $_gracefulStop = false;
  392. /**
  393. * Run all worker instances.
  394. *
  395. * @return void
  396. */
  397. public static function runAll()
  398. {
  399. static::checkSapiEnv();
  400. static::init();
  401. static::parseCommand();
  402. static::daemonize();
  403. static::initWorkers();
  404. static::installSignal();
  405. static::saveMasterPid();
  406. static::displayUI();
  407. static::forkWorkers();
  408. static::resetStd();
  409. static::monitorWorkers();
  410. }
  411. /**
  412. * Check sapi.
  413. *
  414. * @return void
  415. */
  416. protected static function checkSapiEnv()
  417. {
  418. // Only for cli.
  419. if (php_sapi_name() != "cli") {
  420. exit("only run in command line mode \n");
  421. }
  422. if (DIRECTORY_SEPARATOR === '\\') {
  423. self::$_OS = 'windows';
  424. }
  425. }
  426. /**
  427. * Init.
  428. *
  429. * @return void
  430. */
  431. protected static function init()
  432. {
  433. // Start file.
  434. $backtrace = debug_backtrace();
  435. static::$_startFile = $backtrace[count($backtrace) - 1]['file'];
  436. $unique_prefix = str_replace('/', '_', static::$_startFile);
  437. // Pid file.
  438. if (empty(static::$pidFile)) {
  439. static::$pidFile = __DIR__ . "/../$unique_prefix.pid";
  440. }
  441. // Log file.
  442. if (empty(static::$logFile)) {
  443. static::$logFile = __DIR__ . '/../workerman.log';
  444. }
  445. $log_file = (string)static::$logFile;
  446. if (!is_file($log_file)) {
  447. touch($log_file);
  448. chmod($log_file, 0622);
  449. }
  450. // State.
  451. static::$_status = static::STATUS_STARTING;
  452. // For statistics.
  453. static::$_globalStatistics['start_timestamp'] = time();
  454. static::$_statisticsFile = sys_get_temp_dir() . "/$unique_prefix.status";
  455. // Process title.
  456. static::setProcessTitle('WorkerMan: master process start_file=' . static::$_startFile);
  457. // Init data for worker id.
  458. static::initId();
  459. // Timer init.
  460. Timer::init();
  461. }
  462. /**
  463. * Init All worker instances.
  464. *
  465. * @return void
  466. */
  467. protected static function initWorkers()
  468. {
  469. if (static::$_OS !== 'linux') {
  470. return;
  471. }
  472. foreach (static::$_workers as $worker) {
  473. // Worker name.
  474. if (empty($worker->name)) {
  475. $worker->name = 'none';
  476. }
  477. // Get maximum length of worker name.
  478. $worker_name_length = strlen($worker->name);
  479. if (static::$_maxWorkerNameLength < $worker_name_length) {
  480. static::$_maxWorkerNameLength = $worker_name_length;
  481. }
  482. // Get maximum length of socket name.
  483. $socket_name_length = strlen($worker->getSocketName());
  484. if (static::$_maxSocketNameLength < $socket_name_length) {
  485. static::$_maxSocketNameLength = $socket_name_length;
  486. }
  487. // Get unix user of the worker process.
  488. if (empty($worker->user)) {
  489. $worker->user = static::getCurrentUser();
  490. } else {
  491. if (posix_getuid() !== 0 && $worker->user != static::getCurrentUser()) {
  492. static::log('Warning: You must have the root privileges to change uid and gid.');
  493. }
  494. }
  495. // Get maximum length of unix user name.
  496. $user_name_length = strlen($worker->user);
  497. if (static::$_maxUserNameLength < $user_name_length) {
  498. static::$_maxUserNameLength = $user_name_length;
  499. }
  500. // Listen.
  501. if (!$worker->reusePort) {
  502. $worker->listen();
  503. }
  504. }
  505. }
  506. /**
  507. * Get all worker instances.
  508. *
  509. * @return array
  510. */
  511. public static function getAllWorkers()
  512. {
  513. return static::$_workers;
  514. }
  515. /**
  516. * Get global event-loop instance.
  517. *
  518. * @return EventInterface
  519. */
  520. public static function getEventLoop()
  521. {
  522. return static::$globalEvent;
  523. }
  524. /**
  525. * Init idMap.
  526. * return void
  527. */
  528. protected static function initId()
  529. {
  530. foreach (static::$_workers as $worker_id => $worker) {
  531. $new_id_map = array();
  532. $worker->count = $worker->count <= 0 ? 1 : $worker->count;
  533. for($key = 0; $key < $worker->count; $key++) {
  534. $new_id_map[$key] = isset(static::$_idMap[$worker_id][$key]) ? static::$_idMap[$worker_id][$key] : 0;
  535. }
  536. static::$_idMap[$worker_id] = $new_id_map;
  537. }
  538. }
  539. /**
  540. * Get unix user of current porcess.
  541. *
  542. * @return string
  543. */
  544. protected static function getCurrentUser()
  545. {
  546. $user_info = posix_getpwuid(posix_getuid());
  547. return $user_info['name'];
  548. }
  549. /**
  550. * Display staring UI.
  551. *
  552. * @return void
  553. */
  554. protected static function displayUI()
  555. {
  556. global $argv;
  557. if (in_array('-q', $argv)) {
  558. return;
  559. }
  560. if (static::$_OS !== 'linux') {
  561. static::safeEcho("----------------------- WORKERMAN -----------------------------\r\n");
  562. static::safeEcho('Workerman version:'. static::VERSION. " PHP version:". PHP_VERSION. "\r\n");
  563. static::safeEcho("------------------------ WORKERS -------------------------------\r\n");
  564. static::safeEcho("worker listen processes status\r\n");
  565. return;
  566. }
  567. static::safeEcho("\033[1A\n\033[K-----------------------\033[47;30m WORKERMAN \033[0m-----------------------------\r\n\033[0m");
  568. static::safeEcho('Workerman version:'. static::VERSION. " PHP version:". PHP_VERSION. "\r\n");
  569. static::safeEcho("------------------------\033[47;30m WORKERS \033[0m-------------------------------\r\n");
  570. static::safeEcho("\033[47;30muser\033[0m". str_pad('',
  571. static::$_maxUserNameLength + 2 - strlen('user')). "\033[47;30mworker\033[0m". str_pad('',
  572. static::$_maxWorkerNameLength + 2 - strlen('worker')). "\033[47;30mlisten\033[0m". str_pad('',
  573. static::$_maxSocketNameLength + 2 - strlen('listen')). "\033[47;30mprocesses\033[0m \033[47;30m". "status\033[0m\n");
  574. foreach (static::$_workers as $worker) {
  575. static::safeEcho(str_pad($worker->user, static::$_maxUserNameLength + 2). str_pad($worker->name,
  576. static::$_maxWorkerNameLength + 2). str_pad($worker->getSocketName(),
  577. static::$_maxSocketNameLength + 2). str_pad(' ' . $worker->count, 9). " \033[32;40m [OK] \033[0m\n");
  578. }
  579. static::safeEcho("----------------------------------------------------------------\n");
  580. if (static::$daemonize) {
  581. static::safeEcho("Input \"php $argv[0] stop\" to stop. Start success.\n\n");
  582. } else {
  583. static::safeEcho("Press Ctrl+C to stop. Start success.\n");
  584. }
  585. }
  586. /**
  587. * Parse command.
  588. * php yourfile.php start | stop | restart | reload | status [-d]
  589. *
  590. * @return void
  591. */
  592. protected static function parseCommand()
  593. {
  594. if (static::$_OS !== 'linux') {
  595. return;
  596. }
  597. global $argv;
  598. // Check argv;
  599. $start_file = $argv[0];
  600. $available_commands = array(
  601. 'start',
  602. 'stop',
  603. 'restart',
  604. 'reload',
  605. 'status',
  606. 'connections',
  607. );
  608. $usage = "Usage: php yourfile <command> [mode]\nCommands: \nstart\t\tStart worker in DEBUG mode.\n\t\tUse mode -d to start in DAEMON mode.\nstop\t\tStop worker.\n\t\tUse mode -g to stop gracefully.\nrestart\t\tRestart workers.\n\t\tUse mode -d to start in DAEMON mode.\n\t\tUse mode -g to stop gracefully.\nreload\t\tReload codes.\n\t\tUse mode -g to reload gracefully.\nstatus\t\tGet worker status.\n\t\tUse mode -d to show live status.\nconnections\tGet worker connections.\n";
  609. if (!isset($argv[1]) || !in_array($argv[1], $available_commands)) {
  610. if(isset($argv[1])) echo 'Unknown command: ' . $argv[1] . "\n";
  611. exit($usage);
  612. }
  613. // Get command.
  614. $command = trim($argv[1]);
  615. $command2 = isset($argv[2]) ? $argv[2] : '';
  616. // Start command.
  617. $mode = '';
  618. if ($command === 'start') {
  619. if ($command2 === '-d' || static::$daemonize) {
  620. $mode = 'in DAEMON mode';
  621. } else {
  622. $mode = 'in DEBUG mode';
  623. }
  624. }
  625. static::log("Workerman[$start_file] $command $mode");
  626. // Get master process PID.
  627. $master_pid = is_file(static::$pidFile) ? file_get_contents(static::$pidFile) : 0;
  628. $master_is_alive = $master_pid && @posix_kill($master_pid, 0) && posix_getpid() != $master_pid;
  629. // Master is still alive?
  630. if ($master_is_alive) {
  631. if ($command === 'start') {
  632. static::log("Workerman[$start_file] already running");
  633. exit;
  634. }
  635. } elseif ($command !== 'start' && $command !== 'restart') {
  636. static::log("Workerman[$start_file] not run");
  637. exit;
  638. }
  639. // execute command.
  640. switch ($command) {
  641. case 'start':
  642. if ($command2 === '-d') {
  643. static::$daemonize = true;
  644. }
  645. break;
  646. case 'status':
  647. while (1) {
  648. if (is_file(static::$_statisticsFile)) {
  649. @unlink(static::$_statisticsFile);
  650. }
  651. // Master process will send SIGUSR2 signal to all child processes.
  652. posix_kill($master_pid, SIGUSR2);
  653. // Sleep 1 second.
  654. sleep(1);
  655. // Clear terminal.
  656. if ($command2 === '-d') {
  657. echo "\33[H\33[2J\33(B\33[m";
  658. }
  659. // Echo status data.
  660. echo static::formatStatusData();
  661. if ($command2 !== '-d') {
  662. exit(0);
  663. }
  664. echo "\nPress Ctrl+C to quit.\n\n";
  665. }
  666. exit(0);
  667. case 'connections':
  668. if (is_file(static::$_statisticsFile)) {
  669. @unlink(static::$_statisticsFile);
  670. }
  671. // Master process will send SIGIO signal to all child processes.
  672. posix_kill($master_pid, SIGIO);
  673. // Waiting amoment.
  674. usleep(500000);
  675. // Display statisitcs data from a disk file.
  676. @readfile(static::$_statisticsFile);
  677. exit(0);
  678. case 'restart':
  679. case 'stop':
  680. if ($command2 === '-g') {
  681. static::$_gracefulStop = true;
  682. $sig = SIGTERM;
  683. static::log("Workerman[$start_file] is gracefully stopping ...");
  684. } else {
  685. static::$_gracefulStop = false;
  686. $sig = SIGINT;
  687. static::log("Workerman[$start_file] is stopping ...");
  688. }
  689. // Send stop signal to master process.
  690. $master_pid && posix_kill($master_pid, $sig);
  691. // Timeout.
  692. $timeout = 5;
  693. $start_time = time();
  694. // Check master process is still alive?
  695. while (1) {
  696. $master_is_alive = $master_pid && posix_kill($master_pid, 0);
  697. if ($master_is_alive) {
  698. // Timeout?
  699. if (!static::$_gracefulStop && time() - $start_time >= $timeout) {
  700. static::log("Workerman[$start_file] stop fail");
  701. exit;
  702. }
  703. // Waiting amoment.
  704. usleep(10000);
  705. continue;
  706. }
  707. // Stop success.
  708. static::log("Workerman[$start_file] stop success");
  709. if ($command === 'stop') {
  710. exit(0);
  711. }
  712. if ($command2 === '-d') {
  713. static::$daemonize = true;
  714. }
  715. break;
  716. }
  717. break;
  718. case 'reload':
  719. if($command2 === '-g'){
  720. $sig = SIGQUIT;
  721. }else{
  722. $sig = SIGUSR1;
  723. }
  724. posix_kill($master_pid, $sig);
  725. exit;
  726. default :
  727. echo 'Unknown command: ' . $command . "\n";
  728. exit($usage);
  729. }
  730. }
  731. /**
  732. * Format status data.
  733. *
  734. * @return string
  735. */
  736. protected static function formatStatusData()
  737. {
  738. static $total_request_cache = array();
  739. $info = @file(static::$_statisticsFile, FILE_IGNORE_NEW_LINES);
  740. if (!$info) {
  741. return '';
  742. }
  743. $status_str = '';
  744. $current_total_request = array();
  745. $worker_info = json_decode($info[0], true);
  746. ksort($worker_info, SORT_NUMERIC);
  747. unset($info[0]);
  748. $data_waiting_sort = array();
  749. $read_process_status = false;
  750. $total_requests = 0;
  751. $total_qps = 0;
  752. $total_connections = 0;
  753. $total_fails = 0;
  754. $total_memory = 0;
  755. $total_timers = 0;
  756. $maxLen1 = static::$_maxSocketNameLength;
  757. $maxLen2 = static::$_maxWorkerNameLength;
  758. foreach($info as $key => $value) {
  759. if (!$read_process_status) {
  760. $status_str .= $value . "\n";
  761. if (preg_match('/^pid.*?memory.*?listening/', $value)) {
  762. $read_process_status = true;
  763. }
  764. continue;
  765. }
  766. if(preg_match('/^[0-9]+/', $value, $pid_math)) {
  767. $pid = $pid_math[0];
  768. $data_waiting_sort[$pid] = $value;
  769. if(preg_match('/^\S+?\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?/', $value, $match)) {
  770. $total_memory += intval(str_ireplace('M','',$match[1]));
  771. $maxLen1 = max($maxLen1,strlen($match[2]));
  772. $maxLen2 = max($maxLen2,strlen($match[3]));
  773. $total_connections += intval($match[4]);
  774. $total_fails += intval($match[5]);
  775. $total_timers += intval($match[6]);
  776. $current_total_request[$pid] = $match[7];
  777. $total_requests += intval($match[7]);
  778. }
  779. }
  780. }
  781. foreach($worker_info as $pid => $info) {
  782. if (!isset($data_waiting_sort[$pid])) {
  783. $status_str .= "$pid\t" . str_pad('N/A', 7) . " "
  784. . str_pad($info['listen'], static::$_maxSocketNameLength) . " "
  785. . str_pad($info['name'], static::$_maxWorkerNameLength) . " "
  786. . str_pad('N/A', 11) . " " . str_pad('N/A', 9) . " "
  787. . str_pad('N/A', 7) . " " . str_pad('N/A', 13) . " N/A [busy] \n";
  788. continue;
  789. }
  790. //$qps = isset($total_request_cache[$pid]) ? $current_total_request[$pid]
  791. if (!isset($total_request_cache[$pid]) || !isset($current_total_request[$pid])) {
  792. $qps = 0;
  793. } else {
  794. $qps = $current_total_request[$pid] - $total_request_cache[$pid];
  795. $total_qps += $qps;
  796. }
  797. $status_str .= $data_waiting_sort[$pid]. " " . str_pad($qps, 6) ." [idle]\n";
  798. }
  799. $total_request_cache = $current_total_request;
  800. $status_str .= "----------------------------------------------PROCESS STATUS---------------------------------------------------\n";
  801. $status_str .= "Summary\t" . str_pad($total_memory.'M', 7) . " "
  802. . str_pad('-', $maxLen1) . " "
  803. . str_pad('-', $maxLen2) . " "
  804. . str_pad($total_connections, 11) . " " . str_pad($total_fails, 9) . " "
  805. . str_pad($total_timers, 7) . " " . str_pad($total_requests, 13) . " "
  806. . str_pad($total_qps,6)." [Summary] \n";
  807. return $status_str;
  808. }
  809. /**
  810. * Install signal handler.
  811. *
  812. * @return void
  813. */
  814. protected static function installSignal()
  815. {
  816. if (static::$_OS !== 'linux') {
  817. return;
  818. }
  819. // stop
  820. pcntl_signal(SIGINT, array('\Workerman\Worker', 'signalHandler'), false);
  821. // graceful stop
  822. pcntl_signal(SIGTERM, array('\Workerman\Worker', 'signalHandler'), false);
  823. // reload
  824. pcntl_signal(SIGUSR1, array('\Workerman\Worker', 'signalHandler'), false);
  825. // graceful reload
  826. pcntl_signal(SIGQUIT, array('\Workerman\Worker', 'signalHandler'), false);
  827. // status
  828. pcntl_signal(SIGUSR2, array('\Workerman\Worker', 'signalHandler'), false);
  829. // connection status
  830. pcntl_signal(SIGIO, array('\Workerman\Worker', 'signalHandler'), false);
  831. // ignore
  832. pcntl_signal(SIGPIPE, SIG_IGN, false);
  833. }
  834. /**
  835. * Reinstall signal handler.
  836. *
  837. * @return void
  838. */
  839. protected static function reinstallSignal()
  840. {
  841. if (static::$_OS !== 'linux') {
  842. return;
  843. }
  844. // uninstall stop signal handler
  845. pcntl_signal(SIGINT, SIG_IGN, false);
  846. // uninstall graceful stop signal handler
  847. pcntl_signal(SIGTERM, SIG_IGN, false);
  848. // uninstall reload signal handler
  849. pcntl_signal(SIGUSR1, SIG_IGN, false);
  850. // uninstall graceful reload signal handler
  851. pcntl_signal(SIGQUIT, SIG_IGN, false);
  852. // uninstall status signal handler
  853. pcntl_signal(SIGUSR2, SIG_IGN, false);
  854. // reinstall stop signal handler
  855. static::$globalEvent->add(SIGINT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  856. // reinstall graceful stop signal handler
  857. static::$globalEvent->add(SIGTERM, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  858. // reinstall reload signal handler
  859. static::$globalEvent->add(SIGUSR1, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  860. // reinstall graceful reload signal handler
  861. static::$globalEvent->add(SIGQUIT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  862. // reinstall status signal handler
  863. static::$globalEvent->add(SIGUSR2, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  864. // reinstall connection status signal handler
  865. static::$globalEvent->add(SIGIO, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
  866. }
  867. /**
  868. * Signal handler.
  869. *
  870. * @param int $signal
  871. */
  872. public static function signalHandler($signal)
  873. {
  874. switch ($signal) {
  875. // Stop.
  876. case SIGINT:
  877. static::$_gracefulStop = false;
  878. static::stopAll();
  879. break;
  880. // Graceful stop.
  881. case SIGTERM:
  882. static::$_gracefulStop = true;
  883. static::stopAll();
  884. break;
  885. // Reload.
  886. case SIGQUIT:
  887. case SIGUSR1:
  888. if($signal === SIGQUIT){
  889. static::$_gracefulStop = true;
  890. }else{
  891. static::$_gracefulStop = false;
  892. }
  893. static::$_pidsToRestart = static::getAllWorkerPids();
  894. static::reload();
  895. break;
  896. // Show status.
  897. case SIGUSR2:
  898. static::writeStatisticsToStatusFile();
  899. break;
  900. // Show connection status.
  901. case SIGIO:
  902. static::writeConnectionsStatisticsToStatusFile();
  903. break;
  904. }
  905. }
  906. /**
  907. * Run as deamon mode.
  908. *
  909. * @throws Exception
  910. */
  911. protected static function daemonize()
  912. {
  913. if (!static::$daemonize || static::$_OS !== 'linux') {
  914. return;
  915. }
  916. umask(0);
  917. $pid = pcntl_fork();
  918. if (-1 === $pid) {
  919. throw new Exception('fork fail');
  920. } elseif ($pid > 0) {
  921. exit(0);
  922. }
  923. if (-1 === posix_setsid()) {
  924. throw new Exception("setsid fail");
  925. }
  926. // Fork again avoid SVR4 system regain the control of terminal.
  927. $pid = pcntl_fork();
  928. if (-1 === $pid) {
  929. throw new Exception("fork fail");
  930. } elseif (0 !== $pid) {
  931. exit(0);
  932. }
  933. }
  934. /**
  935. * Redirect standard input and output.
  936. *
  937. * @throws Exception
  938. */
  939. public static function resetStd()
  940. {
  941. if (!static::$daemonize || static::$_OS !== 'linux') {
  942. return;
  943. }
  944. global $STDOUT, $STDERR;
  945. $handle = fopen(static::$stdoutFile, "a");
  946. if ($handle) {
  947. unset($handle);
  948. @fclose(STDOUT);
  949. @fclose(STDERR);
  950. $STDOUT = fopen(static::$stdoutFile, "a");
  951. $STDERR = fopen(static::$stdoutFile, "a");
  952. } else {
  953. throw new Exception('can not open stdoutFile ' . static::$stdoutFile);
  954. }
  955. }
  956. /**
  957. * Save pid.
  958. *
  959. * @throws Exception
  960. */
  961. protected static function saveMasterPid()
  962. {
  963. if (static::$_OS !== 'linux') {
  964. return;
  965. }
  966. static::$_masterPid = posix_getpid();
  967. if (false === @file_put_contents(static::$pidFile, static::$_masterPid)) {
  968. throw new Exception('can not save pid to ' . static::$pidFile);
  969. }
  970. }
  971. /**
  972. * Get event loop name.
  973. *
  974. * @return string
  975. */
  976. protected static function getEventLoopName()
  977. {
  978. if (static::$eventLoopClass) {
  979. return static::$eventLoopClass;
  980. }
  981. $loop_name = '';
  982. foreach (static::$_availableEventLoops as $name=>$class) {
  983. if (extension_loaded($name)) {
  984. $loop_name = $name;
  985. break;
  986. }
  987. }
  988. if ($loop_name) {
  989. if (interface_exists('\React\EventLoop\LoopInterface')) {
  990. switch ($loop_name) {
  991. case 'libevent':
  992. static::$eventLoopClass = '\Workerman\Events\React\ExtLibEventLoop';
  993. break;
  994. case 'event':
  995. static::$eventLoopClass = '\Workerman\Events\React\ExtEventLoop';
  996. break;
  997. default :
  998. static::$eventLoopClass = '\Workerman\Events\React\StreamSelectLoop';
  999. break;
  1000. }
  1001. } else {
  1002. static::$eventLoopClass = static::$_availableEventLoops[$loop_name];
  1003. }
  1004. } else {
  1005. static::$eventLoopClass = interface_exists('\React\EventLoop\LoopInterface')? '\Workerman\Events\React\StreamSelectLoop':'\Workerman\Events\Select';
  1006. }
  1007. return static::$eventLoopClass;
  1008. }
  1009. /**
  1010. * Get all pids of worker processes.
  1011. *
  1012. * @return array
  1013. */
  1014. protected static function getAllWorkerPids()
  1015. {
  1016. $pid_array = array();
  1017. foreach (static::$_pidMap as $worker_pid_array) {
  1018. foreach ($worker_pid_array as $worker_pid) {
  1019. $pid_array[$worker_pid] = $worker_pid;
  1020. }
  1021. }
  1022. return $pid_array;
  1023. }
  1024. /**
  1025. * Fork some worker processes.
  1026. *
  1027. * @return void
  1028. */
  1029. protected static function forkWorkers()
  1030. {
  1031. if (static::$_OS === 'linux') {
  1032. static::forkWorkersForLinux();
  1033. } else {
  1034. static::forkWorkersForWindows();
  1035. }
  1036. }
  1037. /**
  1038. * Fork some worker processes.
  1039. *
  1040. * @return void
  1041. */
  1042. protected static function forkWorkersForLinux()
  1043. {
  1044. foreach (static::$_workers as $worker) {
  1045. if (static::$_status === static::STATUS_STARTING) {
  1046. if (empty($worker->name)) {
  1047. $worker->name = $worker->getSocketName();
  1048. }
  1049. $worker_name_length = strlen($worker->name);
  1050. if (static::$_maxWorkerNameLength < $worker_name_length) {
  1051. static::$_maxWorkerNameLength = $worker_name_length;
  1052. }
  1053. }
  1054. while (count(static::$_pidMap[$worker->workerId]) < $worker->count) {
  1055. static::forkOneWorkerForLinux($worker);
  1056. }
  1057. }
  1058. }
  1059. /**
  1060. * Fork some worker processes.
  1061. *
  1062. * @return void
  1063. */
  1064. protected static function forkWorkersForWindows()
  1065. {
  1066. $files = static::getStartFilesForWindows();
  1067. global $argv;
  1068. if(isset($argv[1]) && $argv[1] === '-q')
  1069. {
  1070. if(count(static::$_workers) > 1)
  1071. {
  1072. echo "@@@ Error: multi workers init in one php file are not support @@@\r\n";
  1073. echo "@@@ Please visit http://wiki.workerman.net/Multi_woker_for_win @@@\r\n";
  1074. }
  1075. elseif(count(static::$_workers) <= 0)
  1076. {
  1077. exit("@@@no worker inited@@@\r\n\r\n");
  1078. }
  1079. reset(static::$_workers);
  1080. /** @var Worker $worker */
  1081. $worker = current(static::$_workers);
  1082. // Display UI.
  1083. echo str_pad($worker->name, 21) . str_pad($worker->getSocketName(), 36) . str_pad($worker->count, 10) . "[ok]\n";
  1084. $worker->listen();
  1085. $worker->run();
  1086. exit("@@@child exit@@@\r\n");
  1087. }
  1088. else
  1089. {
  1090. static::$globalEvent = new \Workerman\Events\Select();
  1091. Timer::init(static::$globalEvent);
  1092. foreach($files as $start_file)
  1093. {
  1094. static::forkOneWorkerForWindows($start_file);
  1095. }
  1096. }
  1097. }
  1098. /**
  1099. * Get start files for windows.
  1100. *
  1101. * @return array
  1102. */
  1103. public static function getStartFilesForWindows() {
  1104. global $argv;
  1105. $files = array();
  1106. foreach($argv as $file)
  1107. {
  1108. $ext = pathinfo($file, PATHINFO_EXTENSION );
  1109. if($ext !== 'php')
  1110. {
  1111. continue;
  1112. }
  1113. if(is_file($file))
  1114. {
  1115. $files[$file] = $file;
  1116. }
  1117. }
  1118. return $files;
  1119. }
  1120. /**
  1121. * Fork one worker process.
  1122. *
  1123. * @param string $start_file
  1124. */
  1125. public static function forkOneWorkerForWindows($start_file)
  1126. {
  1127. $start_file = realpath($start_file);
  1128. $std_file = sys_get_temp_dir() . '/'.str_replace(array('/', "\\", ':'), '_', $start_file).'.out.txt';
  1129. $descriptorspec = array(
  1130. 0 => array('pipe', 'a'), // stdin
  1131. 1 => array('file', $std_file, 'w'), // stdout
  1132. 2 => array('file', $std_file, 'w') // stderr
  1133. );
  1134. $pipes = array();
  1135. $process = proc_open("php \"$start_file\" -q", $descriptorspec, $pipes);
  1136. $std_handler = fopen($std_file, 'a+');
  1137. stream_set_blocking($std_handler, 0);
  1138. if (empty(static::$globalEvent)) {
  1139. static::$globalEvent = new Select();
  1140. Timer::init(static::$globalEvent);
  1141. }
  1142. $timer_id = Timer::add(1, function()use($std_handler)
  1143. {
  1144. echo fread($std_handler, 65535);
  1145. });
  1146. // 保存子进程句柄
  1147. static::$_processForWindows[$start_file] = array($process, $start_file, $timer_id);
  1148. }
  1149. /**
  1150. * check worker status for windows.
  1151. * @return void
  1152. */
  1153. public static function checkWorkerStatusForWindows()
  1154. {
  1155. foreach(static::$_processForWindows as $process_data)
  1156. {
  1157. $process = $process_data[0];
  1158. $start_file = $process_data[1];
  1159. $timer_id = $process_data[2];
  1160. $status = proc_get_status($process);
  1161. if(isset($status['running']))
  1162. {
  1163. if(!$status['running'])
  1164. {
  1165. echo "process $start_file terminated and try to restart\n";
  1166. Timer::del($timer_id);
  1167. @proc_close($process);
  1168. static::forkOneWorkerForWindows($start_file);
  1169. }
  1170. }
  1171. else
  1172. {
  1173. echo "proc_get_status fail\n";
  1174. }
  1175. }
  1176. }
  1177. /**
  1178. * Fork one worker process.
  1179. *
  1180. * @param \Workerman\Worker $worker
  1181. * @throws Exception
  1182. */
  1183. protected static function forkOneWorkerForLinux($worker)
  1184. {
  1185. // Get available worker id.
  1186. $id = static::getId($worker->workerId, 0);
  1187. if ($id === false) {
  1188. return;
  1189. }
  1190. $pid = pcntl_fork();
  1191. // For master process.
  1192. if ($pid > 0) {
  1193. static::$_pidMap[$worker->workerId][$pid] = $pid;
  1194. static::$_idMap[$worker->workerId][$id] = $pid;
  1195. } // For child processes.
  1196. elseif (0 === $pid) {
  1197. if ($worker->reusePort) {
  1198. $worker->listen();
  1199. }
  1200. if (static::$_status === static::STATUS_STARTING) {
  1201. static::resetStd();
  1202. }
  1203. static::$_pidMap = array();
  1204. // Remove other listener.
  1205. foreach(static::$_workers as $key => $one_worker) {
  1206. if ($one_worker->workerId !== $worker->workerId) {
  1207. $one_worker->unlisten();
  1208. unset(static::$_workers[$key]);
  1209. }
  1210. }
  1211. Timer::delAll();
  1212. static::setProcessTitle('WorkerMan: worker process ' . $worker->name . ' ' . $worker->getSocketName());
  1213. $worker->setUserAndGroup();
  1214. $worker->id = $id;
  1215. $worker->run();
  1216. $err = new Exception('event-loop exited');
  1217. static::log($err);
  1218. exit(250);
  1219. } else {
  1220. throw new Exception("forkOneWorker fail");
  1221. }
  1222. }
  1223. /**
  1224. * Get worker id.
  1225. *
  1226. * @param int $worker_id
  1227. * @param int $pid
  1228. *
  1229. * @return integer
  1230. */
  1231. protected static function getId($worker_id, $pid)
  1232. {
  1233. return array_search($pid, static::$_idMap[$worker_id]);
  1234. }
  1235. /**
  1236. * Set unix user and group for current process.
  1237. *
  1238. * @return void
  1239. */
  1240. public function setUserAndGroup()
  1241. {
  1242. // Get uid.
  1243. $user_info = posix_getpwnam($this->user);
  1244. if (!$user_info) {
  1245. static::log("Warning: User {$this->user} not exsits");
  1246. return;
  1247. }
  1248. $uid = $user_info['uid'];
  1249. // Get gid.
  1250. if ($this->group) {
  1251. $group_info = posix_getgrnam($this->group);
  1252. if (!$group_info) {
  1253. static::log("Warning: Group {$this->group} not exsits");
  1254. return;
  1255. }
  1256. $gid = $group_info['gid'];
  1257. } else {
  1258. $gid = $user_info['gid'];
  1259. }
  1260. // Set uid and gid.
  1261. if ($uid != posix_getuid() || $gid != posix_getgid()) {
  1262. if (!posix_setgid($gid) || !posix_initgroups($user_info['name'], $gid) || !posix_setuid($uid)) {
  1263. static::log("Warning: change gid or uid fail.");
  1264. }
  1265. }
  1266. }
  1267. /**
  1268. * Set process name.
  1269. *
  1270. * @param string $title
  1271. * @return void
  1272. */
  1273. protected static function setProcessTitle($title)
  1274. {
  1275. // >=php 5.5
  1276. if (function_exists('cli_set_process_title')) {
  1277. @cli_set_process_title($title);
  1278. } // Need proctitle when php<=5.5 .
  1279. elseif (extension_loaded('proctitle') && function_exists('setproctitle')) {
  1280. @setproctitle($title);
  1281. }
  1282. }
  1283. /**
  1284. * Monitor all child processes.
  1285. *
  1286. * @return void
  1287. */
  1288. protected static function monitorWorkers()
  1289. {
  1290. if (static::$_OS === 'linux') {
  1291. static::monitorWorkersForLinux();
  1292. } else {
  1293. static::monitorWorkersForWindows();
  1294. }
  1295. }
  1296. /**
  1297. * Monitor all child processes.
  1298. *
  1299. * @return void
  1300. */
  1301. protected static function monitorWorkersForLinux()
  1302. {
  1303. static::$_status = static::STATUS_RUNNING;
  1304. while (1) {
  1305. // Calls signal handlers for pending signals.
  1306. pcntl_signal_dispatch();
  1307. // Suspends execution of the current process until a child has exited, or until a signal is delivered
  1308. $status = 0;
  1309. $pid = pcntl_wait($status, WUNTRACED);
  1310. // Calls signal handlers for pending signals again.
  1311. pcntl_signal_dispatch();
  1312. // If a child has already exited.
  1313. if ($pid > 0) {
  1314. // Find out witch worker process exited.
  1315. foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
  1316. if (isset($worker_pid_array[$pid])) {
  1317. $worker = static::$_workers[$worker_id];
  1318. // Exit status.
  1319. if ($status !== 0) {
  1320. static::log("worker[" . $worker->name . ":$pid] exit with status $status");
  1321. }
  1322. // For Statistics.
  1323. if (!isset(static::$_globalStatistics['worker_exit_info'][$worker_id][$status])) {
  1324. static::$_globalStatistics['worker_exit_info'][$worker_id][$status] = 0;
  1325. }
  1326. static::$_globalStatistics['worker_exit_info'][$worker_id][$status]++;
  1327. // Clear process data.
  1328. unset(static::$_pidMap[$worker_id][$pid]);
  1329. // Mark id is available.
  1330. $id = static::getId($worker_id, $pid);
  1331. static::$_idMap[$worker_id][$id] = 0;
  1332. break;
  1333. }
  1334. }
  1335. // Is still running state then fork a new worker process.
  1336. if (static::$_status !== static::STATUS_SHUTDOWN) {
  1337. static::forkWorkers();
  1338. // If reloading continue.
  1339. if (isset(static::$_pidsToRestart[$pid])) {
  1340. unset(static::$_pidsToRestart[$pid]);
  1341. static::reload();
  1342. }
  1343. } else {
  1344. // If shutdown state and all child processes exited then master process exit.
  1345. if (!static::getAllWorkerPids()) {
  1346. static::exitAndClearAll();
  1347. }
  1348. }
  1349. } else {
  1350. // If shutdown state and all child processes exited then master process exit.
  1351. if (static::$_status === static::STATUS_SHUTDOWN && !static::getAllWorkerPids()) {
  1352. static::exitAndClearAll();
  1353. }
  1354. }
  1355. }
  1356. }
  1357. /**
  1358. * Monitor all child processes.
  1359. *
  1360. * @return void
  1361. */
  1362. protected static function monitorWorkersForWindows()
  1363. {
  1364. Timer::add(0.5, "\\Workerman\\Worker::checkWorkerStatusForWindows");
  1365. static::$globalEvent->loop();
  1366. }
  1367. /**
  1368. * Exit current process.
  1369. *
  1370. * @return void
  1371. */
  1372. protected static function exitAndClearAll()
  1373. {
  1374. foreach (static::$_workers as $worker) {
  1375. $socket_name = $worker->getSocketName();
  1376. if ($worker->transport === 'unix' && $socket_name) {
  1377. list(, $address) = explode(':', $socket_name, 2);
  1378. @unlink($address);
  1379. }
  1380. }
  1381. @unlink(static::$pidFile);
  1382. static::log("Workerman[" . basename(static::$_startFile) . "] has been stopped");
  1383. if (static::$onMasterStop) {
  1384. call_user_func(static::$onMasterStop);
  1385. }
  1386. exit(0);
  1387. }
  1388. /**
  1389. * Execute reload.
  1390. *
  1391. * @return void
  1392. */
  1393. protected static function reload()
  1394. {
  1395. // For master process.
  1396. if (static::$_masterPid === posix_getpid()) {
  1397. // Set reloading state.
  1398. if (static::$_status !== static::STATUS_RELOADING && static::$_status !== static::STATUS_SHUTDOWN) {
  1399. static::log("Workerman[" . basename(static::$_startFile) . "] reloading");
  1400. static::$_status = static::STATUS_RELOADING;
  1401. // Try to emit onMasterReload callback.
  1402. if (static::$onMasterReload) {
  1403. try {
  1404. call_user_func(static::$onMasterReload);
  1405. } catch (\Exception $e) {
  1406. static::log($e);
  1407. exit(250);
  1408. } catch (\Error $e) {
  1409. static::log($e);
  1410. exit(250);
  1411. }
  1412. static::initId();
  1413. }
  1414. }
  1415. if (static::$_gracefulStop) {
  1416. $sig = SIGQUIT;
  1417. } else {
  1418. $sig = SIGUSR1;
  1419. }
  1420. // Send reload signal to all child processes.
  1421. $reloadable_pid_array = array();
  1422. foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
  1423. $worker = static::$_workers[$worker_id];
  1424. if ($worker->reloadable) {
  1425. foreach ($worker_pid_array as $pid) {
  1426. $reloadable_pid_array[$pid] = $pid;
  1427. }
  1428. } else {
  1429. foreach ($worker_pid_array as $pid) {
  1430. // Send reload signal to a worker process which reloadable is false.
  1431. posix_kill($pid, $sig);
  1432. }
  1433. }
  1434. }
  1435. // Get all pids that are waiting reload.
  1436. static::$_pidsToRestart = array_intersect(static::$_pidsToRestart, $reloadable_pid_array);
  1437. // Reload complete.
  1438. if (empty(static::$_pidsToRestart)) {
  1439. if (static::$_status !== static::STATUS_SHUTDOWN) {
  1440. static::$_status = static::STATUS_RUNNING;
  1441. }
  1442. return;
  1443. }
  1444. // Continue reload.
  1445. $one_worker_pid = current(static::$_pidsToRestart);
  1446. // Send reload signal to a worker process.
  1447. posix_kill($one_worker_pid, $sig);
  1448. // If the process does not exit after static::KILL_WORKER_TIMER_TIME seconds try to kill it.
  1449. if(!static::$_gracefulStop){
  1450. Timer::add(static::KILL_WORKER_TIMER_TIME, 'posix_kill', array($one_worker_pid, SIGKILL), false);
  1451. }
  1452. } // For child processes.
  1453. else {
  1454. reset(static::$_workers);
  1455. $worker = current(static::$_workers);
  1456. // Try to emit onWorkerReload callback.
  1457. if ($worker->onWorkerReload) {
  1458. try {
  1459. call_user_func($worker->onWorkerReload, $worker);
  1460. } catch (\Exception $e) {
  1461. static::log($e);
  1462. exit(250);
  1463. } catch (\Error $e) {
  1464. static::log($e);
  1465. exit(250);
  1466. }
  1467. }
  1468. if ($worker->reloadable) {
  1469. static::stopAll();
  1470. }
  1471. }
  1472. }
  1473. /**
  1474. * Stop.
  1475. *
  1476. * @return void
  1477. */
  1478. public static function stopAll()
  1479. {
  1480. static::$_status = static::STATUS_SHUTDOWN;
  1481. // For master process.
  1482. if (static::$_masterPid === posix_getpid()) {
  1483. static::log("Workerman[" . basename(static::$_startFile) . "] stopping ...");
  1484. $worker_pid_array = static::getAllWorkerPids();
  1485. // Send stop signal to all child processes.
  1486. if (static::$_gracefulStop) {
  1487. $sig = SIGTERM;
  1488. } else {
  1489. $sig = SIGINT;
  1490. }
  1491. foreach ($worker_pid_array as $worker_pid) {
  1492. posix_kill($worker_pid, $sig);
  1493. if(!static::$_gracefulStop){
  1494. Timer::add(static::KILL_WORKER_TIMER_TIME, 'posix_kill', array($worker_pid, SIGKILL), false);
  1495. }
  1496. }
  1497. // Remove statistics file.
  1498. if (is_file(static::$_statisticsFile)) {
  1499. @unlink(static::$_statisticsFile);
  1500. }
  1501. } // For child processes.
  1502. else {
  1503. // Execute exit.
  1504. foreach (static::$_workers as $worker) {
  1505. if(!$worker->stopping){
  1506. $worker->stop();
  1507. $worker->stopping = true;
  1508. }
  1509. }
  1510. if (!static::$_gracefulStop || ConnectionInterface::$statistics['connection_count'] <= 0) {
  1511. static::$_workers = array();
  1512. static::$globalEvent->destroy();
  1513. exit(0);
  1514. }
  1515. }
  1516. }
  1517. /**
  1518. * Get process status.
  1519. *
  1520. * @return number
  1521. */
  1522. public static function getStatus()
  1523. {
  1524. return static::$_status;
  1525. }
  1526. /**
  1527. * If stop gracefully.
  1528. *
  1529. * @return boolean
  1530. */
  1531. public static function getGracefulStop()
  1532. {
  1533. return static::$_gracefulStop;
  1534. }
  1535. /**
  1536. * Write statistics data to disk.
  1537. *
  1538. * @return void
  1539. */
  1540. protected static function writeStatisticsToStatusFile()
  1541. {
  1542. // For master process.
  1543. if (static::$_masterPid === posix_getpid()) {
  1544. $all_worker_info = array();
  1545. foreach(static::$_pidMap as $worker_id => $pid_array) {
  1546. /** @var /Workerman/Worker $worker */
  1547. $worker = static::$_workers[$worker_id];
  1548. foreach($pid_array as $pid) {
  1549. $all_worker_info[$pid] = array('name' => $worker->name, 'listen' => $worker->getSocketName());
  1550. }
  1551. }
  1552. file_put_contents(static::$_statisticsFile, json_encode($all_worker_info)."\n", FILE_APPEND);
  1553. $loadavg = function_exists('sys_getloadavg') ? array_map('round', sys_getloadavg(), array(2)) : array('-', '-', '-');
  1554. file_put_contents(static::$_statisticsFile,
  1555. "----------------------------------------------GLOBAL STATUS----------------------------------------------------\n", FILE_APPEND);
  1556. file_put_contents(static::$_statisticsFile,
  1557. 'Workerman version:' . static::VERSION . " PHP version:" . PHP_VERSION . "\n", FILE_APPEND);
  1558. file_put_contents(static::$_statisticsFile, 'start time:' . date('Y-m-d H:i:s',
  1559. static::$_globalStatistics['start_timestamp']) . ' run ' . floor((time() - static::$_globalStatistics['start_timestamp']) / (24 * 60 * 60)) . ' days ' . floor(((time() - static::$_globalStatistics['start_timestamp']) % (24 * 60 * 60)) / (60 * 60)) . " hours \n",
  1560. FILE_APPEND);
  1561. $load_str = 'load average: ' . implode(", ", $loadavg);
  1562. file_put_contents(static::$_statisticsFile,
  1563. str_pad($load_str, 33) . 'event-loop:' . static::getEventLoopName() . "\n", FILE_APPEND);
  1564. file_put_contents(static::$_statisticsFile,
  1565. count(static::$_pidMap) . ' workers ' . count(static::getAllWorkerPids()) . " processes\n",
  1566. FILE_APPEND);
  1567. file_put_contents(static::$_statisticsFile,
  1568. str_pad('worker_name', static::$_maxWorkerNameLength) . " exit_status exit_count\n", FILE_APPEND);
  1569. foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
  1570. $worker = static::$_workers[$worker_id];
  1571. if (isset(static::$_globalStatistics['worker_exit_info'][$worker_id])) {
  1572. foreach (static::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
  1573. file_put_contents(static::$_statisticsFile,
  1574. str_pad($worker->name, static::$_maxWorkerNameLength) . " " . str_pad($worker_exit_status,
  1575. 16) . " $worker_exit_count\n", FILE_APPEND);
  1576. }
  1577. } else {
  1578. file_put_contents(static::$_statisticsFile,
  1579. str_pad($worker->name, static::$_maxWorkerNameLength) . " " . str_pad(0, 16) . " 0\n",
  1580. FILE_APPEND);
  1581. }
  1582. }
  1583. file_put_contents(static::$_statisticsFile,
  1584. "----------------------------------------------PROCESS STATUS---------------------------------------------------\n",
  1585. FILE_APPEND);
  1586. file_put_contents(static::$_statisticsFile,
  1587. "pid\tmemory " . str_pad('listening', static::$_maxSocketNameLength) . " " . str_pad('worker_name',
  1588. static::$_maxWorkerNameLength) . " connections " . str_pad('send_fail', 9) . " "
  1589. . str_pad('timers', 8) . str_pad('total_request', 13) ." qps status\n", FILE_APPEND);
  1590. chmod(static::$_statisticsFile, 0722);
  1591. foreach (static::getAllWorkerPids() as $worker_pid) {
  1592. posix_kill($worker_pid, SIGUSR2);
  1593. }
  1594. return;
  1595. }
  1596. // For child processes.
  1597. reset(static::$_workers);
  1598. /** @var \Workerman\Worker $worker */
  1599. $worker = current(static::$_workers);
  1600. $worker_status_str = posix_getpid() . "\t" . str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M", 7)
  1601. . " " . str_pad($worker->getSocketName(), static::$_maxSocketNameLength) . " "
  1602. . str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name), static::$_maxWorkerNameLength)
  1603. . " ";
  1604. $worker_status_str .= str_pad(ConnectionInterface::$statistics['connection_count'], 11)
  1605. . " " . str_pad(ConnectionInterface::$statistics['send_fail'], 9)
  1606. . " " . str_pad(static::$globalEvent->getTimerCount(), 7)
  1607. . " " . str_pad(ConnectionInterface::$statistics['total_request'], 13) . "\n";
  1608. file_put_contents(static::$_statisticsFile, $worker_status_str, FILE_APPEND);
  1609. }
  1610. /**
  1611. * Write statistics data to disk.
  1612. *
  1613. * @return void
  1614. */
  1615. protected static function writeConnectionsStatisticsToStatusFile()
  1616. {
  1617. // For master process.
  1618. if (static::$_masterPid === posix_getpid()) {
  1619. file_put_contents(static::$_statisticsFile, "--------------------------------------------------------------------- WORKERMAN CONNECTION STATUS --------------------------------------------------------------------------------\n", FILE_APPEND);
  1620. file_put_contents(static::$_statisticsFile, "PID Worker CID Trans Protocol ipv4 ipv6 Recv-Q Send-Q Bytes-R Bytes-W Status Local Address Foreign Address\n", FILE_APPEND);
  1621. chmod(static::$_statisticsFile, 0722);
  1622. foreach (static::getAllWorkerPids() as $worker_pid) {
  1623. posix_kill($worker_pid, SIGIO);
  1624. }
  1625. return;
  1626. }
  1627. // For child processes.
  1628. $bytes_format = function($bytes)
  1629. {
  1630. if($bytes > 1024*1024*1024*1024) {
  1631. return round($bytes/(1024*1024*1024*1024), 1)."TB";
  1632. }
  1633. if($bytes > 1024*1024*1024) {
  1634. return round($bytes/(1024*1024*1024), 1)."GB";
  1635. }
  1636. if($bytes > 1024*1024) {
  1637. return round($bytes/(1024*1024), 1)."MB";
  1638. }
  1639. if($bytes > 1024) {
  1640. return round($bytes/(1024), 1)."KB";
  1641. }
  1642. return $bytes."B";
  1643. };
  1644. $pid = posix_getpid();
  1645. $str = '';
  1646. reset(static::$_workers);
  1647. $current_worker = current(static::$_workers);
  1648. $default_worker_name = $current_worker->name;
  1649. /** @var \Workerman\Worker $worker */
  1650. foreach(TcpConnection::$connections as $connection) {
  1651. /** @var \Workerman\Connection\TcpConnection $connection */
  1652. $transport = $connection->transport;
  1653. $ipv4 = $connection->isIpV4() ? ' 1' : ' 0';
  1654. $ipv6 = $connection->isIpV6() ? ' 1' : ' 0';
  1655. $recv_q = $bytes_format($connection->getRecvBufferQueueSize());
  1656. $send_q = $bytes_format($connection->getSendBufferQueueSize());
  1657. $local_address = trim($connection->getLocalAddress());
  1658. $remote_address = trim($connection->getRemoteAddress());
  1659. $state = $connection->getStatus(false);
  1660. $bytes_read = $bytes_format($connection->bytesRead);
  1661. $bytes_written = $bytes_format($connection->bytesWritten);
  1662. $id = $connection->id;
  1663. $protocol = $connection->protocol ? $connection->protocol : $connection->transport;
  1664. $pos = strrpos($protocol, '\\');
  1665. if ($pos) {
  1666. $protocol = substr($protocol, $pos+1);
  1667. }
  1668. if (strlen($protocol) > 15) {
  1669. $protocol = substr($protocol, 0, 13) . '..';
  1670. }
  1671. $worker_name = isset($connection->worker) ? $connection->worker->name : $default_worker_name;
  1672. if (strlen($worker_name) > 14) {
  1673. $worker_name = substr($worker_name, 0, 12) . '..';
  1674. }
  1675. $str .= str_pad($pid, 9) . str_pad($worker_name, 16) . str_pad($id, 10) . str_pad($transport, 8)
  1676. . str_pad($protocol, 16) . str_pad($ipv4, 7) . str_pad($ipv6, 7) . str_pad($recv_q, 13)
  1677. . str_pad($send_q, 13) . str_pad($bytes_read, 13) . str_pad($bytes_written, 13) . ' '
  1678. . str_pad($state, 14) . ' ' . str_pad($local_address, 22) . ' ' . str_pad($remote_address, 22) ."\n";
  1679. }
  1680. if ($str) {
  1681. file_put_contents(static::$_statisticsFile, $str, FILE_APPEND);
  1682. }
  1683. }
  1684. /**
  1685. * Check errors when current process exited.
  1686. *
  1687. * @return void
  1688. */
  1689. public static function checkErrors()
  1690. {
  1691. if (static::STATUS_SHUTDOWN != static::$_status) {
  1692. $error_msg = static::$_OS === 'linx' ? 'Worker['. posix_getpid() .'] process terminated' : 'Worker process terminated';
  1693. $errors = error_get_last();
  1694. if ($errors && ($errors['type'] === E_ERROR ||
  1695. $errors['type'] === E_PARSE ||
  1696. $errors['type'] === E_CORE_ERROR ||
  1697. $errors['type'] === E_COMPILE_ERROR ||
  1698. $errors['type'] === E_RECOVERABLE_ERROR)
  1699. ) {
  1700. $error_msg .= ' with ERROR: ' . static::getErrorType($errors['type']) . " \"{$errors['message']} in {$errors['file']} on line {$errors['line']}\"";
  1701. }
  1702. static::log($error_msg);
  1703. }
  1704. }
  1705. /**
  1706. * Get error message by error code.
  1707. *
  1708. * @param integer $type
  1709. * @return string
  1710. */
  1711. protected static function getErrorType($type)
  1712. {
  1713. switch ($type) {
  1714. case E_ERROR: // 1 //
  1715. return 'E_ERROR';
  1716. case E_WARNING: // 2 //
  1717. return 'E_WARNING';
  1718. case E_PARSE: // 4 //
  1719. return 'E_PARSE';
  1720. case E_NOTICE: // 8 //
  1721. return 'E_NOTICE';
  1722. case E_CORE_ERROR: // 16 //
  1723. return 'E_CORE_ERROR';
  1724. case E_CORE_WARNING: // 32 //
  1725. return 'E_CORE_WARNING';
  1726. case E_COMPILE_ERROR: // 64 //
  1727. return 'E_COMPILE_ERROR';
  1728. case E_COMPILE_WARNING: // 128 //
  1729. return 'E_COMPILE_WARNING';
  1730. case E_USER_ERROR: // 256 //
  1731. return 'E_USER_ERROR';
  1732. case E_USER_WARNING: // 512 //
  1733. return 'E_USER_WARNING';
  1734. case E_USER_NOTICE: // 1024 //
  1735. return 'E_USER_NOTICE';
  1736. case E_STRICT: // 2048 //
  1737. return 'E_STRICT';
  1738. case E_RECOVERABLE_ERROR: // 4096 //
  1739. return 'E_RECOVERABLE_ERROR';
  1740. case E_DEPRECATED: // 8192 //
  1741. return 'E_DEPRECATED';
  1742. case E_USER_DEPRECATED: // 16384 //
  1743. return 'E_USER_DEPRECATED';
  1744. }
  1745. return "";
  1746. }
  1747. /**
  1748. * Log.
  1749. *
  1750. * @param string $msg
  1751. * @return void
  1752. */
  1753. public static function log($msg)
  1754. {
  1755. $msg = $msg . "\n";
  1756. if (!static::$daemonize) {
  1757. static::safeEcho($msg);
  1758. }
  1759. file_put_contents((string)static::$logFile, date('Y-m-d H:i:s') . ' ' . 'pid:'
  1760. . (static::$_OS === 'linux' ? posix_getpid() : 1) . ' ' . $msg, FILE_APPEND | LOCK_EX);
  1761. }
  1762. /**
  1763. * Safe Echo.
  1764. *
  1765. * @param $msg
  1766. */
  1767. public static function safeEcho($msg)
  1768. {
  1769. if (!function_exists('posix_isatty') || posix_isatty(STDOUT)) {
  1770. echo $msg;
  1771. }
  1772. }
  1773. /**
  1774. * Construct.
  1775. *
  1776. * @param string $socket_name
  1777. * @param array $context_option
  1778. */
  1779. public function __construct($socket_name = '', $context_option = array())
  1780. {
  1781. // Save all worker instances.
  1782. $this->workerId = spl_object_hash($this);
  1783. static::$_workers[$this->workerId] = $this;
  1784. static::$_pidMap[$this->workerId] = array();
  1785. // Get autoload root path.
  1786. $backtrace = debug_backtrace();
  1787. $this->_autoloadRootPath = dirname($backtrace[0]['file']);
  1788. // Context for socket.
  1789. if ($socket_name) {
  1790. $this->_socketName = $socket_name;
  1791. if (!isset($context_option['socket']['backlog'])) {
  1792. $context_option['socket']['backlog'] = static::DEFAULT_BACKLOG;
  1793. }
  1794. $this->_context = stream_context_create($context_option);
  1795. }
  1796. }
  1797. /**
  1798. * Listen.
  1799. *
  1800. * @throws Exception
  1801. */
  1802. public function listen()
  1803. {
  1804. if (!$this->_socketName) {
  1805. return;
  1806. }
  1807. // Autoload.
  1808. Autoloader::setRootPath($this->_autoloadRootPath);
  1809. if (!$this->_mainSocket) {
  1810. // Get the application layer communication protocol and listening address.
  1811. list($scheme, $address) = explode(':', $this->_socketName, 2);
  1812. // Check application layer protocol class.
  1813. if (!isset(static::$_builtinTransports[$scheme])) {
  1814. $scheme = ucfirst($scheme);
  1815. $this->protocol = substr($scheme,0,1)==='\\' ? $scheme : '\\Protocols\\' . $scheme;
  1816. if (!class_exists($this->protocol)) {
  1817. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  1818. if (!class_exists($this->protocol)) {
  1819. throw new Exception("class \\Protocols\\$scheme not exist");
  1820. }
  1821. }
  1822. if (!isset(static::$_builtinTransports[$this->transport])) {
  1823. throw new \Exception('Bad worker->transport ' . var_export($this->transport, true));
  1824. }
  1825. } else {
  1826. $this->transport = $scheme;
  1827. }
  1828. $local_socket = static::$_builtinTransports[$this->transport] . ":" . $address;
  1829. // Flag.
  1830. $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
  1831. $errno = 0;
  1832. $errmsg = '';
  1833. // SO_REUSEPORT.
  1834. if ($this->reusePort) {
  1835. stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
  1836. }
  1837. // Create an Internet or Unix domain server socket.
  1838. $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context);
  1839. if (!$this->_mainSocket) {
  1840. throw new Exception($errmsg);
  1841. }
  1842. if ($this->transport === 'ssl') {
  1843. stream_socket_enable_crypto($this->_mainSocket, false);
  1844. } elseif ($this->transport === 'unix') {
  1845. $socketFile = substr($address, 2);
  1846. if ($this->user) {
  1847. chown($socketFile, $this->user);
  1848. }
  1849. if ($this->group) {
  1850. chgrp($socketFile, $this->group);
  1851. }
  1852. }
  1853. // Try to open keepalive for tcp and disable Nagle algorithm.
  1854. if (function_exists('socket_import_stream') && static::$_builtinTransports[$this->transport] === 'tcp') {
  1855. $socket = socket_import_stream($this->_mainSocket);
  1856. @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
  1857. @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
  1858. }
  1859. // Non blocking.
  1860. stream_set_blocking($this->_mainSocket, 0);
  1861. }
  1862. $this->resumeAccept();
  1863. }
  1864. /**
  1865. * Unlisten.
  1866. *
  1867. * @return void
  1868. */
  1869. public function unlisten() {
  1870. $this->pauseAccept();
  1871. if ($this->_mainSocket) {
  1872. @fclose($this->_mainSocket);
  1873. $this->_mainSocket = null;
  1874. }
  1875. }
  1876. /**
  1877. * Pause accept new connections.
  1878. *
  1879. * @return void
  1880. */
  1881. public function pauseAccept()
  1882. {
  1883. if (static::$globalEvent && false === $this->_pauseAccept && $this->_mainSocket) {
  1884. static::$globalEvent->del($this->_mainSocket, EventInterface::EV_READ);
  1885. $this->_pauseAccept = true;
  1886. }
  1887. }
  1888. /**
  1889. * Resume accept new connections.
  1890. *
  1891. * @return void
  1892. */
  1893. public function resumeAccept()
  1894. {
  1895. // Register a listener to be notified when server socket is ready to read.
  1896. if (static::$globalEvent && true === $this->_pauseAccept && $this->_mainSocket) {
  1897. if ($this->transport !== 'udp') {
  1898. static::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptConnection'));
  1899. } else {
  1900. static::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
  1901. array($this, 'acceptUdpConnection'));
  1902. }
  1903. $this->_pauseAccept = false;
  1904. }
  1905. }
  1906. /**
  1907. * Get socket name.
  1908. *
  1909. * @return string
  1910. */
  1911. public function getSocketName()
  1912. {
  1913. return $this->_socketName ? lcfirst($this->_socketName) : 'none';
  1914. }
  1915. /**
  1916. * Run worker instance.
  1917. *
  1918. * @return void
  1919. */
  1920. public function run()
  1921. {
  1922. //Update process state.
  1923. static::$_status = static::STATUS_RUNNING;
  1924. // Register shutdown function for checking errors.
  1925. register_shutdown_function(array("\\Workerman\\Worker", 'checkErrors'));
  1926. // Set autoload root path.
  1927. Autoloader::setRootPath($this->_autoloadRootPath);
  1928. // Create a global event loop.
  1929. if (!static::$globalEvent) {
  1930. $event_loop_class = static::getEventLoopName();
  1931. static::$globalEvent = new $event_loop_class;
  1932. $this->resumeAccept();
  1933. }
  1934. // Reinstall signal.
  1935. static::reinstallSignal();
  1936. // Init Timer.
  1937. Timer::init(static::$globalEvent);
  1938. // Set an empty onMessage callback.
  1939. if (empty($this->onMessage)) {
  1940. $this->onMessage = function () {};
  1941. }
  1942. // Try to emit onWorkerStart callback.
  1943. if ($this->onWorkerStart) {
  1944. try {
  1945. call_user_func($this->onWorkerStart, $this);
  1946. } catch (\Exception $e) {
  1947. static::log($e);
  1948. // Avoid rapid infinite loop exit.
  1949. sleep(1);
  1950. exit(250);
  1951. } catch (\Error $e) {
  1952. static::log($e);
  1953. // Avoid rapid infinite loop exit.
  1954. sleep(1);
  1955. exit(250);
  1956. }
  1957. }
  1958. // Main loop.
  1959. static::$globalEvent->loop();
  1960. }
  1961. /**
  1962. * Stop current worker instance.
  1963. *
  1964. * @return void
  1965. */
  1966. public function stop()
  1967. {
  1968. // Try to emit onWorkerStop callback.
  1969. if ($this->onWorkerStop) {
  1970. try {
  1971. call_user_func($this->onWorkerStop, $this);
  1972. } catch (\Exception $e) {
  1973. static::log($e);
  1974. exit(250);
  1975. } catch (\Error $e) {
  1976. static::log($e);
  1977. exit(250);
  1978. }
  1979. }
  1980. // Remove listener for server socket.
  1981. $this->unlisten();
  1982. // Close all connections for the worker.
  1983. if (!static::$_gracefulStop) {
  1984. foreach ($this->connections as $connection) {
  1985. $connection->close();
  1986. }
  1987. }
  1988. // Clear callback.
  1989. $this->onMessage = $this->onClose = $this->onError = $this->onBufferDrain = $this->onBufferFull = null;
  1990. }
  1991. /**
  1992. * Accept a connection.
  1993. *
  1994. * @param resource $socket
  1995. * @return void
  1996. */
  1997. public function acceptConnection($socket)
  1998. {
  1999. // Accept a connection on server socket.
  2000. $new_socket = @stream_socket_accept($socket, 0, $remote_address);
  2001. // Thundering herd.
  2002. if (!$new_socket) {
  2003. return;
  2004. }
  2005. // TcpConnection.
  2006. $connection = new TcpConnection($new_socket, $remote_address);
  2007. $this->connections[$connection->id] = $connection;
  2008. $connection->worker = $this;
  2009. $connection->protocol = $this->protocol;
  2010. $connection->transport = $this->transport;
  2011. $connection->onMessage = $this->onMessage;
  2012. $connection->onClose = $this->onClose;
  2013. $connection->onError = $this->onError;
  2014. $connection->onBufferDrain = $this->onBufferDrain;
  2015. $connection->onBufferFull = $this->onBufferFull;
  2016. // Try to emit onConnect callback.
  2017. if ($this->onConnect) {
  2018. try {
  2019. call_user_func($this->onConnect, $connection);
  2020. } catch (\Exception $e) {
  2021. static::log($e);
  2022. exit(250);
  2023. } catch (\Error $e) {
  2024. static::log($e);
  2025. exit(250);
  2026. }
  2027. }
  2028. }
  2029. /**
  2030. * For udp package.
  2031. *
  2032. * @param resource $socket
  2033. * @return bool
  2034. */
  2035. public function acceptUdpConnection($socket)
  2036. {
  2037. $recv_buffer = stream_socket_recvfrom($socket, static::MAX_UDP_PACKAGE_SIZE, 0, $remote_address);
  2038. if (false === $recv_buffer || empty($remote_address)) {
  2039. return false;
  2040. }
  2041. // UdpConnection.
  2042. $connection = new UdpConnection($socket, $remote_address);
  2043. $connection->protocol = $this->protocol;
  2044. if ($this->onMessage) {
  2045. if ($this->protocol !== null) {
  2046. /** @var \Workerman\Protocols\ProtocolInterface $parser */
  2047. $parser = $this->protocol;
  2048. $recv_buffer = $parser::decode($recv_buffer, $connection);
  2049. // Discard bad packets.
  2050. if ($recv_buffer === false)
  2051. return true;
  2052. }
  2053. ConnectionInterface::$statistics['total_request']++;
  2054. try {
  2055. call_user_func($this->onMessage, $connection, $recv_buffer);
  2056. } catch (\Exception $e) {
  2057. static::log($e);
  2058. exit(250);
  2059. } catch (\Error $e) {
  2060. static::log($e);
  2061. exit(250);
  2062. }
  2063. }
  2064. return true;
  2065. }
  2066. }