Worker.php 69 KB

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