Worker.php 68 KB

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