Worker.php 70 KB

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