Worker.php 70 KB

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